three.webgpu.js 1.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348
  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, UnsignedInt101111Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'aoMapIntensity',
  16. 'attenuationColor',
  17. 'attenuationDistance',
  18. 'bumpMap',
  19. 'clearcoat',
  20. 'clearcoatMap',
  21. 'clearcoatNormalMap',
  22. 'clearcoatNormalScale',
  23. 'clearcoatRoughness',
  24. 'color',
  25. 'dispersion',
  26. 'displacementMap',
  27. 'emissive',
  28. 'emissiveIntensity',
  29. 'emissiveMap',
  30. 'envMap',
  31. 'envMapIntensity',
  32. 'gradientMap',
  33. 'ior',
  34. 'iridescence',
  35. 'iridescenceIOR',
  36. 'iridescenceMap',
  37. 'iridescenceThicknessMap',
  38. 'lightMap',
  39. 'lightMapIntensity',
  40. 'map',
  41. 'matcap',
  42. 'metalness',
  43. 'metalnessMap',
  44. 'normalMap',
  45. 'normalScale',
  46. 'opacity',
  47. 'roughness',
  48. 'roughnessMap',
  49. 'sheen',
  50. 'sheenColor',
  51. 'sheenColorMap',
  52. 'sheenRoughnessMap',
  53. 'shininess',
  54. 'specular',
  55. 'specularColor',
  56. 'specularColorMap',
  57. 'specularIntensity',
  58. 'specularIntensityMap',
  59. 'specularMap',
  60. 'thickness',
  61. 'transmission',
  62. 'transmissionMap'
  63. ];
  64. /**
  65. * A WeakMap to cache lights data for node materials.
  66. * Cache lights data by render ID to avoid unnecessary recalculations.
  67. *
  68. * @private
  69. * @type {WeakMap<LightsNode,Object>}
  70. */
  71. const _lightsCache = new WeakMap();
  72. /**
  73. * This class is used by {@link WebGPURenderer} as management component.
  74. * It's primary purpose is to determine whether render objects require a
  75. * refresh right before they are going to be rendered or not.
  76. */
  77. class NodeMaterialObserver {
  78. /**
  79. * Constructs a new node material observer.
  80. *
  81. * @param {NodeBuilder} builder - The node builder.
  82. */
  83. constructor( builder ) {
  84. /**
  85. * A node material can be used by more than one render object so the
  86. * monitor must maintain a list of render objects.
  87. *
  88. * @type {WeakMap<RenderObject,Object>}
  89. */
  90. this.renderObjects = new WeakMap();
  91. /**
  92. * Whether the material uses node objects or not.
  93. *
  94. * @type {boolean}
  95. */
  96. this.hasNode = this.containsNode( builder );
  97. /**
  98. * Whether the node builder's 3D object is animated or not.
  99. *
  100. * @type {boolean}
  101. */
  102. this.hasAnimation = builder.object.isSkinnedMesh === true;
  103. /**
  104. * A list of all possible material uniforms
  105. *
  106. * @type {Array<string>}
  107. */
  108. this.refreshUniforms = refreshUniforms;
  109. /**
  110. * Holds the current render ID from the node frame.
  111. *
  112. * @type {number}
  113. * @default 0
  114. */
  115. this.renderId = 0;
  116. }
  117. /**
  118. * Returns `true` if the given render object is verified for the first time of this observer.
  119. *
  120. * @param {RenderObject} renderObject - The render object.
  121. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  122. */
  123. firstInitialization( renderObject ) {
  124. const hasInitialized = this.renderObjects.has( renderObject );
  125. if ( hasInitialized === false ) {
  126. this.getRenderObjectData( renderObject );
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns `true` if the current rendering produces motion vectors.
  133. *
  134. * @param {Renderer} renderer - The renderer.
  135. * @return {boolean} Whether the current rendering produces motion vectors or not.
  136. */
  137. needsVelocity( renderer ) {
  138. const mrt = renderer.getMRT();
  139. return ( mrt !== null && mrt.has( 'velocity' ) );
  140. }
  141. /**
  142. * Returns monitoring data for the given render object.
  143. *
  144. * @param {RenderObject} renderObject - The render object.
  145. * @return {Object} The monitoring data.
  146. */
  147. getRenderObjectData( renderObject ) {
  148. let data = this.renderObjects.get( renderObject );
  149. if ( data === undefined ) {
  150. const { geometry, material, object } = renderObject;
  151. data = {
  152. material: this.getMaterialData( material ),
  153. geometry: {
  154. id: geometry.id,
  155. attributes: this.getAttributesData( geometry.attributes ),
  156. indexVersion: geometry.index ? geometry.index.version : null,
  157. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  158. },
  159. worldMatrix: object.matrixWorld.clone()
  160. };
  161. if ( object.center ) {
  162. data.center = object.center.clone();
  163. }
  164. if ( object.morphTargetInfluences ) {
  165. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  166. }
  167. if ( renderObject.bundle !== null ) {
  168. data.version = renderObject.bundle.version;
  169. }
  170. if ( data.material.transmission > 0 ) {
  171. const { width, height } = renderObject.context;
  172. data.bufferWidth = width;
  173. data.bufferHeight = height;
  174. }
  175. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  176. this.renderObjects.set( renderObject, data );
  177. }
  178. return data;
  179. }
  180. /**
  181. * Returns an attribute data structure holding the attributes versions for
  182. * monitoring.
  183. *
  184. * @param {Object} attributes - The geometry attributes.
  185. * @return {Object} An object for monitoring the versions of attributes.
  186. */
  187. getAttributesData( attributes ) {
  188. const attributesData = {};
  189. for ( const name in attributes ) {
  190. const attribute = attributes[ name ];
  191. attributesData[ name ] = {
  192. version: attribute.version
  193. };
  194. }
  195. return attributesData;
  196. }
  197. /**
  198. * Returns `true` if the node builder's material uses
  199. * node properties.
  200. *
  201. * @param {NodeBuilder} builder - The current node builder.
  202. * @return {boolean} Whether the node builder's material uses node properties or not.
  203. */
  204. containsNode( builder ) {
  205. const material = builder.material;
  206. for ( const property in material ) {
  207. if ( material[ property ] && material[ property ].isNode )
  208. return true;
  209. }
  210. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  211. return true;
  212. return false;
  213. }
  214. /**
  215. * Returns a material data structure holding the material property values for
  216. * monitoring.
  217. *
  218. * @param {Material} material - The material.
  219. * @return {Object} An object for monitoring material properties.
  220. */
  221. getMaterialData( material ) {
  222. const data = {};
  223. for ( const property of this.refreshUniforms ) {
  224. const value = material[ property ];
  225. if ( value === null || value === undefined ) continue;
  226. if ( typeof value === 'object' && value.clone !== undefined ) {
  227. if ( value.isTexture === true ) {
  228. data[ property ] = { id: value.id, version: value.version };
  229. } else {
  230. data[ property ] = value.clone();
  231. }
  232. } else {
  233. data[ property ] = value;
  234. }
  235. }
  236. return data;
  237. }
  238. /**
  239. * Returns `true` if the given render object has not changed its state.
  240. *
  241. * @param {RenderObject} renderObject - The render object.
  242. * @param {Array<Light>} lightsData - The current material lights.
  243. * @return {boolean} Whether the given render object has changed its state or not.
  244. */
  245. equals( renderObject, lightsData ) {
  246. const { object, material, geometry } = renderObject;
  247. const renderObjectData = this.getRenderObjectData( renderObject );
  248. // world matrix
  249. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  250. renderObjectData.worldMatrix.copy( object.matrixWorld );
  251. return false;
  252. }
  253. // material
  254. const materialData = renderObjectData.material;
  255. for ( const property in materialData ) {
  256. const value = materialData[ property ];
  257. const mtlValue = material[ property ];
  258. if ( value.equals !== undefined ) {
  259. if ( value.equals( mtlValue ) === false ) {
  260. value.copy( mtlValue );
  261. return false;
  262. }
  263. } else if ( mtlValue.isTexture === true ) {
  264. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  265. value.id = mtlValue.id;
  266. value.version = mtlValue.version;
  267. return false;
  268. }
  269. } else if ( value !== mtlValue ) {
  270. materialData[ property ] = mtlValue;
  271. return false;
  272. }
  273. }
  274. if ( materialData.transmission > 0 ) {
  275. const { width, height } = renderObject.context;
  276. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  277. renderObjectData.bufferWidth = width;
  278. renderObjectData.bufferHeight = height;
  279. return false;
  280. }
  281. }
  282. // geometry
  283. const storedGeometryData = renderObjectData.geometry;
  284. const attributes = geometry.attributes;
  285. const storedAttributes = storedGeometryData.attributes;
  286. const storedAttributeNames = Object.keys( storedAttributes );
  287. const currentAttributeNames = Object.keys( attributes );
  288. if ( storedGeometryData.id !== geometry.id ) {
  289. storedGeometryData.id = geometry.id;
  290. return false;
  291. }
  292. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  293. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  294. return false;
  295. }
  296. // compare each attribute
  297. for ( const name of storedAttributeNames ) {
  298. const storedAttributeData = storedAttributes[ name ];
  299. const attribute = attributes[ name ];
  300. if ( attribute === undefined ) {
  301. // attribute was removed
  302. delete storedAttributes[ name ];
  303. return false;
  304. }
  305. if ( storedAttributeData.version !== attribute.version ) {
  306. storedAttributeData.version = attribute.version;
  307. return false;
  308. }
  309. }
  310. // check index
  311. const index = geometry.index;
  312. const storedIndexVersion = storedGeometryData.indexVersion;
  313. const currentIndexVersion = index ? index.version : null;
  314. if ( storedIndexVersion !== currentIndexVersion ) {
  315. storedGeometryData.indexVersion = currentIndexVersion;
  316. return false;
  317. }
  318. // check drawRange
  319. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  320. storedGeometryData.drawRange.start = geometry.drawRange.start;
  321. storedGeometryData.drawRange.count = geometry.drawRange.count;
  322. return false;
  323. }
  324. // morph targets
  325. if ( renderObjectData.morphTargetInfluences ) {
  326. let morphChanged = false;
  327. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  328. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  329. morphChanged = true;
  330. }
  331. }
  332. if ( morphChanged ) return true;
  333. }
  334. // lights
  335. if ( renderObjectData.lights ) {
  336. for ( let i = 0; i < lightsData.length; i ++ ) {
  337. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  338. return false;
  339. }
  340. }
  341. }
  342. // center
  343. if ( renderObjectData.center ) {
  344. if ( renderObjectData.center.equals( object.center ) === false ) {
  345. renderObjectData.center.copy( object.center );
  346. return true;
  347. }
  348. }
  349. // bundle
  350. if ( renderObject.bundle !== null ) {
  351. renderObjectData.version = renderObject.bundle.version;
  352. }
  353. return true;
  354. }
  355. /**
  356. * Returns the lights data for the given material lights.
  357. *
  358. * @param {Array<Light>} materialLights - The material lights.
  359. * @return {Array<Object>} The lights data for the given material lights.
  360. */
  361. getLightsData( materialLights ) {
  362. const lights = [];
  363. for ( const light of materialLights ) {
  364. if ( light.isSpotLight === true && light.map !== null ) {
  365. // only add lights that have a map
  366. lights.push( { map: light.map.version } );
  367. }
  368. }
  369. return lights;
  370. }
  371. /**
  372. * Returns the lights for the given lights node and render ID.
  373. *
  374. * @param {LightsNode} lightsNode - The lights node.
  375. * @param {number} renderId - The render ID.
  376. * @return {Array} The lights for the given lights node and render ID.
  377. */
  378. getLights( lightsNode, renderId ) {
  379. if ( _lightsCache.has( lightsNode ) ) {
  380. const cached = _lightsCache.get( lightsNode );
  381. if ( cached.renderId === renderId ) {
  382. return cached.lightsData;
  383. }
  384. }
  385. const lightsData = this.getLightsData( lightsNode.getLights() );
  386. _lightsCache.set( lightsNode, { renderId, lightsData } );
  387. return lightsData;
  388. }
  389. /**
  390. * Checks if the given render object requires a refresh.
  391. *
  392. * @param {RenderObject} renderObject - The render object.
  393. * @param {NodeFrame} nodeFrame - The current node frame.
  394. * @return {boolean} Whether the given render object requires a refresh or not.
  395. */
  396. needsRefresh( renderObject, nodeFrame ) {
  397. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  398. return true;
  399. const { renderId } = nodeFrame;
  400. if ( this.renderId !== renderId ) {
  401. this.renderId = renderId;
  402. return true;
  403. }
  404. const isStatic = renderObject.object.static === true;
  405. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  406. if ( isStatic || isBundle )
  407. return false;
  408. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  409. const notEqual = this.equals( renderObject, lightsData ) !== true;
  410. return notEqual;
  411. }
  412. }
  413. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  414. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  415. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  416. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  417. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  418. function cyrb53( value, seed = 0 ) {
  419. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  420. if ( value instanceof Array ) {
  421. for ( let i = 0, val; i < value.length; i ++ ) {
  422. val = value[ i ];
  423. h1 = Math.imul( h1 ^ val, 2654435761 );
  424. h2 = Math.imul( h2 ^ val, 1597334677 );
  425. }
  426. } else {
  427. for ( let i = 0, ch; i < value.length; i ++ ) {
  428. ch = value.charCodeAt( i );
  429. h1 = Math.imul( h1 ^ ch, 2654435761 );
  430. h2 = Math.imul( h2 ^ ch, 1597334677 );
  431. }
  432. }
  433. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  434. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  435. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  436. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  437. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  438. }
  439. /**
  440. * Computes a hash for the given string.
  441. *
  442. * @method
  443. * @param {string} str - The string to be hashed.
  444. * @return {number} The hash.
  445. */
  446. const hashString = ( str ) => cyrb53( str );
  447. /**
  448. * Computes a hash for the given array.
  449. *
  450. * @method
  451. * @param {Array<number>} array - The array to be hashed.
  452. * @return {number} The hash.
  453. */
  454. const hashArray = ( array ) => cyrb53( array );
  455. /**
  456. * Computes a hash for the given list of parameters.
  457. *
  458. * @method
  459. * @param {...number} params - A list of parameters.
  460. * @return {number} The hash.
  461. */
  462. const hash$1 = ( ...params ) => cyrb53( params );
  463. /**
  464. * Computes a cache key for the given node.
  465. *
  466. * @method
  467. * @param {Object|Node} object - The object to be hashed.
  468. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  469. * @return {number} The hash.
  470. */
  471. function getCacheKey$1( object, force = false ) {
  472. const values = [];
  473. if ( object.isNode === true ) {
  474. values.push( object.id );
  475. object = object.getSelf();
  476. }
  477. for ( const { property, childNode } of getNodeChildren( object ) ) {
  478. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  479. }
  480. return cyrb53( values );
  481. }
  482. /**
  483. * This generator function can be used to iterate over the node children
  484. * of the given object.
  485. *
  486. * @generator
  487. * @param {Object} node - The object to be hashed.
  488. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  489. * @yields {Object} A result node holding the property, index (if available) and the child node.
  490. */
  491. function* getNodeChildren( node, toJSON = false ) {
  492. for ( const property in node ) {
  493. // Ignore private properties.
  494. if ( property.startsWith( '_' ) === true ) continue;
  495. const object = node[ property ];
  496. if ( Array.isArray( object ) === true ) {
  497. for ( let i = 0; i < object.length; i ++ ) {
  498. const child = object[ i ];
  499. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  500. yield { property, index: i, childNode: child };
  501. }
  502. }
  503. } else if ( object && object.isNode === true ) {
  504. yield { property, childNode: object };
  505. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  506. for ( const subProperty in object ) {
  507. // Ignore private properties.
  508. if ( subProperty.startsWith( '_' ) === true ) continue;
  509. const child = object[ subProperty ];
  510. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  511. yield { property, index: subProperty, childNode: child };
  512. }
  513. }
  514. }
  515. }
  516. }
  517. const typeFromLength = /*@__PURE__*/ new Map( [
  518. [ 1, 'float' ],
  519. [ 2, 'vec2' ],
  520. [ 3, 'vec3' ],
  521. [ 4, 'vec4' ],
  522. [ 9, 'mat3' ],
  523. [ 16, 'mat4' ]
  524. ] );
  525. const dataFromObject = /*@__PURE__*/ new WeakMap();
  526. /**
  527. * Returns the data type for the given the length.
  528. *
  529. * @method
  530. * @param {number} length - The length.
  531. * @return {string} The data type.
  532. */
  533. function getTypeFromLength( length ) {
  534. return typeFromLength.get( length );
  535. }
  536. /**
  537. * Returns the typed array for the given data type.
  538. *
  539. * @method
  540. * @param {string} type - The data type.
  541. * @return {TypedArray} The typed array.
  542. */
  543. function getTypedArrayFromType( type ) {
  544. // Handle component type for vectors and matrices
  545. if ( /[iu]?vec\d/.test( type ) ) {
  546. // Handle int vectors
  547. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  548. // Handle uint vectors
  549. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  550. // Default to float vectors
  551. return Float32Array;
  552. }
  553. // Handle matrices (always float)
  554. if ( /mat\d/.test( type ) ) return Float32Array;
  555. // Basic types
  556. if ( /float/.test( type ) ) return Float32Array;
  557. if ( /uint/.test( type ) ) return Uint32Array;
  558. if ( /int/.test( type ) ) return Int32Array;
  559. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  560. }
  561. /**
  562. * Returns the length for the given data type.
  563. *
  564. * @method
  565. * @param {string} type - The data type.
  566. * @return {number} The length.
  567. */
  568. function getLengthFromType( type ) {
  569. if ( /float|int|uint/.test( type ) ) return 1;
  570. if ( /vec2/.test( type ) ) return 2;
  571. if ( /vec3/.test( type ) ) return 3;
  572. if ( /vec4/.test( type ) ) return 4;
  573. if ( /mat2/.test( type ) ) return 4;
  574. if ( /mat3/.test( type ) ) return 9;
  575. if ( /mat4/.test( type ) ) return 16;
  576. console.error( 'THREE.TSL: Unsupported type:', type );
  577. }
  578. /**
  579. * Returns the gpu memory length for the given data type.
  580. *
  581. * @method
  582. * @param {string} type - The data type.
  583. * @return {number} The length.
  584. */
  585. function getMemoryLengthFromType( type ) {
  586. if ( /float|int|uint/.test( type ) ) return 1;
  587. if ( /vec2/.test( type ) ) return 2;
  588. if ( /vec3/.test( type ) ) return 3;
  589. if ( /vec4/.test( type ) ) return 4;
  590. if ( /mat2/.test( type ) ) return 4;
  591. if ( /mat3/.test( type ) ) return 12;
  592. if ( /mat4/.test( type ) ) return 16;
  593. console.error( 'THREE.TSL: Unsupported type:', type );
  594. }
  595. /**
  596. * Returns the byte boundary for the given data type.
  597. *
  598. * @method
  599. * @param {string} type - The data type.
  600. * @return {number} The byte boundary.
  601. */
  602. function getByteBoundaryFromType( type ) {
  603. if ( /float|int|uint/.test( type ) ) return 4;
  604. if ( /vec2/.test( type ) ) return 8;
  605. if ( /vec3/.test( type ) ) return 16;
  606. if ( /vec4/.test( type ) ) return 16;
  607. if ( /mat2/.test( type ) ) return 8;
  608. if ( /mat3/.test( type ) ) return 48;
  609. if ( /mat4/.test( type ) ) return 64;
  610. console.error( 'THREE.TSL: Unsupported type:', type );
  611. }
  612. /**
  613. * Returns the data type for the given value.
  614. *
  615. * @method
  616. * @param {any} value - The value.
  617. * @return {?string} The data type.
  618. */
  619. function getValueType( value ) {
  620. if ( value === undefined || value === null ) return null;
  621. const typeOf = typeof value;
  622. if ( value.isNode === true ) {
  623. return 'node';
  624. } else if ( typeOf === 'number' ) {
  625. return 'float';
  626. } else if ( typeOf === 'boolean' ) {
  627. return 'bool';
  628. } else if ( typeOf === 'string' ) {
  629. return 'string';
  630. } else if ( typeOf === 'function' ) {
  631. return 'shader';
  632. } else if ( value.isVector2 === true ) {
  633. return 'vec2';
  634. } else if ( value.isVector3 === true ) {
  635. return 'vec3';
  636. } else if ( value.isVector4 === true ) {
  637. return 'vec4';
  638. } else if ( value.isMatrix2 === true ) {
  639. return 'mat2';
  640. } else if ( value.isMatrix3 === true ) {
  641. return 'mat3';
  642. } else if ( value.isMatrix4 === true ) {
  643. return 'mat4';
  644. } else if ( value.isColor === true ) {
  645. return 'color';
  646. } else if ( value instanceof ArrayBuffer ) {
  647. return 'ArrayBuffer';
  648. }
  649. return null;
  650. }
  651. /**
  652. * Returns the value/object for the given data type and parameters.
  653. *
  654. * @method
  655. * @param {string} type - The given type.
  656. * @param {...any} params - A parameter list.
  657. * @return {any} The value/object.
  658. */
  659. function getValueFromType( type, ...params ) {
  660. const last4 = type ? type.slice( -4 ) : undefined;
  661. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  662. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  663. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  664. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  665. }
  666. if ( type === 'color' ) {
  667. return new Color( ...params );
  668. } else if ( last4 === 'vec2' ) {
  669. return new Vector2( ...params );
  670. } else if ( last4 === 'vec3' ) {
  671. return new Vector3( ...params );
  672. } else if ( last4 === 'vec4' ) {
  673. return new Vector4( ...params );
  674. } else if ( last4 === 'mat2' ) {
  675. return new Matrix2( ...params );
  676. } else if ( last4 === 'mat3' ) {
  677. return new Matrix3( ...params );
  678. } else if ( last4 === 'mat4' ) {
  679. return new Matrix4( ...params );
  680. } else if ( type === 'bool' ) {
  681. return params[ 0 ] || false;
  682. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  683. return params[ 0 ] || 0;
  684. } else if ( type === 'string' ) {
  685. return params[ 0 ] || '';
  686. } else if ( type === 'ArrayBuffer' ) {
  687. return base64ToArrayBuffer( params[ 0 ] );
  688. }
  689. return null;
  690. }
  691. /**
  692. * Gets the object data that can be shared between different rendering steps.
  693. *
  694. * @param {Object} object - The object to get the data for.
  695. * @return {Object} The object data.
  696. */
  697. function getDataFromObject( object ) {
  698. let data = dataFromObject.get( object );
  699. if ( data === undefined ) {
  700. data = {};
  701. dataFromObject.set( object, data );
  702. }
  703. return data;
  704. }
  705. /**
  706. * Converts the given array buffer to a Base64 string.
  707. *
  708. * @method
  709. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  710. * @return {string} The Base64 string.
  711. */
  712. function arrayBufferToBase64( arrayBuffer ) {
  713. let chars = '';
  714. const array = new Uint8Array( arrayBuffer );
  715. for ( let i = 0; i < array.length; i ++ ) {
  716. chars += String.fromCharCode( array[ i ] );
  717. }
  718. return btoa( chars );
  719. }
  720. /**
  721. * Converts the given Base64 string to an array buffer.
  722. *
  723. * @method
  724. * @param {string} base64 - The Base64 string.
  725. * @return {ArrayBuffer} The array buffer.
  726. */
  727. function base64ToArrayBuffer( base64 ) {
  728. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  729. }
  730. var NodeUtils = /*#__PURE__*/Object.freeze({
  731. __proto__: null,
  732. arrayBufferToBase64: arrayBufferToBase64,
  733. base64ToArrayBuffer: base64ToArrayBuffer,
  734. getByteBoundaryFromType: getByteBoundaryFromType,
  735. getCacheKey: getCacheKey$1,
  736. getDataFromObject: getDataFromObject,
  737. getLengthFromType: getLengthFromType,
  738. getMemoryLengthFromType: getMemoryLengthFromType,
  739. getNodeChildren: getNodeChildren,
  740. getTypeFromLength: getTypeFromLength,
  741. getTypedArrayFromType: getTypedArrayFromType,
  742. getValueFromType: getValueFromType,
  743. getValueType: getValueType,
  744. hash: hash$1,
  745. hashArray: hashArray,
  746. hashString: hashString
  747. });
  748. /**
  749. * Possible shader stages.
  750. *
  751. * @property {string} VERTEX The vertex shader stage.
  752. * @property {string} FRAGMENT The fragment shader stage.
  753. */
  754. const NodeShaderStage = {
  755. VERTEX: 'vertex',
  756. FRAGMENT: 'fragment'
  757. };
  758. /**
  759. * Update types of a node.
  760. *
  761. * @property {string} NONE The update method is not executed.
  762. * @property {string} FRAME The update method is executed per frame.
  763. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  764. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  765. */
  766. const NodeUpdateType = {
  767. NONE: 'none',
  768. FRAME: 'frame',
  769. RENDER: 'render',
  770. OBJECT: 'object'
  771. };
  772. /**
  773. * Data types of a node.
  774. *
  775. * @property {string} BOOLEAN Boolean type.
  776. * @property {string} INTEGER Integer type.
  777. * @property {string} FLOAT Float type.
  778. * @property {string} VECTOR2 Two-dimensional vector type.
  779. * @property {string} VECTOR3 Three-dimensional vector type.
  780. * @property {string} VECTOR4 Four-dimensional vector type.
  781. * @property {string} MATRIX2 2x2 matrix type.
  782. * @property {string} MATRIX3 3x3 matrix type.
  783. * @property {string} MATRIX4 4x4 matrix type.
  784. */
  785. const NodeType = {
  786. BOOLEAN: 'bool',
  787. INTEGER: 'int',
  788. FLOAT: 'float',
  789. VECTOR2: 'vec2',
  790. VECTOR3: 'vec3',
  791. VECTOR4: 'vec4',
  792. MATRIX2: 'mat2',
  793. MATRIX3: 'mat3',
  794. MATRIX4: 'mat4'
  795. };
  796. /**
  797. * Access types of a node. These are relevant for compute and storage usage.
  798. *
  799. * @property {string} READ_ONLY Read-only access
  800. * @property {string} WRITE_ONLY Write-only access.
  801. * @property {string} READ_WRITE Read and write access.
  802. */
  803. const NodeAccess = {
  804. READ_ONLY: 'readOnly',
  805. WRITE_ONLY: 'writeOnly',
  806. READ_WRITE: 'readWrite',
  807. };
  808. const defaultShaderStages = [ 'fragment', 'vertex' ];
  809. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  810. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  811. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  812. const _parentBuildStage = {
  813. analyze: 'setup',
  814. generate: 'analyze'
  815. };
  816. let _nodeId = 0;
  817. /**
  818. * Base class for all nodes.
  819. *
  820. * @augments EventDispatcher
  821. */
  822. class Node extends EventDispatcher {
  823. static get type() {
  824. return 'Node';
  825. }
  826. /**
  827. * Constructs a new node.
  828. *
  829. * @param {?string} nodeType - The node type.
  830. */
  831. constructor( nodeType = null ) {
  832. super();
  833. /**
  834. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  835. *
  836. * @type {?string}
  837. * @default null
  838. */
  839. this.nodeType = nodeType;
  840. /**
  841. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  842. *
  843. * @type {string}
  844. * @default 'none'
  845. */
  846. this.updateType = NodeUpdateType.NONE;
  847. /**
  848. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  849. *
  850. * @type {string}
  851. * @default 'none'
  852. */
  853. this.updateBeforeType = NodeUpdateType.NONE;
  854. /**
  855. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  856. *
  857. * @type {string}
  858. * @default 'none'
  859. */
  860. this.updateAfterType = NodeUpdateType.NONE;
  861. /**
  862. * The UUID of the node.
  863. *
  864. * @type {string}
  865. * @readonly
  866. */
  867. this.uuid = MathUtils.generateUUID();
  868. /**
  869. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  870. *
  871. * @type {number}
  872. * @readonly
  873. * @default 0
  874. */
  875. this.version = 0;
  876. /**
  877. * Whether this node is global or not. This property is relevant for the internal
  878. * node caching system. All nodes which should be declared just once should
  879. * set this flag to `true` (a typical example is {@link AttributeNode}).
  880. *
  881. * @type {boolean}
  882. * @default false
  883. */
  884. this.global = false;
  885. /**
  886. * Create a list of parents for this node during the build process.
  887. *
  888. * @type {boolean}
  889. * @default false
  890. */
  891. this.parents = false;
  892. /**
  893. * This flag can be used for type testing.
  894. *
  895. * @type {boolean}
  896. * @readonly
  897. * @default true
  898. */
  899. this.isNode = true;
  900. // private
  901. /**
  902. * The cache key of this node.
  903. *
  904. * @private
  905. * @type {?number}
  906. * @default null
  907. */
  908. this._cacheKey = null;
  909. /**
  910. * The cache key 's version.
  911. *
  912. * @private
  913. * @type {number}
  914. * @default 0
  915. */
  916. this._cacheKeyVersion = 0;
  917. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  918. }
  919. /**
  920. * Set this property to `true` when the node should be regenerated.
  921. *
  922. * @type {boolean}
  923. * @default false
  924. * @param {boolean} value
  925. */
  926. set needsUpdate( value ) {
  927. if ( value === true ) {
  928. this.version ++;
  929. }
  930. }
  931. /**
  932. * The type of the class. The value is usually the constructor name.
  933. *
  934. * @type {string}
  935. * @readonly
  936. */
  937. get type() {
  938. return this.constructor.type;
  939. }
  940. /**
  941. * Convenient method for defining {@link Node#update}.
  942. *
  943. * @param {Function} callback - The update method.
  944. * @param {string} updateType - The update type.
  945. * @return {Node} A reference to this node.
  946. */
  947. onUpdate( callback, updateType ) {
  948. this.updateType = updateType;
  949. this.update = callback.bind( this.getSelf() );
  950. return this;
  951. }
  952. /**
  953. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  954. * this method automatically sets the update type to `FRAME`.
  955. *
  956. * @param {Function} callback - The update method.
  957. * @return {Node} A reference to this node.
  958. */
  959. onFrameUpdate( callback ) {
  960. return this.onUpdate( callback, NodeUpdateType.FRAME );
  961. }
  962. /**
  963. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  964. * this method automatically sets the update type to `RENDER`.
  965. *
  966. * @param {Function} callback - The update method.
  967. * @return {Node} A reference to this node.
  968. */
  969. onRenderUpdate( callback ) {
  970. return this.onUpdate( callback, NodeUpdateType.RENDER );
  971. }
  972. /**
  973. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  974. * this method automatically sets the update type to `OBJECT`.
  975. *
  976. * @param {Function} callback - The update method.
  977. * @return {Node} A reference to this node.
  978. */
  979. onObjectUpdate( callback ) {
  980. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  981. }
  982. /**
  983. * Convenient method for defining {@link Node#updateReference}.
  984. *
  985. * @param {Function} callback - The update method.
  986. * @return {Node} A reference to this node.
  987. */
  988. onReference( callback ) {
  989. this.updateReference = callback.bind( this.getSelf() );
  990. return this;
  991. }
  992. /**
  993. * The `this` reference might point to a Proxy so this method can be used
  994. * to get the reference to the actual node instance.
  995. *
  996. * @return {Node} A reference to the node.
  997. */
  998. getSelf() {
  999. // Returns non-node object.
  1000. return this.self || this;
  1001. }
  1002. /**
  1003. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1004. * to such objects based on a given state (e.g. the current node frame or builder).
  1005. *
  1006. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1007. * @return {any} The updated reference.
  1008. */
  1009. updateReference( /*state*/ ) {
  1010. return this;
  1011. }
  1012. /**
  1013. * By default this method returns the value of the {@link Node#global} flag. This method
  1014. * can be overwritten in derived classes if an analytical way is required to determine the
  1015. * global cache referring to the current shader-stage.
  1016. *
  1017. * @param {NodeBuilder} builder - The current node builder.
  1018. * @return {boolean} Whether this node is global or not.
  1019. */
  1020. isGlobal( /*builder*/ ) {
  1021. return this.global;
  1022. }
  1023. /**
  1024. * Generator function that can be used to iterate over the child nodes.
  1025. *
  1026. * @generator
  1027. * @yields {Node} A child node.
  1028. */
  1029. * getChildren() {
  1030. for ( const { childNode } of getNodeChildren( this ) ) {
  1031. yield childNode;
  1032. }
  1033. }
  1034. /**
  1035. * Calling this method dispatches the `dispose` event. This event can be used
  1036. * to register event listeners for clean up tasks.
  1037. */
  1038. dispose() {
  1039. this.dispatchEvent( { type: 'dispose' } );
  1040. }
  1041. /**
  1042. * Callback for {@link Node#traverse}.
  1043. *
  1044. * @callback traverseCallback
  1045. * @param {Node} node - The current node.
  1046. */
  1047. /**
  1048. * Can be used to traverse through the node's hierarchy.
  1049. *
  1050. * @param {traverseCallback} callback - A callback that is executed per node.
  1051. */
  1052. traverse( callback ) {
  1053. callback( this );
  1054. for ( const childNode of this.getChildren() ) {
  1055. childNode.traverse( callback );
  1056. }
  1057. }
  1058. /**
  1059. * Returns the cache key for this node.
  1060. *
  1061. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1062. * @return {number} The cache key of the node.
  1063. */
  1064. getCacheKey( force = false ) {
  1065. force = force || this.version !== this._cacheKeyVersion;
  1066. if ( force === true || this._cacheKey === null ) {
  1067. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1068. this._cacheKeyVersion = this.version;
  1069. }
  1070. return this._cacheKey;
  1071. }
  1072. /**
  1073. * Generate a custom cache key for this node.
  1074. *
  1075. * @return {number} The cache key of the node.
  1076. */
  1077. customCacheKey() {
  1078. return 0;
  1079. }
  1080. /**
  1081. * Returns the references to this node which is by default `this`.
  1082. *
  1083. * @return {Node} A reference to this node.
  1084. */
  1085. getScope() {
  1086. return this;
  1087. }
  1088. /**
  1089. * Returns the hash of the node which is used to identify the node. By default it's
  1090. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1091. * depending on their implementation.
  1092. *
  1093. * @param {NodeBuilder} builder - The current node builder.
  1094. * @return {string} The hash.
  1095. */
  1096. getHash( /*builder*/ ) {
  1097. return this.uuid;
  1098. }
  1099. /**
  1100. * Returns the update type of {@link Node#update}.
  1101. *
  1102. * @return {NodeUpdateType} The update type.
  1103. */
  1104. getUpdateType() {
  1105. return this.updateType;
  1106. }
  1107. /**
  1108. * Returns the update type of {@link Node#updateBefore}.
  1109. *
  1110. * @return {NodeUpdateType} The update type.
  1111. */
  1112. getUpdateBeforeType() {
  1113. return this.updateBeforeType;
  1114. }
  1115. /**
  1116. * Returns the update type of {@link Node#updateAfter}.
  1117. *
  1118. * @return {NodeUpdateType} The update type.
  1119. */
  1120. getUpdateAfterType() {
  1121. return this.updateAfterType;
  1122. }
  1123. /**
  1124. * Certain types are composed of multiple elements. For example a `vec3`
  1125. * is composed of three `float` values. This method returns the type of
  1126. * these elements.
  1127. *
  1128. * @param {NodeBuilder} builder - The current node builder.
  1129. * @return {string} The type of the node.
  1130. */
  1131. getElementType( builder ) {
  1132. const type = this.getNodeType( builder );
  1133. const elementType = builder.getElementType( type );
  1134. return elementType;
  1135. }
  1136. /**
  1137. * Returns the node member type for the given name.
  1138. *
  1139. * @param {NodeBuilder} builder - The current node builder.
  1140. * @param {string} name - The name of the member.
  1141. * @return {string} The type of the node.
  1142. */
  1143. getMemberType( /*builder, name*/ ) {
  1144. return 'void';
  1145. }
  1146. /**
  1147. * Returns the node's type.
  1148. *
  1149. * @param {NodeBuilder} builder - The current node builder.
  1150. * @return {string} The type of the node.
  1151. */
  1152. getNodeType( builder ) {
  1153. const nodeProperties = builder.getNodeProperties( this );
  1154. if ( nodeProperties.outputNode ) {
  1155. return nodeProperties.outputNode.getNodeType( builder );
  1156. }
  1157. return this.nodeType;
  1158. }
  1159. /**
  1160. * This method is used during the build process of a node and ensures
  1161. * equal nodes are not built multiple times but just once. For example if
  1162. * `attribute( 'uv' )` is used multiple times by the user, the build
  1163. * process makes sure to process just the first node.
  1164. *
  1165. * @param {NodeBuilder} builder - The current node builder.
  1166. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1167. */
  1168. getShared( builder ) {
  1169. const hash = this.getHash( builder );
  1170. const nodeFromHash = builder.getNodeFromHash( hash );
  1171. return nodeFromHash || this;
  1172. }
  1173. /**
  1174. * Returns the number of elements in the node array.
  1175. *
  1176. * @param {NodeBuilder} builder - The current node builder.
  1177. * @return {?number} The number of elements in the node array.
  1178. */
  1179. getArrayCount( /*builder*/ ) {
  1180. return null;
  1181. }
  1182. /**
  1183. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1184. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1185. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1186. *
  1187. * @param {NodeBuilder} builder - The current node builder.
  1188. * @return {?Node} The output node.
  1189. */
  1190. setup( builder ) {
  1191. const nodeProperties = builder.getNodeProperties( this );
  1192. let index = 0;
  1193. for ( const childNode of this.getChildren() ) {
  1194. nodeProperties[ 'node' + index ++ ] = childNode;
  1195. }
  1196. // return a outputNode if exists or null
  1197. return nodeProperties.outputNode || null;
  1198. }
  1199. /**
  1200. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1201. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1202. *
  1203. * @param {NodeBuilder} builder - The current node builder.
  1204. * @param {?Node} output - The target output node.
  1205. */
  1206. analyze( builder, output = null ) {
  1207. const usageCount = builder.increaseUsage( this );
  1208. if ( this.parents === true ) {
  1209. const nodeData = builder.getDataFromNode( this, 'any' );
  1210. nodeData.stages = nodeData.stages || {};
  1211. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1212. nodeData.stages[ builder.shaderStage ].push( output );
  1213. }
  1214. if ( usageCount === 1 ) {
  1215. // node flow children
  1216. const nodeProperties = builder.getNodeProperties( this );
  1217. for ( const childNode of Object.values( nodeProperties ) ) {
  1218. if ( childNode && childNode.isNode === true ) {
  1219. childNode.build( builder, this );
  1220. }
  1221. }
  1222. }
  1223. }
  1224. /**
  1225. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1226. * This state builds the output node and returns the resulting shader string.
  1227. *
  1228. * @param {NodeBuilder} builder - The current node builder.
  1229. * @param {?string} output - Can be used to define the output type.
  1230. * @return {?string} The generated shader string.
  1231. */
  1232. generate( builder, output ) {
  1233. const { outputNode } = builder.getNodeProperties( this );
  1234. if ( outputNode && outputNode.isNode === true ) {
  1235. return outputNode.build( builder, output );
  1236. }
  1237. }
  1238. /**
  1239. * The method can be implemented to update the node's internal state before it is used to render an object.
  1240. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1241. *
  1242. * @abstract
  1243. * @param {NodeFrame} frame - A reference to the current node frame.
  1244. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1245. */
  1246. updateBefore( /*frame*/ ) {
  1247. console.warn( 'Abstract function.' );
  1248. }
  1249. /**
  1250. * The method can be implemented to update the node's internal state after it was used to render an object.
  1251. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1252. *
  1253. * @abstract
  1254. * @param {NodeFrame} frame - A reference to the current node frame.
  1255. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1256. */
  1257. updateAfter( /*frame*/ ) {
  1258. console.warn( 'Abstract function.' );
  1259. }
  1260. /**
  1261. * The method can be implemented to update the node's internal state when it is used to render an object.
  1262. * The {@link Node#updateType} property defines how often the update is executed.
  1263. *
  1264. * @abstract
  1265. * @param {NodeFrame} frame - A reference to the current node frame.
  1266. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1267. */
  1268. update( /*frame*/ ) {
  1269. console.warn( 'Abstract function.' );
  1270. }
  1271. /**
  1272. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1273. * - **setup**: Prepares the node and its children for the build process. This process can also create new nodes. Returns the node itself or a variant.
  1274. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1275. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1276. *
  1277. * @param {NodeBuilder} builder - The current node builder.
  1278. * @param {string|Node|null} [output=null] - Can be used to define the output type.
  1279. * @return {Node|string|null} The result of the build process, depending on the build stage.
  1280. */
  1281. build( builder, output = null ) {
  1282. const refNode = this.getShared( builder );
  1283. if ( this !== refNode ) {
  1284. return refNode.build( builder, output );
  1285. }
  1286. //
  1287. const nodeData = builder.getDataFromNode( this );
  1288. nodeData.buildStages = nodeData.buildStages || {};
  1289. nodeData.buildStages[ builder.buildStage ] = true;
  1290. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1291. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1292. // force parent build stage (setup or analyze)
  1293. const previousBuildStage = builder.getBuildStage();
  1294. builder.setBuildStage( parentBuildStage );
  1295. this.build( builder );
  1296. builder.setBuildStage( previousBuildStage );
  1297. }
  1298. //
  1299. builder.addNode( this );
  1300. builder.addChain( this );
  1301. /* Build stages expected results:
  1302. - "setup" -> Node
  1303. - "analyze" -> null
  1304. - "generate" -> String
  1305. */
  1306. let result = null;
  1307. const buildStage = builder.getBuildStage();
  1308. if ( buildStage === 'setup' ) {
  1309. this.updateReference( builder );
  1310. const properties = builder.getNodeProperties( this );
  1311. if ( properties.initialized !== true ) {
  1312. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1313. properties.initialized = true;
  1314. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1315. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1316. // !! no outputNode !!
  1317. //outputNode = builder.stack;
  1318. }*/
  1319. for ( const childNode of Object.values( properties ) ) {
  1320. if ( childNode && childNode.isNode === true ) {
  1321. if ( childNode.parents === true ) {
  1322. const childProperties = builder.getNodeProperties( childNode );
  1323. childProperties.parents = childProperties.parents || [];
  1324. childProperties.parents.push( this );
  1325. }
  1326. childNode.build( builder );
  1327. }
  1328. }
  1329. }
  1330. result = properties.outputNode;
  1331. } else if ( buildStage === 'analyze' ) {
  1332. this.analyze( builder, output );
  1333. } else if ( buildStage === 'generate' ) {
  1334. const isGenerateOnce = this.generate.length === 1;
  1335. if ( isGenerateOnce ) {
  1336. const type = this.getNodeType( builder );
  1337. const nodeData = builder.getDataFromNode( this );
  1338. result = nodeData.snippet;
  1339. if ( result === undefined ) {
  1340. if ( nodeData.generated === undefined ) {
  1341. nodeData.generated = true;
  1342. result = this.generate( builder ) || '';
  1343. nodeData.snippet = result;
  1344. } else {
  1345. console.warn( 'THREE.Node: Recursion detected.', this );
  1346. result = '/* Recursion detected. */';
  1347. }
  1348. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1349. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1350. }
  1351. result = builder.format( result, type, output );
  1352. } else {
  1353. result = this.generate( builder, output ) || '';
  1354. }
  1355. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1356. // if no snippet is generated, return a default value
  1357. console.error( `THREE.TSL: Invalid generated code, expected a "${ output }".` );
  1358. result = builder.generateConst( output );
  1359. }
  1360. }
  1361. builder.removeChain( this );
  1362. builder.addSequentialNode( this );
  1363. return result;
  1364. }
  1365. /**
  1366. * Returns the child nodes as a JSON object.
  1367. *
  1368. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1369. */
  1370. getSerializeChildren() {
  1371. return getNodeChildren( this );
  1372. }
  1373. /**
  1374. * Serializes the node to JSON.
  1375. *
  1376. * @param {Object} json - The output JSON object.
  1377. */
  1378. serialize( json ) {
  1379. const nodeChildren = this.getSerializeChildren();
  1380. const inputNodes = {};
  1381. for ( const { property, index, childNode } of nodeChildren ) {
  1382. if ( index !== undefined ) {
  1383. if ( inputNodes[ property ] === undefined ) {
  1384. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1385. }
  1386. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1387. } else {
  1388. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1389. }
  1390. }
  1391. if ( Object.keys( inputNodes ).length > 0 ) {
  1392. json.inputNodes = inputNodes;
  1393. }
  1394. }
  1395. /**
  1396. * Deserializes the node from the given JSON.
  1397. *
  1398. * @param {Object} json - The JSON object.
  1399. */
  1400. deserialize( json ) {
  1401. if ( json.inputNodes !== undefined ) {
  1402. const nodes = json.meta.nodes;
  1403. for ( const property in json.inputNodes ) {
  1404. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1405. const inputArray = [];
  1406. for ( const uuid of json.inputNodes[ property ] ) {
  1407. inputArray.push( nodes[ uuid ] );
  1408. }
  1409. this[ property ] = inputArray;
  1410. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1411. const inputObject = {};
  1412. for ( const subProperty in json.inputNodes[ property ] ) {
  1413. const uuid = json.inputNodes[ property ][ subProperty ];
  1414. inputObject[ subProperty ] = nodes[ uuid ];
  1415. }
  1416. this[ property ] = inputObject;
  1417. } else {
  1418. const uuid = json.inputNodes[ property ];
  1419. this[ property ] = nodes[ uuid ];
  1420. }
  1421. }
  1422. }
  1423. }
  1424. /**
  1425. * Serializes the node into the three.js JSON Object/Scene format.
  1426. *
  1427. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1428. * @return {Object} The serialized node.
  1429. */
  1430. toJSON( meta ) {
  1431. const { uuid, type } = this;
  1432. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1433. if ( isRoot ) {
  1434. meta = {
  1435. textures: {},
  1436. images: {},
  1437. nodes: {}
  1438. };
  1439. }
  1440. // serialize
  1441. let data = meta.nodes[ uuid ];
  1442. if ( data === undefined ) {
  1443. data = {
  1444. uuid,
  1445. type,
  1446. meta,
  1447. metadata: {
  1448. version: 4.7,
  1449. type: 'Node',
  1450. generator: 'Node.toJSON'
  1451. }
  1452. };
  1453. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1454. this.serialize( data );
  1455. delete data.meta;
  1456. }
  1457. // TODO: Copied from Object3D.toJSON
  1458. function extractFromCache( cache ) {
  1459. const values = [];
  1460. for ( const key in cache ) {
  1461. const data = cache[ key ];
  1462. delete data.metadata;
  1463. values.push( data );
  1464. }
  1465. return values;
  1466. }
  1467. if ( isRoot ) {
  1468. const textures = extractFromCache( meta.textures );
  1469. const images = extractFromCache( meta.images );
  1470. const nodes = extractFromCache( meta.nodes );
  1471. if ( textures.length > 0 ) data.textures = textures;
  1472. if ( images.length > 0 ) data.images = images;
  1473. if ( nodes.length > 0 ) data.nodes = nodes;
  1474. }
  1475. return data;
  1476. }
  1477. }
  1478. /**
  1479. * Base class for representing element access on an array-like
  1480. * node data structures.
  1481. *
  1482. * @augments Node
  1483. */
  1484. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1485. static get type() {
  1486. return 'ArrayElementNode';
  1487. }
  1488. /**
  1489. * Constructs an array element node.
  1490. *
  1491. * @param {Node} node - The array-like node.
  1492. * @param {Node} indexNode - The index node that defines the element access.
  1493. */
  1494. constructor( node, indexNode ) {
  1495. super();
  1496. /**
  1497. * The array-like node.
  1498. *
  1499. * @type {Node}
  1500. */
  1501. this.node = node;
  1502. /**
  1503. * The index node that defines the element access.
  1504. *
  1505. * @type {Node}
  1506. */
  1507. this.indexNode = indexNode;
  1508. /**
  1509. * This flag can be used for type testing.
  1510. *
  1511. * @type {boolean}
  1512. * @readonly
  1513. * @default true
  1514. */
  1515. this.isArrayElementNode = true;
  1516. }
  1517. /**
  1518. * This method is overwritten since the node type is inferred from the array-like node.
  1519. *
  1520. * @param {NodeBuilder} builder - The current node builder.
  1521. * @return {string} The node type.
  1522. */
  1523. getNodeType( builder ) {
  1524. return this.node.getElementType( builder );
  1525. }
  1526. generate( builder ) {
  1527. const indexType = this.indexNode.getNodeType( builder );
  1528. const nodeSnippet = this.node.build( builder );
  1529. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1530. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1531. }
  1532. }
  1533. /**
  1534. * This module is part of the TSL core and usually not used in app level code.
  1535. * It represents a convert operation during the shader generation process
  1536. * meaning it converts the data type of a node to a target data type.
  1537. *
  1538. * @augments Node
  1539. */
  1540. class ConvertNode extends Node {
  1541. static get type() {
  1542. return 'ConvertNode';
  1543. }
  1544. /**
  1545. * Constructs a new convert node.
  1546. *
  1547. * @param {Node} node - The node which type should be converted.
  1548. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1549. */
  1550. constructor( node, convertTo ) {
  1551. super();
  1552. /**
  1553. * The node which type should be converted.
  1554. *
  1555. * @type {Node}
  1556. */
  1557. this.node = node;
  1558. /**
  1559. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1560. *
  1561. * @type {string}
  1562. */
  1563. this.convertTo = convertTo;
  1564. }
  1565. /**
  1566. * This method is overwritten since the implementation tries to infer the best
  1567. * matching type from the {@link ConvertNode#convertTo} property.
  1568. *
  1569. * @param {NodeBuilder} builder - The current node builder.
  1570. * @return {string} The node type.
  1571. */
  1572. getNodeType( builder ) {
  1573. const requestType = this.node.getNodeType( builder );
  1574. let convertTo = null;
  1575. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1576. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1577. convertTo = overloadingType;
  1578. }
  1579. }
  1580. return convertTo;
  1581. }
  1582. serialize( data ) {
  1583. super.serialize( data );
  1584. data.convertTo = this.convertTo;
  1585. }
  1586. deserialize( data ) {
  1587. super.deserialize( data );
  1588. this.convertTo = data.convertTo;
  1589. }
  1590. generate( builder, output ) {
  1591. const node = this.node;
  1592. const type = this.getNodeType( builder );
  1593. const snippet = node.build( builder, type );
  1594. return builder.format( snippet, type, output );
  1595. }
  1596. }
  1597. /**
  1598. * This module uses cache management to create temporary variables
  1599. * if the node is used more than once to prevent duplicate calculations.
  1600. *
  1601. * The class acts as a base class for many other nodes types.
  1602. *
  1603. * @augments Node
  1604. */
  1605. class TempNode extends Node {
  1606. static get type() {
  1607. return 'TempNode';
  1608. }
  1609. /**
  1610. * Constructs a temp node.
  1611. *
  1612. * @param {?string} nodeType - The node type.
  1613. */
  1614. constructor( nodeType = null ) {
  1615. super( nodeType );
  1616. /**
  1617. * This flag can be used for type testing.
  1618. *
  1619. * @type {boolean}
  1620. * @readonly
  1621. * @default true
  1622. */
  1623. this.isTempNode = true;
  1624. }
  1625. /**
  1626. * Whether this node is used more than once in context of other nodes.
  1627. *
  1628. * @param {NodeBuilder} builder - The node builder.
  1629. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1630. */
  1631. hasDependencies( builder ) {
  1632. return builder.getDataFromNode( this ).usageCount > 1;
  1633. }
  1634. build( builder, output ) {
  1635. const buildStage = builder.getBuildStage();
  1636. if ( buildStage === 'generate' ) {
  1637. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1638. const nodeData = builder.getDataFromNode( this );
  1639. if ( nodeData.propertyName !== undefined ) {
  1640. return builder.format( nodeData.propertyName, type, output );
  1641. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1642. const snippet = super.build( builder, type );
  1643. const nodeVar = builder.getVarFromNode( this, null, type );
  1644. const propertyName = builder.getPropertyName( nodeVar );
  1645. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1646. nodeData.snippet = snippet;
  1647. nodeData.propertyName = propertyName;
  1648. return builder.format( nodeData.propertyName, type, output );
  1649. }
  1650. }
  1651. return super.build( builder, output );
  1652. }
  1653. }
  1654. /**
  1655. * This module is part of the TSL core and usually not used in app level code.
  1656. * It represents a join operation during the shader generation process.
  1657. * For example in can compose/join two single floats into a `vec2` type.
  1658. *
  1659. * @augments TempNode
  1660. */
  1661. class JoinNode extends TempNode {
  1662. static get type() {
  1663. return 'JoinNode';
  1664. }
  1665. /**
  1666. * Constructs a new join node.
  1667. *
  1668. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1669. * @param {?string} [nodeType=null] - The node type.
  1670. */
  1671. constructor( nodes = [], nodeType = null ) {
  1672. super( nodeType );
  1673. /**
  1674. * An array of nodes that should be joined.
  1675. *
  1676. * @type {Array<Node>}
  1677. */
  1678. this.nodes = nodes;
  1679. }
  1680. /**
  1681. * This method is overwritten since the node type must be inferred from the
  1682. * joined data length if not explicitly defined.
  1683. *
  1684. * @param {NodeBuilder} builder - The current node builder.
  1685. * @return {string} The node type.
  1686. */
  1687. getNodeType( builder ) {
  1688. if ( this.nodeType !== null ) {
  1689. return builder.getVectorType( this.nodeType );
  1690. }
  1691. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1692. }
  1693. generate( builder, output ) {
  1694. const type = this.getNodeType( builder );
  1695. const maxLength = builder.getTypeLength( type );
  1696. const nodes = this.nodes;
  1697. const primitiveType = builder.getComponentType( type );
  1698. const snippetValues = [];
  1699. let length = 0;
  1700. for ( const input of nodes ) {
  1701. if ( length >= maxLength ) {
  1702. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1703. break;
  1704. }
  1705. let inputType = input.getNodeType( builder );
  1706. let inputTypeLength = builder.getTypeLength( inputType );
  1707. let inputSnippet;
  1708. if ( length + inputTypeLength > maxLength ) {
  1709. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1710. inputTypeLength = maxLength - length;
  1711. inputType = builder.getTypeFromLength( inputTypeLength );
  1712. }
  1713. length += inputTypeLength;
  1714. inputSnippet = input.build( builder, inputType );
  1715. const inputPrimitiveType = builder.getComponentType( inputType );
  1716. if ( inputPrimitiveType !== primitiveType ) {
  1717. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1718. }
  1719. snippetValues.push( inputSnippet );
  1720. }
  1721. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1722. return builder.format( snippet, type, output );
  1723. }
  1724. }
  1725. const _stringVectorComponents = vectorComponents.join( '' );
  1726. /**
  1727. * This module is part of the TSL core and usually not used in app level code.
  1728. * `SplitNode` represents a property access operation which means it is
  1729. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1730. * For example:
  1731. * ```js
  1732. * const redValue = color.r;
  1733. * ```
  1734. *
  1735. * @augments Node
  1736. */
  1737. class SplitNode extends Node {
  1738. static get type() {
  1739. return 'SplitNode';
  1740. }
  1741. /**
  1742. * Constructs a new split node.
  1743. *
  1744. * @param {Node} node - The node that should be accessed.
  1745. * @param {string} [components='x'] - The components that should be accessed.
  1746. */
  1747. constructor( node, components = 'x' ) {
  1748. super();
  1749. /**
  1750. * The node that should be accessed.
  1751. *
  1752. * @type {Node}
  1753. */
  1754. this.node = node;
  1755. /**
  1756. * The components that should be accessed.
  1757. *
  1758. * @type {string}
  1759. */
  1760. this.components = components;
  1761. /**
  1762. * This flag can be used for type testing.
  1763. *
  1764. * @type {boolean}
  1765. * @readonly
  1766. * @default true
  1767. */
  1768. this.isSplitNode = true;
  1769. }
  1770. /**
  1771. * Returns the vector length which is computed based on the requested components.
  1772. *
  1773. * @return {number} The vector length.
  1774. */
  1775. getVectorLength() {
  1776. let vectorLength = this.components.length;
  1777. for ( const c of this.components ) {
  1778. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1779. }
  1780. return vectorLength;
  1781. }
  1782. /**
  1783. * Returns the component type of the node's type.
  1784. *
  1785. * @param {NodeBuilder} builder - The current node builder.
  1786. * @return {string} The component type.
  1787. */
  1788. getComponentType( builder ) {
  1789. return builder.getComponentType( this.node.getNodeType( builder ) );
  1790. }
  1791. /**
  1792. * This method is overwritten since the node type is inferred from requested components.
  1793. *
  1794. * @param {NodeBuilder} builder - The current node builder.
  1795. * @return {string} The node type.
  1796. */
  1797. getNodeType( builder ) {
  1798. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1799. }
  1800. generate( builder, output ) {
  1801. const node = this.node;
  1802. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1803. let snippet = null;
  1804. if ( nodeTypeLength > 1 ) {
  1805. let type = null;
  1806. const componentsLength = this.getVectorLength();
  1807. if ( componentsLength >= nodeTypeLength ) {
  1808. // needed expand the input node
  1809. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1810. }
  1811. const nodeSnippet = node.build( builder, type );
  1812. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1813. // unnecessary swizzle
  1814. snippet = builder.format( nodeSnippet, type, output );
  1815. } else {
  1816. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1817. }
  1818. } else {
  1819. // ignore .components if .node returns float/integer
  1820. snippet = node.build( builder, output );
  1821. }
  1822. return snippet;
  1823. }
  1824. serialize( data ) {
  1825. super.serialize( data );
  1826. data.components = this.components;
  1827. }
  1828. deserialize( data ) {
  1829. super.deserialize( data );
  1830. this.components = data.components;
  1831. }
  1832. }
  1833. /**
  1834. * This module is part of the TSL core and usually not used in app level code.
  1835. * `SetNode` represents a set operation which means it is used to implement any
  1836. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1837. * For example:
  1838. * ```js
  1839. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1840. * ```
  1841. *
  1842. * @augments TempNode
  1843. */
  1844. class SetNode extends TempNode {
  1845. static get type() {
  1846. return 'SetNode';
  1847. }
  1848. /**
  1849. * Constructs a new set node.
  1850. *
  1851. * @param {Node} sourceNode - The node that should be updated.
  1852. * @param {string} components - The components that should be updated.
  1853. * @param {Node} targetNode - The value node.
  1854. */
  1855. constructor( sourceNode, components, targetNode ) {
  1856. super();
  1857. /**
  1858. * The node that should be updated.
  1859. *
  1860. * @type {Node}
  1861. */
  1862. this.sourceNode = sourceNode;
  1863. /**
  1864. * The components that should be updated.
  1865. *
  1866. * @type {string}
  1867. */
  1868. this.components = components;
  1869. /**
  1870. * The value node.
  1871. *
  1872. * @type {Node}
  1873. */
  1874. this.targetNode = targetNode;
  1875. }
  1876. /**
  1877. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1878. *
  1879. * @param {NodeBuilder} builder - The current node builder.
  1880. * @return {string} The node type.
  1881. */
  1882. getNodeType( builder ) {
  1883. return this.sourceNode.getNodeType( builder );
  1884. }
  1885. generate( builder ) {
  1886. const { sourceNode, components, targetNode } = this;
  1887. const sourceType = this.getNodeType( builder );
  1888. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1889. const targetType = builder.getTypeFromLength( components.length, componentType );
  1890. const targetSnippet = targetNode.build( builder, targetType );
  1891. const sourceSnippet = sourceNode.build( builder, sourceType );
  1892. const length = builder.getTypeLength( sourceType );
  1893. const snippetValues = [];
  1894. for ( let i = 0; i < length; i ++ ) {
  1895. const component = vectorComponents[ i ];
  1896. if ( component === components[ 0 ] ) {
  1897. snippetValues.push( targetSnippet );
  1898. i += components.length - 1;
  1899. } else {
  1900. snippetValues.push( sourceSnippet + '.' + component );
  1901. }
  1902. }
  1903. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1904. }
  1905. }
  1906. /**
  1907. * This module is part of the TSL core and usually not used in app level code.
  1908. * It represents a flip operation during the shader generation process
  1909. * meaning it flips normalized values with the following formula:
  1910. * ```
  1911. * x = 1 - x;
  1912. * ```
  1913. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1914. * `flipSTPQ()` method invocations on node objects. For example:
  1915. * ```js
  1916. * uvNode = uvNode.flipY();
  1917. * ```
  1918. *
  1919. * @augments TempNode
  1920. */
  1921. class FlipNode extends TempNode {
  1922. static get type() {
  1923. return 'FlipNode';
  1924. }
  1925. /**
  1926. * Constructs a new flip node.
  1927. *
  1928. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1929. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1930. */
  1931. constructor( sourceNode, components ) {
  1932. super();
  1933. /**
  1934. * The node which component(s) should be flipped.
  1935. *
  1936. * @type {Node}
  1937. */
  1938. this.sourceNode = sourceNode;
  1939. /**
  1940. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1941. *
  1942. * @type {string}
  1943. */
  1944. this.components = components;
  1945. }
  1946. /**
  1947. * This method is overwritten since the node type is inferred from the source node.
  1948. *
  1949. * @param {NodeBuilder} builder - The current node builder.
  1950. * @return {string} The node type.
  1951. */
  1952. getNodeType( builder ) {
  1953. return this.sourceNode.getNodeType( builder );
  1954. }
  1955. generate( builder ) {
  1956. const { components, sourceNode } = this;
  1957. const sourceType = this.getNodeType( builder );
  1958. const sourceSnippet = sourceNode.build( builder );
  1959. const sourceCache = builder.getVarFromNode( this );
  1960. const sourceProperty = builder.getPropertyName( sourceCache );
  1961. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1962. const length = builder.getTypeLength( sourceType );
  1963. const snippetValues = [];
  1964. let componentIndex = 0;
  1965. for ( let i = 0; i < length; i ++ ) {
  1966. const component = vectorComponents[ i ];
  1967. if ( component === components[ componentIndex ] ) {
  1968. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1969. componentIndex ++;
  1970. } else {
  1971. snippetValues.push( sourceProperty + '.' + component );
  1972. }
  1973. }
  1974. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1975. }
  1976. }
  1977. /**
  1978. * Base class for representing data input nodes.
  1979. *
  1980. * @augments Node
  1981. */
  1982. class InputNode extends Node {
  1983. static get type() {
  1984. return 'InputNode';
  1985. }
  1986. /**
  1987. * Constructs a new input node.
  1988. *
  1989. * @param {any} value - The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1990. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1991. */
  1992. constructor( value, nodeType = null ) {
  1993. super( nodeType );
  1994. /**
  1995. * This flag can be used for type testing.
  1996. *
  1997. * @type {boolean}
  1998. * @readonly
  1999. * @default true
  2000. */
  2001. this.isInputNode = true;
  2002. /**
  2003. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2004. *
  2005. * @type {any}
  2006. */
  2007. this.value = value;
  2008. /**
  2009. * The precision of the value in the shader.
  2010. *
  2011. * @type {?('low'|'medium'|'high')}
  2012. * @default null
  2013. */
  2014. this.precision = null;
  2015. }
  2016. getNodeType( /*builder*/ ) {
  2017. if ( this.nodeType === null ) {
  2018. return getValueType( this.value );
  2019. }
  2020. return this.nodeType;
  2021. }
  2022. /**
  2023. * Returns the input type of the node which is by default the node type. Derived modules
  2024. * might overwrite this method and use a fixed type or compute one analytically.
  2025. *
  2026. * A typical example for different input and node types are textures. The input type of a
  2027. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2028. *
  2029. * @param {NodeBuilder} builder - The current node builder.
  2030. * @return {string} The input type.
  2031. */
  2032. getInputType( builder ) {
  2033. return this.getNodeType( builder );
  2034. }
  2035. /**
  2036. * Sets the precision to the given value. The method can be
  2037. * overwritten in derived classes if the final precision must be computed
  2038. * analytically.
  2039. *
  2040. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2041. * @return {InputNode} A reference to this node.
  2042. */
  2043. setPrecision( precision ) {
  2044. this.precision = precision;
  2045. return this;
  2046. }
  2047. serialize( data ) {
  2048. super.serialize( data );
  2049. data.value = this.value;
  2050. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2051. data.valueType = getValueType( this.value );
  2052. data.nodeType = this.nodeType;
  2053. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2054. data.precision = this.precision;
  2055. }
  2056. deserialize( data ) {
  2057. super.deserialize( data );
  2058. this.nodeType = data.nodeType;
  2059. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2060. this.precision = data.precision || null;
  2061. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2062. }
  2063. generate( /*builder, output*/ ) {
  2064. console.warn( 'Abstract function.' );
  2065. }
  2066. }
  2067. const _regNum = /float|u?int/;
  2068. /**
  2069. * Class for representing a constant value in the shader.
  2070. *
  2071. * @augments InputNode
  2072. */
  2073. class ConstNode extends InputNode {
  2074. static get type() {
  2075. return 'ConstNode';
  2076. }
  2077. /**
  2078. * Constructs a new input node.
  2079. *
  2080. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2081. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2082. */
  2083. constructor( value, nodeType = null ) {
  2084. super( value, nodeType );
  2085. /**
  2086. * This flag can be used for type testing.
  2087. *
  2088. * @type {boolean}
  2089. * @readonly
  2090. * @default true
  2091. */
  2092. this.isConstNode = true;
  2093. }
  2094. /**
  2095. * Generates the shader string of the value with the current node builder.
  2096. *
  2097. * @param {NodeBuilder} builder - The current node builder.
  2098. * @return {string} The generated value as a shader string.
  2099. */
  2100. generateConst( builder ) {
  2101. return builder.generateConst( this.getNodeType( builder ), this.value );
  2102. }
  2103. generate( builder, output ) {
  2104. const type = this.getNodeType( builder );
  2105. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2106. return builder.generateConst( output, this.value );
  2107. }
  2108. return builder.format( this.generateConst( builder ), type, output );
  2109. }
  2110. }
  2111. /**
  2112. * Base class for representing member access on an object-like
  2113. * node data structures.
  2114. *
  2115. * @augments Node
  2116. */
  2117. class MemberNode extends Node {
  2118. static get type() {
  2119. return 'MemberNode';
  2120. }
  2121. /**
  2122. * Constructs an array element node.
  2123. *
  2124. * @param {Node} node - The array-like node.
  2125. * @param {string} property - The property name.
  2126. */
  2127. constructor( node, property ) {
  2128. super();
  2129. /**
  2130. * The array-like node.
  2131. *
  2132. * @type {Node}
  2133. */
  2134. this.node = node;
  2135. /**
  2136. * The property name.
  2137. *
  2138. * @type {Node}
  2139. */
  2140. this.property = property;
  2141. /**
  2142. * This flag can be used for type testing.
  2143. *
  2144. * @type {boolean}
  2145. * @readonly
  2146. * @default true
  2147. */
  2148. this.isMemberNode = true;
  2149. }
  2150. getNodeType( builder ) {
  2151. return this.node.getMemberType( builder, this.property );
  2152. }
  2153. generate( builder ) {
  2154. const propertyName = this.node.build( builder );
  2155. return propertyName + '.' + this.property;
  2156. }
  2157. }
  2158. let currentStack = null;
  2159. const NodeElements = new Map();
  2160. function addMethodChaining( name, nodeElement ) {
  2161. if ( NodeElements.has( name ) ) {
  2162. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2163. return;
  2164. }
  2165. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2166. NodeElements.set( name, nodeElement );
  2167. }
  2168. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2169. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2170. const shaderNodeHandler = {
  2171. setup( NodeClosure, params ) {
  2172. const inputs = params.shift();
  2173. return NodeClosure( nodeObjects( inputs ), ...params );
  2174. },
  2175. get( node, prop, nodeObj ) {
  2176. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2177. if ( node.isStackNode !== true && prop === 'assign' ) {
  2178. return ( ...params ) => {
  2179. currentStack.assign( nodeObj, ...params );
  2180. return nodeObj;
  2181. };
  2182. } else if ( NodeElements.has( prop ) ) {
  2183. const nodeElement = NodeElements.get( prop );
  2184. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2185. } else if ( prop === 'toVarIntent' ) {
  2186. return () => nodeObj;
  2187. } else if ( prop === 'self' ) {
  2188. return node;
  2189. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2190. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2191. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2192. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2193. // accessing properties ( swizzle )
  2194. prop = parseSwizzle( prop );
  2195. return nodeObject( new SplitNode( nodeObj, prop ) );
  2196. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2197. // set properties ( swizzle ) and sort to xyzw sequence
  2198. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2199. return ( value ) => nodeObject( new SetNode( node, prop, nodeObject( value ) ) );
  2200. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2201. // set properties ( swizzle ) and sort to xyzw sequence
  2202. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2203. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2204. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2205. // accessing property
  2206. if ( prop === 'width' ) prop = 'x';
  2207. else if ( prop === 'height' ) prop = 'y';
  2208. else if ( prop === 'depth' ) prop = 'z';
  2209. return nodeObject( new SplitNode( node, prop ) );
  2210. } else if ( /^\d+$/.test( prop ) === true ) {
  2211. // accessing array
  2212. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2213. } else if ( /^get$/.test( prop ) === true ) {
  2214. // accessing properties
  2215. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2216. }
  2217. }
  2218. return Reflect.get( node, prop, nodeObj );
  2219. },
  2220. set( node, prop, value, nodeObj ) {
  2221. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2222. // setting properties
  2223. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2224. nodeObj[ prop ].assign( value );
  2225. return true;
  2226. }
  2227. }
  2228. return Reflect.set( node, prop, value, nodeObj );
  2229. }
  2230. };
  2231. const nodeObjectsCacheMap = new WeakMap();
  2232. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2233. const ShaderNodeObject = function ( obj, altType = null ) {
  2234. const type = getValueType( obj );
  2235. if ( type === 'node' ) {
  2236. let nodeObject = nodeObjectsCacheMap.get( obj );
  2237. if ( nodeObject === undefined ) {
  2238. nodeObject = new Proxy( obj, shaderNodeHandler );
  2239. nodeObjectsCacheMap.set( obj, nodeObject );
  2240. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2241. }
  2242. return nodeObject;
  2243. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2244. return nodeObject( getConstNode( obj, altType ) );
  2245. } else if ( type === 'shader' ) {
  2246. return obj.isFn ? obj : Fn( obj );
  2247. }
  2248. return obj;
  2249. };
  2250. const ShaderNodeObjects = function ( objects, altType = null ) {
  2251. for ( const name in objects ) {
  2252. objects[ name ] = nodeObject( objects[ name ], altType );
  2253. }
  2254. return objects;
  2255. };
  2256. const ShaderNodeArray = function ( array, altType = null ) {
  2257. const len = array.length;
  2258. for ( let i = 0; i < len; i ++ ) {
  2259. array[ i ] = nodeObject( array[ i ], altType );
  2260. }
  2261. return array;
  2262. };
  2263. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2264. function assignNode( node ) {
  2265. if ( settings !== null ) {
  2266. node = nodeObject( Object.assign( node, settings ) );
  2267. if ( settings.intent === true ) {
  2268. node = node.toVarIntent();
  2269. }
  2270. } else {
  2271. node = nodeObject( node );
  2272. }
  2273. return node;
  2274. }
  2275. let fn, name = scope, minParams, maxParams;
  2276. function verifyParamsLimit( params ) {
  2277. let tslName;
  2278. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2279. else tslName = NodeClass.type;
  2280. if ( minParams !== undefined && params.length < minParams ) {
  2281. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2282. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2283. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2284. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2285. return params.slice( 0, maxParams );
  2286. }
  2287. return params;
  2288. }
  2289. if ( scope === null ) {
  2290. fn = ( ...params ) => {
  2291. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2292. };
  2293. } else if ( factor !== null ) {
  2294. factor = nodeObject( factor );
  2295. fn = ( ...params ) => {
  2296. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2297. };
  2298. } else {
  2299. fn = ( ...params ) => {
  2300. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2301. };
  2302. }
  2303. fn.setParameterLength = ( ...params ) => {
  2304. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2305. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2306. return fn;
  2307. };
  2308. fn.setName = ( value ) => {
  2309. name = value;
  2310. return fn;
  2311. };
  2312. return fn;
  2313. };
  2314. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2315. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2316. };
  2317. class ShaderCallNodeInternal extends Node {
  2318. constructor( shaderNode, rawInputs ) {
  2319. super();
  2320. this.shaderNode = shaderNode;
  2321. this.rawInputs = rawInputs;
  2322. this.isShaderCallNodeInternal = true;
  2323. }
  2324. getNodeType( builder ) {
  2325. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2326. }
  2327. getMemberType( builder, name ) {
  2328. return this.getOutputNode( builder ).getMemberType( builder, name );
  2329. }
  2330. call( builder ) {
  2331. const { shaderNode, rawInputs } = this;
  2332. const properties = builder.getNodeProperties( shaderNode );
  2333. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2334. const subBuildProperty = subBuild || 'default';
  2335. if ( properties[ subBuildProperty ] ) {
  2336. return properties[ subBuildProperty ];
  2337. }
  2338. //
  2339. const previousSubBuildFn = builder.subBuildFn;
  2340. builder.subBuildFn = subBuild;
  2341. let result = null;
  2342. if ( shaderNode.layout ) {
  2343. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2344. if ( functionNodesCacheMap === undefined ) {
  2345. functionNodesCacheMap = new WeakMap();
  2346. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2347. }
  2348. let functionNode = functionNodesCacheMap.get( shaderNode );
  2349. if ( functionNode === undefined ) {
  2350. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2351. functionNodesCacheMap.set( shaderNode, functionNode );
  2352. }
  2353. builder.addInclude( functionNode );
  2354. //
  2355. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2356. result = nodeObject( functionNode.call( inputs ) );
  2357. } else {
  2358. const secureNodeBuilder = new Proxy( builder, {
  2359. get: ( target, property, receiver ) => {
  2360. let value;
  2361. if ( Symbol.iterator === property ) {
  2362. value = function* () {
  2363. yield undefined;
  2364. };
  2365. } else {
  2366. value = Reflect.get( target, property, receiver );
  2367. }
  2368. return value;
  2369. }
  2370. } );
  2371. //
  2372. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2373. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2374. const jsFunc = shaderNode.jsFunc;
  2375. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2376. result = nodeObject( outputNode );
  2377. }
  2378. builder.subBuildFn = previousSubBuildFn;
  2379. if ( shaderNode.once ) {
  2380. properties[ subBuildProperty ] = result;
  2381. }
  2382. return result;
  2383. }
  2384. setupOutput( builder ) {
  2385. builder.addStack();
  2386. builder.stack.outputNode = this.call( builder );
  2387. return builder.removeStack();
  2388. }
  2389. getOutputNode( builder ) {
  2390. const properties = builder.getNodeProperties( this );
  2391. const subBuildOutput = builder.getSubBuildOutput( this );
  2392. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2393. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2394. return properties[ subBuildOutput ];
  2395. }
  2396. build( builder, output = null ) {
  2397. let result = null;
  2398. const buildStage = builder.getBuildStage();
  2399. const properties = builder.getNodeProperties( this );
  2400. const subBuildOutput = builder.getSubBuildOutput( this );
  2401. const outputNode = this.getOutputNode( builder );
  2402. if ( buildStage === 'setup' ) {
  2403. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2404. if ( properties[ subBuildInitialized ] !== true ) {
  2405. properties[ subBuildInitialized ] = true;
  2406. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2407. properties[ subBuildOutput ].build( builder );
  2408. // If the shaderNode has subBuilds, add them to the chaining nodes
  2409. // so they can be built later in the build process.
  2410. if ( this.shaderNode.subBuilds ) {
  2411. for ( const node of builder.chaining ) {
  2412. const nodeData = builder.getDataFromNode( node, 'any' );
  2413. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2414. for ( const subBuild of this.shaderNode.subBuilds ) {
  2415. nodeData.subBuilds.add( subBuild );
  2416. }
  2417. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2418. }
  2419. }
  2420. }
  2421. result = properties[ subBuildOutput ];
  2422. } else if ( buildStage === 'analyze' ) {
  2423. outputNode.build( builder, output );
  2424. } else if ( buildStage === 'generate' ) {
  2425. result = outputNode.build( builder, output ) || '';
  2426. }
  2427. return result;
  2428. }
  2429. }
  2430. function getLayoutParameters( params ) {
  2431. let output;
  2432. nodeObjects( params );
  2433. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2434. if ( isArrayAsParameter ) {
  2435. output = [ ...params ];
  2436. } else {
  2437. output = params[ 0 ];
  2438. }
  2439. return output;
  2440. }
  2441. function getProxyParameters( params ) {
  2442. let index = 0;
  2443. nodeObjects( params );
  2444. return new Proxy( params, {
  2445. get: ( target, property, receiver ) => {
  2446. let value;
  2447. if ( property === 'length' ) {
  2448. value = params.length;
  2449. return value;
  2450. }
  2451. if ( Symbol.iterator === property ) {
  2452. value = function* () {
  2453. for ( const inputNode of params ) {
  2454. yield nodeObject( inputNode );
  2455. }
  2456. };
  2457. } else {
  2458. if ( params.length > 0 ) {
  2459. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2460. const objectTarget = params[ 0 ];
  2461. if ( objectTarget[ property ] === undefined ) {
  2462. value = objectTarget[ index ++ ];
  2463. } else {
  2464. value = Reflect.get( objectTarget, property, receiver );
  2465. }
  2466. } else if ( params[ 0 ] instanceof Node ) {
  2467. if ( params[ property ] === undefined ) {
  2468. value = params[ index ++ ];
  2469. } else {
  2470. value = Reflect.get( params, property, receiver );
  2471. }
  2472. }
  2473. } else {
  2474. value = Reflect.get( target, property, receiver );
  2475. }
  2476. value = nodeObject( value );
  2477. }
  2478. return value;
  2479. }
  2480. } );
  2481. }
  2482. class ShaderNodeInternal extends Node {
  2483. constructor( jsFunc, nodeType ) {
  2484. super( nodeType );
  2485. this.jsFunc = jsFunc;
  2486. this.layout = null;
  2487. this.global = true;
  2488. this.once = false;
  2489. }
  2490. setLayout( layout ) {
  2491. this.layout = layout;
  2492. return this;
  2493. }
  2494. call( rawInputs = null ) {
  2495. return nodeObject( new ShaderCallNodeInternal( this, rawInputs ) );
  2496. }
  2497. setup() {
  2498. return this.call();
  2499. }
  2500. }
  2501. const bools = [ false, true ];
  2502. const uints = [ 0, 1, 2, 3 ];
  2503. const ints = [ -1, -2 ];
  2504. 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 ];
  2505. const boolsCacheMap = new Map();
  2506. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2507. const uintsCacheMap = new Map();
  2508. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2509. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2510. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2511. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2512. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2513. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2514. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2515. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2516. const getConstNode = ( value, type ) => {
  2517. if ( constNodesCacheMap.has( value ) ) {
  2518. return constNodesCacheMap.get( value );
  2519. } else if ( value.isNode === true ) {
  2520. return value;
  2521. } else {
  2522. return new ConstNode( value, type );
  2523. }
  2524. };
  2525. const ConvertType = function ( type, cacheMap = null ) {
  2526. return ( ...params ) => {
  2527. for ( const param of params ) {
  2528. if ( param === undefined ) {
  2529. console.error( `THREE.TSL: Invalid parameter for the type "${ type }".` );
  2530. return nodeObject( new ConstNode( 0, type ) );
  2531. }
  2532. }
  2533. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2534. const paramType = typeof param;
  2535. return paramType !== 'object' && paramType !== 'function';
  2536. } ) ) ) {
  2537. params = [ getValueFromType( type, ...params ) ];
  2538. }
  2539. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2540. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2541. }
  2542. if ( params.length === 1 ) {
  2543. const node = getConstNode( params[ 0 ], type );
  2544. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2545. return nodeObjectIntent( new ConvertNode( node, type ) );
  2546. }
  2547. const nodes = params.map( param => getConstNode( param ) );
  2548. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2549. };
  2550. };
  2551. // exports
  2552. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2553. // utils
  2554. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2555. // shader node base
  2556. function ShaderNode( jsFunc, nodeType ) {
  2557. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2558. }
  2559. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2560. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2561. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2562. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2563. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2564. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2565. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2566. let fnId = 0;
  2567. class FnNode extends Node {
  2568. constructor( jsFunc, layout = null ) {
  2569. super();
  2570. let nodeType = null;
  2571. if ( layout !== null ) {
  2572. if ( typeof layout === 'object' ) {
  2573. nodeType = layout.return;
  2574. } else {
  2575. if ( typeof layout === 'string' ) {
  2576. nodeType = layout;
  2577. } else {
  2578. console.error( 'THREE.TSL: Invalid layout type.' );
  2579. }
  2580. layout = null;
  2581. }
  2582. }
  2583. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2584. if ( layout !== null ) {
  2585. this.setLayout( layout );
  2586. }
  2587. this.isFn = true;
  2588. }
  2589. setLayout( layout ) {
  2590. const nodeType = this.shaderNode.nodeType;
  2591. if ( typeof layout.inputs !== 'object' ) {
  2592. const fullLayout = {
  2593. name: 'fn' + fnId ++,
  2594. type: nodeType,
  2595. inputs: []
  2596. };
  2597. for ( const name in layout ) {
  2598. if ( name === 'return' ) continue;
  2599. fullLayout.inputs.push( {
  2600. name: name,
  2601. type: layout[ name ]
  2602. } );
  2603. }
  2604. layout = fullLayout;
  2605. }
  2606. this.shaderNode.setLayout( layout );
  2607. return this;
  2608. }
  2609. getNodeType( builder ) {
  2610. return this.shaderNode.getNodeType( builder ) || 'float';
  2611. }
  2612. call( ...params ) {
  2613. const fnCall = this.shaderNode.call( params );
  2614. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2615. return fnCall.toVarIntent();
  2616. }
  2617. once( subBuilds = null ) {
  2618. this.shaderNode.once = true;
  2619. this.shaderNode.subBuilds = subBuilds;
  2620. return this;
  2621. }
  2622. generate( builder ) {
  2623. const type = this.getNodeType( builder );
  2624. console.error( 'THREE.TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2625. return builder.generateConst( type );
  2626. }
  2627. }
  2628. function Fn( jsFunc, layout = null ) {
  2629. const instance = new FnNode( jsFunc, layout );
  2630. return new Proxy( () => {}, {
  2631. apply( target, thisArg, params ) {
  2632. return instance.call( ...params );
  2633. },
  2634. get( target, prop, receiver ) {
  2635. return Reflect.get( instance, prop, receiver );
  2636. },
  2637. set( target, prop, value, receiver ) {
  2638. return Reflect.set( instance, prop, value, receiver );
  2639. }
  2640. } );
  2641. }
  2642. //
  2643. const setCurrentStack = ( stack ) => {
  2644. currentStack = stack;
  2645. };
  2646. const getCurrentStack = () => currentStack;
  2647. /**
  2648. * Represent a conditional node using if/else statements.
  2649. *
  2650. * ```js
  2651. * If( condition, function )
  2652. * .ElseIf( condition, function )
  2653. * .Else( function )
  2654. * ```
  2655. * @tsl
  2656. * @function
  2657. * @param {...any} params - The parameters for the conditional node.
  2658. * @returns {StackNode} The conditional node.
  2659. */
  2660. const If = ( ...params ) => currentStack.If( ...params );
  2661. /**
  2662. * Represent a conditional node using switch/case statements.
  2663. *
  2664. * ```js
  2665. * Switch( value )
  2666. * .Case( 1, function )
  2667. * .Case( 2, 3, 4, function )
  2668. * .Default( function )
  2669. * ```
  2670. * @tsl
  2671. * @function
  2672. * @param {...any} params - The parameters for the conditional node.
  2673. * @returns {StackNode} The conditional node.
  2674. */
  2675. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2676. /**
  2677. * Add the given node to the current stack.
  2678. *
  2679. * @param {Node} node - The node to add.
  2680. * @returns {Node} The node that was added to the stack.
  2681. */
  2682. function Stack( node ) {
  2683. if ( currentStack ) currentStack.add( node );
  2684. return node;
  2685. }
  2686. addMethodChaining( 'toStack', Stack );
  2687. // types
  2688. const color = new ConvertType( 'color' );
  2689. const float = new ConvertType( 'float', cacheMaps.float );
  2690. const int = new ConvertType( 'int', cacheMaps.ints );
  2691. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2692. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2693. const vec2 = new ConvertType( 'vec2' );
  2694. const ivec2 = new ConvertType( 'ivec2' );
  2695. const uvec2 = new ConvertType( 'uvec2' );
  2696. const bvec2 = new ConvertType( 'bvec2' );
  2697. const vec3 = new ConvertType( 'vec3' );
  2698. const ivec3 = new ConvertType( 'ivec3' );
  2699. const uvec3 = new ConvertType( 'uvec3' );
  2700. const bvec3 = new ConvertType( 'bvec3' );
  2701. const vec4 = new ConvertType( 'vec4' );
  2702. const ivec4 = new ConvertType( 'ivec4' );
  2703. const uvec4 = new ConvertType( 'uvec4' );
  2704. const bvec4 = new ConvertType( 'bvec4' );
  2705. const mat2 = new ConvertType( 'mat2' );
  2706. const mat3 = new ConvertType( 'mat3' );
  2707. const mat4 = new ConvertType( 'mat4' );
  2708. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2709. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2710. addMethodChaining( 'toColor', color );
  2711. addMethodChaining( 'toFloat', float );
  2712. addMethodChaining( 'toInt', int );
  2713. addMethodChaining( 'toUint', uint );
  2714. addMethodChaining( 'toBool', bool );
  2715. addMethodChaining( 'toVec2', vec2 );
  2716. addMethodChaining( 'toIVec2', ivec2 );
  2717. addMethodChaining( 'toUVec2', uvec2 );
  2718. addMethodChaining( 'toBVec2', bvec2 );
  2719. addMethodChaining( 'toVec3', vec3 );
  2720. addMethodChaining( 'toIVec3', ivec3 );
  2721. addMethodChaining( 'toUVec3', uvec3 );
  2722. addMethodChaining( 'toBVec3', bvec3 );
  2723. addMethodChaining( 'toVec4', vec4 );
  2724. addMethodChaining( 'toIVec4', ivec4 );
  2725. addMethodChaining( 'toUVec4', uvec4 );
  2726. addMethodChaining( 'toBVec4', bvec4 );
  2727. addMethodChaining( 'toMat2', mat2 );
  2728. addMethodChaining( 'toMat3', mat3 );
  2729. addMethodChaining( 'toMat4', mat4 );
  2730. // basic nodes
  2731. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2732. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2733. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2734. addMethodChaining( 'element', element );
  2735. addMethodChaining( 'convert', convert );
  2736. // deprecated
  2737. /**
  2738. * @tsl
  2739. * @function
  2740. * @deprecated since r176. Use {@link Stack} instead.
  2741. *
  2742. * @param {Node} node - The node to add.
  2743. * @returns {Function}
  2744. */
  2745. const append = ( node ) => { // @deprecated, r176
  2746. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2747. return Stack( node );
  2748. };
  2749. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2750. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2751. return Stack( node );
  2752. } );
  2753. /**
  2754. * This class represents a shader property. It can be used
  2755. * to explicitly define a property and assign a value to it.
  2756. *
  2757. * ```js
  2758. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2759. *```
  2760. * `PropertyNode` is used by the engine to predefined common material properties
  2761. * for TSL code.
  2762. *
  2763. * @augments Node
  2764. */
  2765. class PropertyNode extends Node {
  2766. static get type() {
  2767. return 'PropertyNode';
  2768. }
  2769. /**
  2770. * Constructs a new property node.
  2771. *
  2772. * @param {string} nodeType - The type of the node.
  2773. * @param {?string} [name=null] - The name of the property in the shader.
  2774. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2775. */
  2776. constructor( nodeType, name = null, varying = false ) {
  2777. super( nodeType );
  2778. /**
  2779. * The name of the property in the shader. If no name is defined,
  2780. * the node system auto-generates one.
  2781. *
  2782. * @type {?string}
  2783. * @default null
  2784. */
  2785. this.name = name;
  2786. /**
  2787. * Whether this property is a varying or not.
  2788. *
  2789. * @type {boolean}
  2790. * @default false
  2791. */
  2792. this.varying = varying;
  2793. /**
  2794. * This flag can be used for type testing.
  2795. *
  2796. * @type {boolean}
  2797. * @readonly
  2798. * @default true
  2799. */
  2800. this.isPropertyNode = true;
  2801. /**
  2802. * This flag is used for global cache.
  2803. *
  2804. * @type {boolean}
  2805. * @default true
  2806. */
  2807. this.global = true;
  2808. }
  2809. getHash( builder ) {
  2810. return this.name || super.getHash( builder );
  2811. }
  2812. generate( builder ) {
  2813. let nodeVar;
  2814. if ( this.varying === true ) {
  2815. nodeVar = builder.getVaryingFromNode( this, this.name );
  2816. nodeVar.needsInterpolation = true;
  2817. } else {
  2818. nodeVar = builder.getVarFromNode( this, this.name );
  2819. }
  2820. return builder.getPropertyName( nodeVar );
  2821. }
  2822. }
  2823. /**
  2824. * TSL function for creating a property node.
  2825. *
  2826. * @tsl
  2827. * @function
  2828. * @param {string} type - The type of the node.
  2829. * @param {?string} [name=null] - The name of the property in the shader.
  2830. * @returns {PropertyNode}
  2831. */
  2832. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2833. /**
  2834. * TSL function for creating a varying property node.
  2835. *
  2836. * @tsl
  2837. * @function
  2838. * @param {string} type - The type of the node.
  2839. * @param {?string} [name=null] - The name of the varying in the shader.
  2840. * @returns {PropertyNode}
  2841. */
  2842. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2843. /**
  2844. * TSL object that represents the shader variable `DiffuseColor`.
  2845. *
  2846. * @tsl
  2847. * @type {PropertyNode<vec4>}
  2848. */
  2849. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2850. /**
  2851. * TSL object that represents the shader variable `EmissiveColor`.
  2852. *
  2853. * @tsl
  2854. * @type {PropertyNode<vec3>}
  2855. */
  2856. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2857. /**
  2858. * TSL object that represents the shader variable `Roughness`.
  2859. *
  2860. * @tsl
  2861. * @type {PropertyNode<float>}
  2862. */
  2863. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2864. /**
  2865. * TSL object that represents the shader variable `Metalness`.
  2866. *
  2867. * @tsl
  2868. * @type {PropertyNode<float>}
  2869. */
  2870. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2871. /**
  2872. * TSL object that represents the shader variable `Clearcoat`.
  2873. *
  2874. * @tsl
  2875. * @type {PropertyNode<float>}
  2876. */
  2877. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2878. /**
  2879. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2880. *
  2881. * @tsl
  2882. * @type {PropertyNode<float>}
  2883. */
  2884. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2885. /**
  2886. * TSL object that represents the shader variable `Sheen`.
  2887. *
  2888. * @tsl
  2889. * @type {PropertyNode<vec3>}
  2890. */
  2891. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2892. /**
  2893. * TSL object that represents the shader variable `SheenRoughness`.
  2894. *
  2895. * @tsl
  2896. * @type {PropertyNode<float>}
  2897. */
  2898. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2899. /**
  2900. * TSL object that represents the shader variable `Iridescence`.
  2901. *
  2902. * @tsl
  2903. * @type {PropertyNode<float>}
  2904. */
  2905. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2906. /**
  2907. * TSL object that represents the shader variable `IridescenceIOR`.
  2908. *
  2909. * @tsl
  2910. * @type {PropertyNode<float>}
  2911. */
  2912. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2913. /**
  2914. * TSL object that represents the shader variable `IridescenceThickness`.
  2915. *
  2916. * @tsl
  2917. * @type {PropertyNode<float>}
  2918. */
  2919. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2920. /**
  2921. * TSL object that represents the shader variable `AlphaT`.
  2922. *
  2923. * @tsl
  2924. * @type {PropertyNode<float>}
  2925. */
  2926. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2927. /**
  2928. * TSL object that represents the shader variable `Anisotropy`.
  2929. *
  2930. * @tsl
  2931. * @type {PropertyNode<float>}
  2932. */
  2933. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2934. /**
  2935. * TSL object that represents the shader variable `AnisotropyT`.
  2936. *
  2937. * @tsl
  2938. * @type {PropertyNode<vec3>}
  2939. */
  2940. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2941. /**
  2942. * TSL object that represents the shader variable `AnisotropyB`.
  2943. *
  2944. * @tsl
  2945. * @type {PropertyNode<vec3>}
  2946. */
  2947. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2948. /**
  2949. * TSL object that represents the shader variable `SpecularColor`.
  2950. *
  2951. * @tsl
  2952. * @type {PropertyNode<color>}
  2953. */
  2954. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2955. /**
  2956. * TSL object that represents the shader variable `SpecularF90`.
  2957. *
  2958. * @tsl
  2959. * @type {PropertyNode<float>}
  2960. */
  2961. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2962. /**
  2963. * TSL object that represents the shader variable `Shininess`.
  2964. *
  2965. * @tsl
  2966. * @type {PropertyNode<float>}
  2967. */
  2968. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2969. /**
  2970. * TSL object that represents the shader variable `Output`.
  2971. *
  2972. * @tsl
  2973. * @type {PropertyNode<vec4>}
  2974. */
  2975. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2976. /**
  2977. * TSL object that represents the shader variable `dashSize`.
  2978. *
  2979. * @tsl
  2980. * @type {PropertyNode<float>}
  2981. */
  2982. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2983. /**
  2984. * TSL object that represents the shader variable `gapSize`.
  2985. *
  2986. * @tsl
  2987. * @type {PropertyNode<float>}
  2988. */
  2989. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2990. /**
  2991. * TSL object that represents the shader variable `pointWidth`.
  2992. *
  2993. * @tsl
  2994. * @type {PropertyNode<float>}
  2995. */
  2996. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2997. /**
  2998. * TSL object that represents the shader variable `IOR`.
  2999. *
  3000. * @tsl
  3001. * @type {PropertyNode<float>}
  3002. */
  3003. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3004. /**
  3005. * TSL object that represents the shader variable `Transmission`.
  3006. *
  3007. * @tsl
  3008. * @type {PropertyNode<float>}
  3009. */
  3010. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3011. /**
  3012. * TSL object that represents the shader variable `Thickness`.
  3013. *
  3014. * @tsl
  3015. * @type {PropertyNode<float>}
  3016. */
  3017. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3018. /**
  3019. * TSL object that represents the shader variable `AttenuationDistance`.
  3020. *
  3021. * @tsl
  3022. * @type {PropertyNode<float>}
  3023. */
  3024. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3025. /**
  3026. * TSL object that represents the shader variable `AttenuationColor`.
  3027. *
  3028. * @tsl
  3029. * @type {PropertyNode<color>}
  3030. */
  3031. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3032. /**
  3033. * TSL object that represents the shader variable `Dispersion`.
  3034. *
  3035. * @tsl
  3036. * @type {PropertyNode<float>}
  3037. */
  3038. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3039. /**
  3040. * This node can be used to group single instances of {@link UniformNode}
  3041. * and manage them as a uniform buffer.
  3042. *
  3043. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3044. * will be used when defining the {@link UniformNode#groupNode} property.
  3045. *
  3046. * - `objectGroup`: Uniform buffer per object.
  3047. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3048. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3049. *
  3050. * @augments Node
  3051. */
  3052. class UniformGroupNode extends Node {
  3053. static get type() {
  3054. return 'UniformGroupNode';
  3055. }
  3056. /**
  3057. * Constructs a new uniform group node.
  3058. *
  3059. * @param {string} name - The name of the uniform group node.
  3060. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3061. * @param {number} [order=1] - Influences the internal sorting.
  3062. */
  3063. constructor( name, shared = false, order = 1 ) {
  3064. super( 'string' );
  3065. /**
  3066. * The name of the uniform group node.
  3067. *
  3068. * @type {string}
  3069. */
  3070. this.name = name;
  3071. /**
  3072. * Whether this uniform group node is shared or not.
  3073. *
  3074. * @type {boolean}
  3075. * @default false
  3076. */
  3077. this.shared = shared;
  3078. /**
  3079. * Influences the internal sorting.
  3080. * TODO: Add details when this property should be changed.
  3081. *
  3082. * @type {number}
  3083. * @default 1
  3084. */
  3085. this.order = order;
  3086. /**
  3087. * This flag can be used for type testing.
  3088. *
  3089. * @type {boolean}
  3090. * @readonly
  3091. * @default true
  3092. */
  3093. this.isUniformGroup = true;
  3094. }
  3095. serialize( data ) {
  3096. super.serialize( data );
  3097. data.name = this.name;
  3098. data.version = this.version;
  3099. data.shared = this.shared;
  3100. }
  3101. deserialize( data ) {
  3102. super.deserialize( data );
  3103. this.name = data.name;
  3104. this.version = data.version;
  3105. this.shared = data.shared;
  3106. }
  3107. }
  3108. /**
  3109. * TSL function for creating a uniform group node with the given name.
  3110. *
  3111. * @tsl
  3112. * @function
  3113. * @param {string} name - The name of the uniform group node.
  3114. * @returns {UniformGroupNode}
  3115. */
  3116. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3117. /**
  3118. * TSL function for creating a shared uniform group node with the given name and order.
  3119. *
  3120. * @tsl
  3121. * @function
  3122. * @param {string} name - The name of the uniform group node.
  3123. * @param {number} [order=0] - Influences the internal sorting.
  3124. * @returns {UniformGroupNode}
  3125. */
  3126. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3127. /**
  3128. * TSL object that represents a shared uniform group node which is updated once per frame.
  3129. *
  3130. * @tsl
  3131. * @type {UniformGroupNode}
  3132. */
  3133. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3134. /**
  3135. * TSL object that represents a shared uniform group node which is updated once per render.
  3136. *
  3137. * @tsl
  3138. * @type {UniformGroupNode}
  3139. */
  3140. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3141. /**
  3142. * TSL object that represents a uniform group node which is updated once per object.
  3143. *
  3144. * @tsl
  3145. * @type {UniformGroupNode}
  3146. */
  3147. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3148. /**
  3149. * Class for representing a uniform.
  3150. *
  3151. * @augments InputNode
  3152. */
  3153. class UniformNode extends InputNode {
  3154. static get type() {
  3155. return 'UniformNode';
  3156. }
  3157. /**
  3158. * Constructs a new uniform node.
  3159. *
  3160. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3161. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3162. */
  3163. constructor( value, nodeType = null ) {
  3164. super( value, nodeType );
  3165. /**
  3166. * This flag can be used for type testing.
  3167. *
  3168. * @type {boolean}
  3169. * @readonly
  3170. * @default true
  3171. */
  3172. this.isUniformNode = true;
  3173. /**
  3174. * The name or label of the uniform.
  3175. *
  3176. * @type {string}
  3177. * @default ''
  3178. */
  3179. this.name = '';
  3180. /**
  3181. * The uniform group of this uniform. By default, uniforms are
  3182. * managed per object but they might belong to a shared group
  3183. * which is updated per frame or render call.
  3184. *
  3185. * @type {UniformGroupNode}
  3186. */
  3187. this.groupNode = objectGroup;
  3188. }
  3189. /**
  3190. * Sets the {@link UniformNode#name} property.
  3191. *
  3192. * @param {string} name - The name of the uniform.
  3193. * @return {UniformNode} A reference to this node.
  3194. */
  3195. setName( name ) {
  3196. this.name = name;
  3197. return this;
  3198. }
  3199. /**
  3200. * Sets the {@link UniformNode#name} property.
  3201. *
  3202. * @deprecated
  3203. * @param {string} name - The name of the uniform.
  3204. * @return {UniformNode} A reference to this node.
  3205. */
  3206. label( name ) {
  3207. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3208. return this.setName( name );
  3209. }
  3210. /**
  3211. * Sets the {@link UniformNode#groupNode} property.
  3212. *
  3213. * @param {UniformGroupNode} group - The uniform group.
  3214. * @return {UniformNode} A reference to this node.
  3215. */
  3216. setGroup( group ) {
  3217. this.groupNode = group;
  3218. return this;
  3219. }
  3220. /**
  3221. * Returns the {@link UniformNode#groupNode}.
  3222. *
  3223. * @return {UniformGroupNode} The uniform group.
  3224. */
  3225. getGroup() {
  3226. return this.groupNode;
  3227. }
  3228. /**
  3229. * By default, this method returns the result of {@link Node#getHash} but derived
  3230. * classes might overwrite this method with a different implementation.
  3231. *
  3232. * @param {NodeBuilder} builder - The current node builder.
  3233. * @return {string} The uniform hash.
  3234. */
  3235. getUniformHash( builder ) {
  3236. return this.getHash( builder );
  3237. }
  3238. onUpdate( callback, updateType ) {
  3239. const self = this.getSelf();
  3240. callback = callback.bind( self );
  3241. return super.onUpdate( ( frame ) => {
  3242. const value = callback( frame, self );
  3243. if ( value !== undefined ) {
  3244. this.value = value;
  3245. }
  3246. }, updateType );
  3247. }
  3248. getInputType( builder ) {
  3249. let type = super.getInputType( builder );
  3250. if ( type === 'bool' ) {
  3251. type = 'uint';
  3252. }
  3253. return type;
  3254. }
  3255. generate( builder, output ) {
  3256. const type = this.getNodeType( builder );
  3257. const hash = this.getUniformHash( builder );
  3258. let sharedNode = builder.getNodeFromHash( hash );
  3259. if ( sharedNode === undefined ) {
  3260. builder.setHashNode( this, hash );
  3261. sharedNode = this;
  3262. }
  3263. const sharedNodeType = sharedNode.getInputType( builder );
  3264. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3265. const uniformName = builder.getPropertyName( nodeUniform );
  3266. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3267. //
  3268. let snippet = uniformName;
  3269. if ( type === 'bool' ) {
  3270. // cache to variable
  3271. const nodeData = builder.getDataFromNode( this );
  3272. let propertyName = nodeData.propertyName;
  3273. if ( propertyName === undefined ) {
  3274. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3275. propertyName = builder.getPropertyName( nodeVar );
  3276. nodeData.propertyName = propertyName;
  3277. snippet = builder.format( uniformName, sharedNodeType, type );
  3278. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3279. }
  3280. snippet = propertyName;
  3281. }
  3282. return builder.format( snippet, type, output );
  3283. }
  3284. }
  3285. /**
  3286. * TSL function for creating a uniform node.
  3287. *
  3288. * @tsl
  3289. * @function
  3290. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3291. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3292. * @returns {UniformNode}
  3293. */
  3294. const uniform = ( value, type ) => {
  3295. const nodeType = getConstNodeType( type || value );
  3296. if ( nodeType === value ) {
  3297. // if the value is a type but no having a value
  3298. value = getValueFromType( nodeType );
  3299. }
  3300. // @TODO: get ConstNode from .traverse() in the future
  3301. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3302. return nodeObject( new UniformNode( value, nodeType ) );
  3303. };
  3304. /**
  3305. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3306. * ```js
  3307. * const colors = array( [
  3308. * vec3( 1, 0, 0 ),
  3309. * vec3( 0, 1, 0 ),
  3310. * vec3( 0, 0, 1 )
  3311. * ] );
  3312. *
  3313. * const redColor = tintColors.element( 0 );
  3314. *
  3315. * @augments TempNode
  3316. */
  3317. class ArrayNode extends TempNode {
  3318. static get type() {
  3319. return 'ArrayNode';
  3320. }
  3321. /**
  3322. * Constructs a new array node.
  3323. *
  3324. * @param {?string} nodeType - The data type of the elements.
  3325. * @param {number} count - Size of the array.
  3326. * @param {?Array<Node>} [values=null] - Array default values.
  3327. */
  3328. constructor( nodeType, count, values = null ) {
  3329. super( nodeType );
  3330. /**
  3331. * Array size.
  3332. *
  3333. * @type {number}
  3334. */
  3335. this.count = count;
  3336. /**
  3337. * Array default values.
  3338. *
  3339. * @type {?Array<Node>}
  3340. */
  3341. this.values = values;
  3342. /**
  3343. * This flag can be used for type testing.
  3344. *
  3345. * @type {boolean}
  3346. * @readonly
  3347. * @default true
  3348. */
  3349. this.isArrayNode = true;
  3350. }
  3351. /**
  3352. * Returns the number of elements in the node array.
  3353. *
  3354. * @param {NodeBuilder} builder - The current node builder.
  3355. * @return {number} The number of elements in the node array.
  3356. */
  3357. getArrayCount( /*builder*/ ) {
  3358. return this.count;
  3359. }
  3360. /**
  3361. * Returns the node's type.
  3362. *
  3363. * @param {NodeBuilder} builder - The current node builder.
  3364. * @return {string} The type of the node.
  3365. */
  3366. getNodeType( builder ) {
  3367. if ( this.nodeType === null ) {
  3368. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3369. }
  3370. return this.nodeType;
  3371. }
  3372. /**
  3373. * Returns the node's type.
  3374. *
  3375. * @param {NodeBuilder} builder - The current node builder.
  3376. * @return {string} The type of the node.
  3377. */
  3378. getElementType( builder ) {
  3379. return this.getNodeType( builder );
  3380. }
  3381. /**
  3382. * This method builds the output node and returns the resulting array as a shader string.
  3383. *
  3384. * @param {NodeBuilder} builder - The current node builder.
  3385. * @return {string} The generated shader string.
  3386. */
  3387. generate( builder ) {
  3388. const type = this.getNodeType( builder );
  3389. return builder.generateArray( type, this.count, this.values );
  3390. }
  3391. }
  3392. /**
  3393. * TSL function for creating an array node.
  3394. *
  3395. * @tsl
  3396. * @function
  3397. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3398. * or an array containing the default values (e.g., [ vec3() ]).
  3399. * @param {?number} [count] - Size of the array.
  3400. * @returns {ArrayNode}
  3401. */
  3402. const array = ( ...params ) => {
  3403. let node;
  3404. if ( params.length === 1 ) {
  3405. const values = params[ 0 ];
  3406. node = new ArrayNode( null, values.length, values );
  3407. } else {
  3408. const nodeType = params[ 0 ];
  3409. const count = params[ 1 ];
  3410. node = new ArrayNode( nodeType, count );
  3411. }
  3412. return nodeObject( node );
  3413. };
  3414. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3415. /**
  3416. * These node represents an assign operation. Meaning a node is assigned
  3417. * to another node.
  3418. *
  3419. * @augments TempNode
  3420. */
  3421. class AssignNode extends TempNode {
  3422. static get type() {
  3423. return 'AssignNode';
  3424. }
  3425. /**
  3426. * Constructs a new assign node.
  3427. *
  3428. * @param {Node} targetNode - The target node.
  3429. * @param {Node} sourceNode - The source type.
  3430. */
  3431. constructor( targetNode, sourceNode ) {
  3432. super();
  3433. /**
  3434. * The target node.
  3435. *
  3436. * @type {Node}
  3437. */
  3438. this.targetNode = targetNode;
  3439. /**
  3440. * The source node.
  3441. *
  3442. * @type {Node}
  3443. */
  3444. this.sourceNode = sourceNode;
  3445. /**
  3446. * This flag can be used for type testing.
  3447. *
  3448. * @type {boolean}
  3449. * @readonly
  3450. * @default true
  3451. */
  3452. this.isAssignNode = true;
  3453. }
  3454. /**
  3455. * Whether this node is used more than once in context of other nodes. This method
  3456. * is overwritten since it always returns `false` (assigns are unique).
  3457. *
  3458. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3459. */
  3460. hasDependencies() {
  3461. return false;
  3462. }
  3463. getNodeType( builder, output ) {
  3464. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3465. }
  3466. /**
  3467. * Whether a split is required when assigning source to target. This can happen when the component length of
  3468. * target and source data type does not match.
  3469. *
  3470. * @param {NodeBuilder} builder - The current node builder.
  3471. * @return {boolean} Whether a split is required when assigning source to target.
  3472. */
  3473. needsSplitAssign( builder ) {
  3474. const { targetNode } = this;
  3475. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3476. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3477. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3478. return assignDifferentVector;
  3479. }
  3480. return false;
  3481. }
  3482. setup( builder ) {
  3483. const { targetNode, sourceNode } = this;
  3484. const targetProperties = builder.getNodeProperties( targetNode );
  3485. targetProperties.assign = true;
  3486. const properties = builder.getNodeProperties( this );
  3487. properties.sourceNode = sourceNode;
  3488. properties.targetNode = targetNode.context( { assign: true } );
  3489. }
  3490. generate( builder, output ) {
  3491. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3492. const needsSplitAssign = this.needsSplitAssign( builder );
  3493. const target = targetNode.build( builder );
  3494. const targetType = targetNode.getNodeType( builder );
  3495. const source = sourceNode.build( builder, targetType );
  3496. const sourceType = sourceNode.getNodeType( builder );
  3497. const nodeData = builder.getDataFromNode( this );
  3498. //
  3499. let snippet;
  3500. if ( nodeData.initialized === true ) {
  3501. if ( output !== 'void' ) {
  3502. snippet = target;
  3503. }
  3504. } else if ( needsSplitAssign ) {
  3505. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3506. const sourceProperty = builder.getPropertyName( sourceVar );
  3507. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3508. const splitNode = targetNode.node;
  3509. const splitTargetNode = splitNode.node.context( { assign: true } );
  3510. const targetRoot = splitTargetNode.build( builder );
  3511. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3512. const component = splitNode.components[ i ];
  3513. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3514. }
  3515. if ( output !== 'void' ) {
  3516. snippet = target;
  3517. }
  3518. } else {
  3519. snippet = `${ target } = ${ source }`;
  3520. if ( output === 'void' || sourceType === 'void' ) {
  3521. builder.addLineFlowCode( snippet, this );
  3522. if ( output !== 'void' ) {
  3523. snippet = target;
  3524. }
  3525. }
  3526. }
  3527. nodeData.initialized = true;
  3528. return builder.format( snippet, targetType, output );
  3529. }
  3530. }
  3531. /**
  3532. * TSL function for creating an assign node.
  3533. *
  3534. * @tsl
  3535. * @function
  3536. * @param {Node} targetNode - The target node.
  3537. * @param {Node} sourceNode - The source type.
  3538. * @returns {AssignNode}
  3539. */
  3540. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3541. addMethodChaining( 'assign', assign );
  3542. /**
  3543. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3544. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3545. * this logic.
  3546. *
  3547. * @augments TempNode
  3548. */
  3549. class FunctionCallNode extends TempNode {
  3550. static get type() {
  3551. return 'FunctionCallNode';
  3552. }
  3553. /**
  3554. * Constructs a new function call node.
  3555. *
  3556. * @param {?FunctionNode} functionNode - The function node.
  3557. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3558. */
  3559. constructor( functionNode = null, parameters = {} ) {
  3560. super();
  3561. /**
  3562. * The function node.
  3563. *
  3564. * @type {?FunctionNode}
  3565. * @default null
  3566. */
  3567. this.functionNode = functionNode;
  3568. /**
  3569. * The parameters of the function call.
  3570. *
  3571. * @type {Object<string, Node>}
  3572. * @default {}
  3573. */
  3574. this.parameters = parameters;
  3575. }
  3576. /**
  3577. * Sets the parameters of the function call node.
  3578. *
  3579. * @param {Object<string, Node>} parameters - The parameters to set.
  3580. * @return {FunctionCallNode} A reference to this node.
  3581. */
  3582. setParameters( parameters ) {
  3583. this.parameters = parameters;
  3584. return this;
  3585. }
  3586. /**
  3587. * Returns the parameters of the function call node.
  3588. *
  3589. * @return {Object<string, Node>} The parameters of this node.
  3590. */
  3591. getParameters() {
  3592. return this.parameters;
  3593. }
  3594. /**
  3595. * Returns the type of this function call node.
  3596. *
  3597. * @param {NodeBuilder} builder - The current node builder.
  3598. * @returns {string} The type of this node.
  3599. */
  3600. getNodeType( builder ) {
  3601. return this.functionNode.getNodeType( builder );
  3602. }
  3603. /**
  3604. * Returns the function node of this function call node.
  3605. *
  3606. * @param {NodeBuilder} builder - The current node builder.
  3607. * @param {string} [name] - The name of the member.
  3608. * @returns {string} The type of the member.
  3609. */
  3610. getMemberType( builder, name ) {
  3611. return this.functionNode.getMemberType( builder, name );
  3612. }
  3613. generate( builder ) {
  3614. const params = [];
  3615. const functionNode = this.functionNode;
  3616. const inputs = functionNode.getInputs( builder );
  3617. const parameters = this.parameters;
  3618. const generateInput = ( node, inputNode ) => {
  3619. const type = inputNode.type;
  3620. const pointer = type === 'pointer';
  3621. let output;
  3622. if ( pointer ) output = '&' + node.build( builder );
  3623. else output = node.build( builder, type );
  3624. return output;
  3625. };
  3626. if ( Array.isArray( parameters ) ) {
  3627. if ( parameters.length > inputs.length ) {
  3628. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3629. parameters.length = inputs.length;
  3630. } else if ( parameters.length < inputs.length ) {
  3631. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3632. while ( parameters.length < inputs.length ) {
  3633. parameters.push( float( 0 ) );
  3634. }
  3635. }
  3636. for ( let i = 0; i < parameters.length; i ++ ) {
  3637. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3638. }
  3639. } else {
  3640. for ( const inputNode of inputs ) {
  3641. const node = parameters[ inputNode.name ];
  3642. if ( node !== undefined ) {
  3643. params.push( generateInput( node, inputNode ) );
  3644. } else {
  3645. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3646. params.push( generateInput( float( 0 ), inputNode ) );
  3647. }
  3648. }
  3649. }
  3650. const functionName = functionNode.build( builder, 'property' );
  3651. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3652. }
  3653. }
  3654. const call = ( func, ...params ) => {
  3655. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3656. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3657. };
  3658. addMethodChaining( 'call', call );
  3659. const _vectorOperators = {
  3660. '==': 'equal',
  3661. '!=': 'notEqual',
  3662. '<': 'lessThan',
  3663. '>': 'greaterThan',
  3664. '<=': 'lessThanEqual',
  3665. '>=': 'greaterThanEqual',
  3666. '%': 'mod'
  3667. };
  3668. /**
  3669. * This node represents basic mathematical and logical operations like addition,
  3670. * subtraction or comparisons (e.g. `equal()`).
  3671. *
  3672. * @augments TempNode
  3673. */
  3674. class OperatorNode extends TempNode {
  3675. static get type() {
  3676. return 'OperatorNode';
  3677. }
  3678. /**
  3679. * Constructs a new operator node.
  3680. *
  3681. * @param {string} op - The operator.
  3682. * @param {Node} aNode - The first input.
  3683. * @param {Node} bNode - The second input.
  3684. * @param {...Node} params - Additional input parameters.
  3685. */
  3686. constructor( op, aNode, bNode, ...params ) {
  3687. super();
  3688. if ( params.length > 0 ) {
  3689. let finalOp = new OperatorNode( op, aNode, bNode );
  3690. for ( let i = 0; i < params.length - 1; i ++ ) {
  3691. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3692. }
  3693. aNode = finalOp;
  3694. bNode = params[ params.length - 1 ];
  3695. }
  3696. /**
  3697. * The operator.
  3698. *
  3699. * @type {string}
  3700. */
  3701. this.op = op;
  3702. /**
  3703. * The first input.
  3704. *
  3705. * @type {Node}
  3706. */
  3707. this.aNode = aNode;
  3708. /**
  3709. * The second input.
  3710. *
  3711. * @type {Node}
  3712. */
  3713. this.bNode = bNode;
  3714. /**
  3715. * This flag can be used for type testing.
  3716. *
  3717. * @type {boolean}
  3718. * @readonly
  3719. * @default true
  3720. */
  3721. this.isOperatorNode = true;
  3722. }
  3723. /**
  3724. * Returns the operator method name.
  3725. *
  3726. * @param {NodeBuilder} builder - The current node builder.
  3727. * @param {string} output - The output type.
  3728. * @returns {string} The operator method name.
  3729. */
  3730. getOperatorMethod( builder, output ) {
  3731. return builder.getMethod( _vectorOperators[ this.op ], output );
  3732. }
  3733. /**
  3734. * This method is overwritten since the node type is inferred from the operator
  3735. * and the input node types.
  3736. *
  3737. * @param {NodeBuilder} builder - The current node builder.
  3738. * @param {?string} [output=null] - The output type.
  3739. * @return {string} The node type.
  3740. */
  3741. getNodeType( builder, output = null ) {
  3742. const op = this.op;
  3743. const aNode = this.aNode;
  3744. const bNode = this.bNode;
  3745. const typeA = aNode.getNodeType( builder );
  3746. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3747. if ( typeA === 'void' || typeB === 'void' ) {
  3748. return output || 'void';
  3749. } else if ( op === '%' ) {
  3750. return typeA;
  3751. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3752. return builder.getIntegerType( typeA );
  3753. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3754. return 'bool';
  3755. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3756. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3757. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3758. } else {
  3759. // Handle matrix operations
  3760. if ( builder.isMatrix( typeA ) ) {
  3761. if ( typeB === 'float' ) {
  3762. return typeA; // matrix * scalar = matrix
  3763. } else if ( builder.isVector( typeB ) ) {
  3764. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3765. } else if ( builder.isMatrix( typeB ) ) {
  3766. return typeA; // matrix * matrix
  3767. }
  3768. } else if ( builder.isMatrix( typeB ) ) {
  3769. if ( typeA === 'float' ) {
  3770. return typeB; // scalar * matrix = matrix
  3771. } else if ( builder.isVector( typeA ) ) {
  3772. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3773. }
  3774. }
  3775. // Handle non-matrix cases
  3776. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3777. // anytype x anytype: use the greater length vector
  3778. return typeB;
  3779. }
  3780. return typeA;
  3781. }
  3782. }
  3783. generate( builder, output ) {
  3784. const op = this.op;
  3785. const { aNode, bNode } = this;
  3786. const type = this.getNodeType( builder, output );
  3787. let typeA = null;
  3788. let typeB = null;
  3789. if ( type !== 'void' ) {
  3790. typeA = aNode.getNodeType( builder );
  3791. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3792. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3793. if ( builder.isVector( typeA ) ) {
  3794. typeB = typeA;
  3795. } else if ( builder.isVector( typeB ) ) {
  3796. typeA = typeB;
  3797. } else if ( typeA !== typeB ) {
  3798. typeA = typeB = 'float';
  3799. }
  3800. } else if ( op === '>>' || op === '<<' ) {
  3801. typeA = type;
  3802. typeB = builder.changeComponentType( typeB, 'uint' );
  3803. } else if ( op === '%' ) {
  3804. typeA = type;
  3805. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3806. } else if ( builder.isMatrix( typeA ) ) {
  3807. if ( typeB === 'float' ) {
  3808. // Keep matrix type for typeA, but ensure typeB stays float
  3809. typeB = 'float';
  3810. } else if ( builder.isVector( typeB ) ) {
  3811. // matrix x vector
  3812. typeB = builder.getVectorFromMatrix( typeA );
  3813. } else if ( builder.isMatrix( typeB ) ) ; else {
  3814. typeA = typeB = type;
  3815. }
  3816. } else if ( builder.isMatrix( typeB ) ) {
  3817. if ( typeA === 'float' ) {
  3818. // Keep matrix type for typeB, but ensure typeA stays float
  3819. typeA = 'float';
  3820. } else if ( builder.isVector( typeA ) ) {
  3821. // vector x matrix
  3822. typeA = builder.getVectorFromMatrix( typeB );
  3823. } else {
  3824. typeA = typeB = type;
  3825. }
  3826. } else {
  3827. // anytype x anytype
  3828. typeA = typeB = type;
  3829. }
  3830. } else {
  3831. typeA = typeB = type;
  3832. }
  3833. const a = aNode.build( builder, typeA );
  3834. const b = bNode ? bNode.build( builder, typeB ) : null;
  3835. const fnOpSnippet = builder.getFunctionOperator( op );
  3836. if ( output !== 'void' ) {
  3837. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3838. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3839. if ( isGLSL ) {
  3840. if ( builder.isVector( typeA ) ) {
  3841. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3842. } else {
  3843. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3844. }
  3845. } else {
  3846. // WGSL
  3847. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3848. }
  3849. } else if ( op === '%' ) {
  3850. if ( builder.isInteger( typeB ) ) {
  3851. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3852. } else {
  3853. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3854. }
  3855. } else if ( op === '!' || op === '~' ) {
  3856. return builder.format( `(${op}${a})`, typeA, output );
  3857. } else if ( fnOpSnippet ) {
  3858. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3859. } else {
  3860. // Handle matrix operations
  3861. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3862. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3863. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3864. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3865. } else {
  3866. let snippet = `( ${ a } ${ op } ${ b } )`;
  3867. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3868. snippet = `all${ snippet }`;
  3869. }
  3870. return builder.format( snippet, type, output );
  3871. }
  3872. }
  3873. } else if ( typeA !== 'void' ) {
  3874. if ( fnOpSnippet ) {
  3875. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3876. } else {
  3877. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3878. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3879. } else {
  3880. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3881. }
  3882. }
  3883. }
  3884. }
  3885. serialize( data ) {
  3886. super.serialize( data );
  3887. data.op = this.op;
  3888. }
  3889. deserialize( data ) {
  3890. super.deserialize( data );
  3891. this.op = data.op;
  3892. }
  3893. }
  3894. /**
  3895. * Returns the addition of two or more value.
  3896. *
  3897. * @tsl
  3898. * @function
  3899. * @param {Node} a - The first input.
  3900. * @param {Node} b - The second input.
  3901. * @param {...Node} params - Additional input parameters.
  3902. * @returns {OperatorNode}
  3903. */
  3904. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3905. /**
  3906. * Returns the subtraction of two or more value.
  3907. *
  3908. * @tsl
  3909. * @function
  3910. * @param {Node} a - The first input.
  3911. * @param {Node} b - The second input.
  3912. * @param {...Node} params - Additional input parameters.
  3913. * @returns {OperatorNode}
  3914. */
  3915. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3916. /**
  3917. * Returns the multiplication of two or more value.
  3918. *
  3919. * @tsl
  3920. * @function
  3921. * @param {Node} a - The first input.
  3922. * @param {Node} b - The second input.
  3923. * @param {...Node} params - Additional input parameters.
  3924. * @returns {OperatorNode}
  3925. */
  3926. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3927. /**
  3928. * Returns the division of two or more value.
  3929. *
  3930. * @tsl
  3931. * @function
  3932. * @param {Node} a - The first input.
  3933. * @param {Node} b - The second input.
  3934. * @param {...Node} params - Additional input parameters.
  3935. * @returns {OperatorNode}
  3936. */
  3937. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3938. /**
  3939. * Computes the remainder of dividing the first node by the second one.
  3940. *
  3941. * @tsl
  3942. * @function
  3943. * @param {Node} a - The first input.
  3944. * @param {Node} b - The second input.
  3945. * @returns {OperatorNode}
  3946. */
  3947. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3948. /**
  3949. * Checks if two nodes are equal.
  3950. *
  3951. * @tsl
  3952. * @function
  3953. * @param {Node} a - The first input.
  3954. * @param {Node} b - The second input.
  3955. * @returns {OperatorNode}
  3956. */
  3957. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3958. /**
  3959. * Checks if two nodes are not equal.
  3960. *
  3961. * @tsl
  3962. * @function
  3963. * @param {Node} a - The first input.
  3964. * @param {Node} b - The second input.
  3965. * @returns {OperatorNode}
  3966. */
  3967. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3968. /**
  3969. * Checks if the first node is less than the second.
  3970. *
  3971. * @tsl
  3972. * @function
  3973. * @param {Node} a - The first input.
  3974. * @param {Node} b - The second input.
  3975. * @returns {OperatorNode}
  3976. */
  3977. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3978. /**
  3979. * Checks if the first node is greater than the second.
  3980. *
  3981. * @tsl
  3982. * @function
  3983. * @param {Node} a - The first input.
  3984. * @param {Node} b - The second input.
  3985. * @returns {OperatorNode}
  3986. */
  3987. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3988. /**
  3989. * Checks if the first node is less than or equal to the second.
  3990. *
  3991. * @tsl
  3992. * @function
  3993. * @param {Node} a - The first input.
  3994. * @param {Node} b - The second input.
  3995. * @returns {OperatorNode}
  3996. */
  3997. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  3998. /**
  3999. * Checks if the first node is greater than or equal to the second.
  4000. *
  4001. * @tsl
  4002. * @function
  4003. * @param {Node} a - The first input.
  4004. * @param {Node} b - The second input.
  4005. * @returns {OperatorNode}
  4006. */
  4007. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4008. /**
  4009. * Performs a logical AND operation on multiple nodes.
  4010. *
  4011. * @tsl
  4012. * @function
  4013. * @param {...Node} nodes - The input nodes to be combined using AND.
  4014. * @returns {OperatorNode}
  4015. */
  4016. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4017. /**
  4018. * Performs a logical OR operation on multiple nodes.
  4019. *
  4020. * @tsl
  4021. * @function
  4022. * @param {...Node} nodes - The input nodes to be combined using OR.
  4023. * @returns {OperatorNode}
  4024. */
  4025. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4026. /**
  4027. * Performs logical NOT on a node.
  4028. *
  4029. * @tsl
  4030. * @function
  4031. * @param {Node} value - The value.
  4032. * @returns {OperatorNode}
  4033. */
  4034. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4035. /**
  4036. * Performs logical XOR on two nodes.
  4037. *
  4038. * @tsl
  4039. * @function
  4040. * @param {Node} a - The first input.
  4041. * @param {Node} b - The second input.
  4042. * @returns {OperatorNode}
  4043. */
  4044. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4045. /**
  4046. * Performs bitwise AND on two nodes.
  4047. *
  4048. * @tsl
  4049. * @function
  4050. * @param {Node} a - The first input.
  4051. * @param {Node} b - The second input.
  4052. * @returns {OperatorNode}
  4053. */
  4054. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4055. /**
  4056. * Performs bitwise NOT on a node.
  4057. *
  4058. * @tsl
  4059. * @function
  4060. * @param {Node} a - The first input.
  4061. * @param {Node} b - The second input.
  4062. * @returns {OperatorNode}
  4063. */
  4064. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  4065. /**
  4066. * Performs bitwise OR on two nodes.
  4067. *
  4068. * @tsl
  4069. * @function
  4070. * @param {Node} a - The first input.
  4071. * @param {Node} b - The second input.
  4072. * @returns {OperatorNode}
  4073. */
  4074. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4075. /**
  4076. * Performs bitwise XOR on two nodes.
  4077. *
  4078. * @tsl
  4079. * @function
  4080. * @param {Node} a - The first input.
  4081. * @param {Node} b - The second input.
  4082. * @returns {OperatorNode}
  4083. */
  4084. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4085. /**
  4086. * Shifts a node to the left.
  4087. *
  4088. * @tsl
  4089. * @function
  4090. * @param {Node} a - The node to shift.
  4091. * @param {Node} b - The value to shift.
  4092. * @returns {OperatorNode}
  4093. */
  4094. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4095. /**
  4096. * Shifts a node to the right.
  4097. *
  4098. * @tsl
  4099. * @function
  4100. * @param {Node} a - The node to shift.
  4101. * @param {Node} b - The value to shift.
  4102. * @returns {OperatorNode}
  4103. */
  4104. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4105. /**
  4106. * Increments a node by 1.
  4107. *
  4108. * @tsl
  4109. * @function
  4110. * @param {Node} a - The node to increment.
  4111. * @returns {OperatorNode}
  4112. */
  4113. const incrementBefore = Fn( ( [ a ] ) => {
  4114. a.addAssign( 1 );
  4115. return a;
  4116. } );
  4117. /**
  4118. * Decrements a node by 1.
  4119. *
  4120. * @tsl
  4121. * @function
  4122. * @param {Node} a - The node to decrement.
  4123. * @returns {OperatorNode}
  4124. */
  4125. const decrementBefore = Fn( ( [ a ] ) => {
  4126. a.subAssign( 1 );
  4127. return a;
  4128. } );
  4129. /**
  4130. * Increments a node by 1 and returns the previous value.
  4131. *
  4132. * @tsl
  4133. * @function
  4134. * @param {Node} a - The node to increment.
  4135. * @returns {OperatorNode}
  4136. */
  4137. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4138. const temp = int( a ).toConst();
  4139. a.addAssign( 1 );
  4140. return temp;
  4141. } );
  4142. /**
  4143. * Decrements a node by 1 and returns the previous value.
  4144. *
  4145. * @tsl
  4146. * @function
  4147. * @param {Node} a - The node to decrement.
  4148. * @returns {OperatorNode}
  4149. */
  4150. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4151. const temp = int( a ).toConst();
  4152. a.subAssign( 1 );
  4153. return temp;
  4154. } );
  4155. addMethodChaining( 'add', add );
  4156. addMethodChaining( 'sub', sub );
  4157. addMethodChaining( 'mul', mul );
  4158. addMethodChaining( 'div', div );
  4159. addMethodChaining( 'mod', mod );
  4160. addMethodChaining( 'equal', equal );
  4161. addMethodChaining( 'notEqual', notEqual );
  4162. addMethodChaining( 'lessThan', lessThan );
  4163. addMethodChaining( 'greaterThan', greaterThan );
  4164. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4165. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4166. addMethodChaining( 'and', and );
  4167. addMethodChaining( 'or', or );
  4168. addMethodChaining( 'not', not );
  4169. addMethodChaining( 'xor', xor );
  4170. addMethodChaining( 'bitAnd', bitAnd );
  4171. addMethodChaining( 'bitNot', bitNot );
  4172. addMethodChaining( 'bitOr', bitOr );
  4173. addMethodChaining( 'bitXor', bitXor );
  4174. addMethodChaining( 'shiftLeft', shiftLeft );
  4175. addMethodChaining( 'shiftRight', shiftRight );
  4176. addMethodChaining( 'incrementBefore', incrementBefore );
  4177. addMethodChaining( 'decrementBefore', decrementBefore );
  4178. addMethodChaining( 'increment', increment );
  4179. addMethodChaining( 'decrement', decrement );
  4180. /**
  4181. * @tsl
  4182. * @function
  4183. * @deprecated since r175. Use {@link mod} instead.
  4184. *
  4185. * @param {Node} a - The first input.
  4186. * @param {Node} b - The second input.
  4187. * @returns {OperatorNode}
  4188. */
  4189. const modInt = ( a, b ) => { // @deprecated, r175
  4190. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4191. return mod( int( a ), int( b ) );
  4192. };
  4193. addMethodChaining( 'modInt', modInt );
  4194. /**
  4195. * This node represents a variety of mathematical methods available in shaders.
  4196. * They are divided into three categories:
  4197. *
  4198. * - Methods with one input like `sin`, `cos` or `normalize`.
  4199. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4200. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4201. *
  4202. * @augments TempNode
  4203. */
  4204. class MathNode extends TempNode {
  4205. static get type() {
  4206. return 'MathNode';
  4207. }
  4208. /**
  4209. * Constructs a new math node.
  4210. *
  4211. * @param {string} method - The method name.
  4212. * @param {Node} aNode - The first input.
  4213. * @param {?Node} [bNode=null] - The second input.
  4214. * @param {?Node} [cNode=null] - The third input.
  4215. */
  4216. constructor( method, aNode, bNode = null, cNode = null ) {
  4217. super();
  4218. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4219. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4220. let finalOp = new MathNode( method, aNode, bNode );
  4221. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4222. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4223. }
  4224. aNode = finalOp;
  4225. bNode = arguments[ arguments.length - 1 ];
  4226. cNode = null;
  4227. }
  4228. /**
  4229. * The method name.
  4230. *
  4231. * @type {string}
  4232. */
  4233. this.method = method;
  4234. /**
  4235. * The first input.
  4236. *
  4237. * @type {Node}
  4238. */
  4239. this.aNode = aNode;
  4240. /**
  4241. * The second input.
  4242. *
  4243. * @type {?Node}
  4244. * @default null
  4245. */
  4246. this.bNode = bNode;
  4247. /**
  4248. * The third input.
  4249. *
  4250. * @type {?Node}
  4251. * @default null
  4252. */
  4253. this.cNode = cNode;
  4254. /**
  4255. * This flag can be used for type testing.
  4256. *
  4257. * @type {boolean}
  4258. * @readonly
  4259. * @default true
  4260. */
  4261. this.isMathNode = true;
  4262. }
  4263. /**
  4264. * The input type is inferred from the node types of the input nodes.
  4265. *
  4266. * @param {NodeBuilder} builder - The current node builder.
  4267. * @return {string} The input type.
  4268. */
  4269. getInputType( builder ) {
  4270. const aType = this.aNode.getNodeType( builder );
  4271. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4272. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4273. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4274. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4275. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4276. if ( aLen > bLen && aLen > cLen ) {
  4277. return aType;
  4278. } else if ( bLen > cLen ) {
  4279. return bType;
  4280. } else if ( cLen > aLen ) {
  4281. return cType;
  4282. }
  4283. return aType;
  4284. }
  4285. /**
  4286. * The selected method as well as the input type determine the node type of this node.
  4287. *
  4288. * @param {NodeBuilder} builder - The current node builder.
  4289. * @return {string} The node type.
  4290. */
  4291. getNodeType( builder ) {
  4292. const method = this.method;
  4293. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4294. return 'float';
  4295. } else if ( method === MathNode.CROSS ) {
  4296. return 'vec3';
  4297. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4298. return 'bool';
  4299. } else if ( method === MathNode.EQUALS ) {
  4300. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4301. } else {
  4302. return this.getInputType( builder );
  4303. }
  4304. }
  4305. setup( builder ) {
  4306. const { aNode, bNode, method } = this;
  4307. let outputNode = null;
  4308. if ( method === MathNode.ONE_MINUS ) {
  4309. outputNode = sub( 1.0, aNode );
  4310. } else if ( method === MathNode.RECIPROCAL ) {
  4311. outputNode = div( 1.0, aNode );
  4312. } else if ( method === MathNode.DIFFERENCE ) {
  4313. outputNode = abs( sub( aNode, bNode ) );
  4314. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4315. // dir can be either a direction vector or a normal vector
  4316. // upper-left 3x3 of matrix is assumed to be orthogonal
  4317. let tA = aNode;
  4318. let tB = bNode;
  4319. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4320. tB = vec4( vec3( tB ), 0.0 );
  4321. } else {
  4322. tA = vec4( vec3( tA ), 0.0 );
  4323. }
  4324. const mulNode = mul( tA, tB ).xyz;
  4325. outputNode = normalize( mulNode );
  4326. }
  4327. if ( outputNode !== null ) {
  4328. return outputNode;
  4329. } else {
  4330. return super.setup( builder );
  4331. }
  4332. }
  4333. generate( builder, output ) {
  4334. const properties = builder.getNodeProperties( this );
  4335. if ( properties.outputNode ) {
  4336. return super.generate( builder, output );
  4337. }
  4338. let method = this.method;
  4339. const type = this.getNodeType( builder );
  4340. const inputType = this.getInputType( builder );
  4341. const a = this.aNode;
  4342. const b = this.bNode;
  4343. const c = this.cNode;
  4344. const coordinateSystem = builder.renderer.coordinateSystem;
  4345. if ( method === MathNode.NEGATE ) {
  4346. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4347. } else {
  4348. const params = [];
  4349. if ( method === MathNode.CROSS ) {
  4350. params.push(
  4351. a.build( builder, type ),
  4352. b.build( builder, type )
  4353. );
  4354. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4355. params.push(
  4356. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4357. b.build( builder, inputType )
  4358. );
  4359. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4360. params.push(
  4361. a.build( builder, inputType ),
  4362. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4363. );
  4364. } else if ( method === MathNode.REFRACT ) {
  4365. params.push(
  4366. a.build( builder, inputType ),
  4367. b.build( builder, inputType ),
  4368. c.build( builder, 'float' )
  4369. );
  4370. } else if ( method === MathNode.MIX ) {
  4371. params.push(
  4372. a.build( builder, inputType ),
  4373. b.build( builder, inputType ),
  4374. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4375. );
  4376. } else {
  4377. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4378. method = 'atan2';
  4379. }
  4380. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4381. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4382. method = '/*' + method + '*/';
  4383. }
  4384. params.push( a.build( builder, inputType ) );
  4385. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4386. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4387. }
  4388. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4389. }
  4390. }
  4391. serialize( data ) {
  4392. super.serialize( data );
  4393. data.method = this.method;
  4394. }
  4395. deserialize( data ) {
  4396. super.deserialize( data );
  4397. this.method = data.method;
  4398. }
  4399. }
  4400. // 1 input
  4401. MathNode.ALL = 'all';
  4402. MathNode.ANY = 'any';
  4403. MathNode.RADIANS = 'radians';
  4404. MathNode.DEGREES = 'degrees';
  4405. MathNode.EXP = 'exp';
  4406. MathNode.EXP2 = 'exp2';
  4407. MathNode.LOG = 'log';
  4408. MathNode.LOG2 = 'log2';
  4409. MathNode.SQRT = 'sqrt';
  4410. MathNode.INVERSE_SQRT = 'inversesqrt';
  4411. MathNode.FLOOR = 'floor';
  4412. MathNode.CEIL = 'ceil';
  4413. MathNode.NORMALIZE = 'normalize';
  4414. MathNode.FRACT = 'fract';
  4415. MathNode.SIN = 'sin';
  4416. MathNode.COS = 'cos';
  4417. MathNode.TAN = 'tan';
  4418. MathNode.ASIN = 'asin';
  4419. MathNode.ACOS = 'acos';
  4420. MathNode.ATAN = 'atan';
  4421. MathNode.ABS = 'abs';
  4422. MathNode.SIGN = 'sign';
  4423. MathNode.LENGTH = 'length';
  4424. MathNode.NEGATE = 'negate';
  4425. MathNode.ONE_MINUS = 'oneMinus';
  4426. MathNode.DFDX = 'dFdx';
  4427. MathNode.DFDY = 'dFdy';
  4428. MathNode.ROUND = 'round';
  4429. MathNode.RECIPROCAL = 'reciprocal';
  4430. MathNode.TRUNC = 'trunc';
  4431. MathNode.FWIDTH = 'fwidth';
  4432. MathNode.TRANSPOSE = 'transpose';
  4433. MathNode.DETERMINANT = 'determinant';
  4434. MathNode.INVERSE = 'inverse';
  4435. // 2 inputs
  4436. MathNode.BITCAST = 'bitcast';
  4437. MathNode.EQUALS = 'equals';
  4438. MathNode.MIN = 'min';
  4439. MathNode.MAX = 'max';
  4440. MathNode.STEP = 'step';
  4441. MathNode.REFLECT = 'reflect';
  4442. MathNode.DISTANCE = 'distance';
  4443. MathNode.DIFFERENCE = 'difference';
  4444. MathNode.DOT = 'dot';
  4445. MathNode.CROSS = 'cross';
  4446. MathNode.POW = 'pow';
  4447. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4448. // 3 inputs
  4449. MathNode.MIX = 'mix';
  4450. MathNode.CLAMP = 'clamp';
  4451. MathNode.REFRACT = 'refract';
  4452. MathNode.SMOOTHSTEP = 'smoothstep';
  4453. MathNode.FACEFORWARD = 'faceforward';
  4454. // 1 inputs
  4455. /**
  4456. * A small value used to handle floating-point precision errors.
  4457. *
  4458. * @tsl
  4459. * @type {Node<float>}
  4460. */
  4461. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4462. /**
  4463. * Represents infinity.
  4464. *
  4465. * @tsl
  4466. * @type {Node<float>}
  4467. */
  4468. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4469. /**
  4470. * Represents PI.
  4471. *
  4472. * @tsl
  4473. * @type {Node<float>}
  4474. */
  4475. const PI = /*@__PURE__*/ float( Math.PI );
  4476. /**
  4477. * Represents PI * 2.
  4478. *
  4479. * @tsl
  4480. * @type {Node<float>}
  4481. */
  4482. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4483. /**
  4484. * Returns `true` if all components of `x` are `true`.
  4485. *
  4486. * @tsl
  4487. * @function
  4488. * @param {Node | number} x - The parameter.
  4489. * @returns {Node<bool>}
  4490. */
  4491. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4492. /**
  4493. * Returns `true` if any components of `x` are `true`.
  4494. *
  4495. * @tsl
  4496. * @function
  4497. * @param {Node | number} x - The parameter.
  4498. * @returns {Node<bool>}
  4499. */
  4500. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4501. /**
  4502. * Converts a quantity in degrees to radians.
  4503. *
  4504. * @tsl
  4505. * @function
  4506. * @param {Node | number} x - The input in degrees.
  4507. * @returns {Node}
  4508. */
  4509. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4510. /**
  4511. * Convert a quantity in radians to degrees.
  4512. *
  4513. * @tsl
  4514. * @function
  4515. * @param {Node | number} x - The input in radians.
  4516. * @returns {Node}
  4517. */
  4518. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4519. /**
  4520. * Returns the natural exponentiation of the parameter.
  4521. *
  4522. * @tsl
  4523. * @function
  4524. * @param {Node | number} x - The parameter.
  4525. * @returns {Node}
  4526. */
  4527. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4528. /**
  4529. * Returns 2 raised to the power of the parameter.
  4530. *
  4531. * @tsl
  4532. * @function
  4533. * @param {Node | number} x - The parameter.
  4534. * @returns {Node}
  4535. */
  4536. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4537. /**
  4538. * Returns the natural logarithm of the parameter.
  4539. *
  4540. * @tsl
  4541. * @function
  4542. * @param {Node | number} x - The parameter.
  4543. * @returns {Node}
  4544. */
  4545. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4546. /**
  4547. * Returns the base 2 logarithm of the parameter.
  4548. *
  4549. * @tsl
  4550. * @function
  4551. * @param {Node | number} x - The parameter.
  4552. * @returns {Node}
  4553. */
  4554. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4555. /**
  4556. * Returns the square root of the parameter.
  4557. *
  4558. * @tsl
  4559. * @function
  4560. * @param {Node | number} x - The parameter.
  4561. * @returns {Node}
  4562. */
  4563. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4564. /**
  4565. * Returns the inverse of the square root of the parameter.
  4566. *
  4567. * @tsl
  4568. * @function
  4569. * @param {Node | number} x - The parameter.
  4570. * @returns {Node}
  4571. */
  4572. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4573. /**
  4574. * Finds the nearest integer less than or equal to the parameter.
  4575. *
  4576. * @tsl
  4577. * @function
  4578. * @param {Node | number} x - The parameter.
  4579. * @returns {Node}
  4580. */
  4581. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4582. /**
  4583. * Finds the nearest integer that is greater than or equal to the parameter.
  4584. *
  4585. * @tsl
  4586. * @function
  4587. * @param {Node | number} x - The parameter.
  4588. * @returns {Node}
  4589. */
  4590. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4591. /**
  4592. * Calculates the unit vector in the same direction as the original vector.
  4593. *
  4594. * @tsl
  4595. * @function
  4596. * @param {Node} x - The input vector.
  4597. * @returns {Node}
  4598. */
  4599. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4600. /**
  4601. * Computes the fractional part of the parameter.
  4602. *
  4603. * @tsl
  4604. * @function
  4605. * @param {Node | number} x - The parameter.
  4606. * @returns {Node}
  4607. */
  4608. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4609. /**
  4610. * Returns the sine of the parameter.
  4611. *
  4612. * @tsl
  4613. * @function
  4614. * @param {Node | number} x - The parameter.
  4615. * @returns {Node}
  4616. */
  4617. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4618. /**
  4619. * Returns the cosine of the parameter.
  4620. *
  4621. * @tsl
  4622. * @function
  4623. * @param {Node | number} x - The parameter.
  4624. * @returns {Node}
  4625. */
  4626. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4627. /**
  4628. * Returns the tangent of the parameter.
  4629. *
  4630. * @tsl
  4631. * @function
  4632. * @param {Node | number} x - The parameter.
  4633. * @returns {Node}
  4634. */
  4635. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4636. /**
  4637. * Returns the arcsine of the parameter.
  4638. *
  4639. * @tsl
  4640. * @function
  4641. * @param {Node | number} x - The parameter.
  4642. * @returns {Node}
  4643. */
  4644. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4645. /**
  4646. * Returns the arccosine of the parameter.
  4647. *
  4648. * @tsl
  4649. * @function
  4650. * @param {Node | number} x - The parameter.
  4651. * @returns {Node}
  4652. */
  4653. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4654. /**
  4655. * Returns the arc-tangent of the parameter.
  4656. * If two parameters are provided, the result is `atan2(y/x)`.
  4657. *
  4658. * @tsl
  4659. * @function
  4660. * @param {Node | number} y - The y parameter.
  4661. * @param {?(Node | number)} x - The x parameter.
  4662. * @returns {Node}
  4663. */
  4664. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4665. /**
  4666. * Returns the absolute value of the parameter.
  4667. *
  4668. * @tsl
  4669. * @function
  4670. * @param {Node | number} x - The parameter.
  4671. * @returns {Node}
  4672. */
  4673. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4674. /**
  4675. * Extracts the sign of the parameter.
  4676. *
  4677. * @tsl
  4678. * @function
  4679. * @param {Node | number} x - The parameter.
  4680. * @returns {Node}
  4681. */
  4682. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4683. /**
  4684. * Calculates the length of a vector.
  4685. *
  4686. * @tsl
  4687. * @function
  4688. * @param {Node} x - The parameter.
  4689. * @returns {Node<float>}
  4690. */
  4691. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4692. /**
  4693. * Negates the value of the parameter (-x).
  4694. *
  4695. * @tsl
  4696. * @function
  4697. * @param {Node | number} x - The parameter.
  4698. * @returns {Node}
  4699. */
  4700. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4701. /**
  4702. * Return `1` minus the parameter.
  4703. *
  4704. * @tsl
  4705. * @function
  4706. * @param {Node | number} x - The parameter.
  4707. * @returns {Node}
  4708. */
  4709. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4710. /**
  4711. * Returns the partial derivative of the parameter with respect to x.
  4712. *
  4713. * @tsl
  4714. * @function
  4715. * @param {Node | number} x - The parameter.
  4716. * @returns {Node}
  4717. */
  4718. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4719. /**
  4720. * Returns the partial derivative of the parameter with respect to y.
  4721. *
  4722. * @tsl
  4723. * @function
  4724. * @param {Node | number} x - The parameter.
  4725. * @returns {Node}
  4726. */
  4727. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4728. /**
  4729. * Rounds the parameter to the nearest integer.
  4730. *
  4731. * @tsl
  4732. * @function
  4733. * @param {Node | number} x - The parameter.
  4734. * @returns {Node}
  4735. */
  4736. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4737. /**
  4738. * Returns the reciprocal of the parameter `(1/x)`.
  4739. *
  4740. * @tsl
  4741. * @function
  4742. * @param {Node | number} x - The parameter.
  4743. * @returns {Node}
  4744. */
  4745. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4746. /**
  4747. * Truncates the parameter, removing the fractional part.
  4748. *
  4749. * @tsl
  4750. * @function
  4751. * @param {Node | number} x - The parameter.
  4752. * @returns {Node}
  4753. */
  4754. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4755. /**
  4756. * Returns the sum of the absolute derivatives in x and y.
  4757. *
  4758. * @tsl
  4759. * @function
  4760. * @param {Node | number} x - The parameter.
  4761. * @returns {Node}
  4762. */
  4763. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4764. /**
  4765. * Returns the transpose of a matrix.
  4766. *
  4767. * @tsl
  4768. * @function
  4769. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4770. * @returns {Node}
  4771. */
  4772. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4773. /**
  4774. * Returns the determinant of a matrix.
  4775. *
  4776. * @tsl
  4777. * @function
  4778. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4779. * @returns {Node<float>}
  4780. */
  4781. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4782. /**
  4783. * Returns the inverse of a matrix.
  4784. *
  4785. * @tsl
  4786. * @function
  4787. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4788. * @returns {Node<mat2|mat3|mat4>}
  4789. */
  4790. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4791. // 2 inputs
  4792. /**
  4793. * Reinterpret the bit representation of a value in one type as a value in another type.
  4794. *
  4795. * @tsl
  4796. * @function
  4797. * @param {Node | number} x - The parameter.
  4798. * @param {string} y - The new type.
  4799. * @returns {Node}
  4800. */
  4801. const bitcast = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4802. /**
  4803. * Returns `true` if `x` equals `y`.
  4804. *
  4805. * @tsl
  4806. * @function
  4807. * @param {Node | number} x - The first parameter.
  4808. * @param {Node | number} y - The second parameter.
  4809. * @deprecated since r175. Use {@link equal} instead.
  4810. * @returns {Node<bool>}
  4811. */
  4812. const equals = ( x, y ) => { // @deprecated, r172
  4813. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4814. return equal( x, y );
  4815. };
  4816. /**
  4817. * Returns the least of the given values.
  4818. *
  4819. * @tsl
  4820. * @function
  4821. * @param {...(Node | number)} values - The values to compare.
  4822. * @returns {Node}
  4823. */
  4824. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4825. /**
  4826. * Returns the greatest of the given values.
  4827. *
  4828. * @tsl
  4829. * @function
  4830. * @param {...(Node | number)} values - The values to compare.
  4831. * @returns {Node}
  4832. */
  4833. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4834. /**
  4835. * Generate a step function by comparing two values.
  4836. *
  4837. * @tsl
  4838. * @function
  4839. * @param {Node | number} x - The y parameter.
  4840. * @param {Node | number} y - The x parameter.
  4841. * @returns {Node}
  4842. */
  4843. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4844. /**
  4845. * Calculates the reflection direction for an incident vector.
  4846. *
  4847. * @tsl
  4848. * @function
  4849. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4850. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4851. * @returns {Node<vec2|vec3|vec4>}
  4852. */
  4853. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4854. /**
  4855. * Calculates the distance between two points.
  4856. *
  4857. * @tsl
  4858. * @function
  4859. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4860. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4861. * @returns {Node<float>}
  4862. */
  4863. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4864. /**
  4865. * Calculates the absolute difference between two values.
  4866. *
  4867. * @tsl
  4868. * @function
  4869. * @param {Node | number} x - The first parameter.
  4870. * @param {Node | number} y - The second parameter.
  4871. * @returns {Node}
  4872. */
  4873. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4874. /**
  4875. * Calculates the dot product of two vectors.
  4876. *
  4877. * @tsl
  4878. * @function
  4879. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4880. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4881. * @returns {Node<float>}
  4882. */
  4883. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4884. /**
  4885. * Calculates the cross product of two vectors.
  4886. *
  4887. * @tsl
  4888. * @function
  4889. * @param {Node<vec2|vec3>} x - The first vector.
  4890. * @param {Node<vec2|vec3>} y - The second vector.
  4891. * @returns {Node<float|vec3>}
  4892. */
  4893. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4894. /**
  4895. * Return the value of the first parameter raised to the power of the second one.
  4896. *
  4897. * @tsl
  4898. * @function
  4899. * @param {Node | number} x - The first parameter.
  4900. * @param {Node | number} y - The second parameter.
  4901. * @returns {Node}
  4902. */
  4903. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  4904. /**
  4905. * Returns the square of the parameter.
  4906. *
  4907. * @tsl
  4908. * @function
  4909. * @param {Node | number} x - The first parameter.
  4910. * @returns {Node}
  4911. */
  4912. const pow2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4913. /**
  4914. * Returns the cube of the parameter.
  4915. *
  4916. * @tsl
  4917. * @function
  4918. * @param {Node | number} x - The first parameter.
  4919. * @returns {Node}
  4920. */
  4921. const pow3 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4922. /**
  4923. * Returns the fourth power of the parameter.
  4924. *
  4925. * @tsl
  4926. * @function
  4927. * @param {Node | number} x - The first parameter.
  4928. * @returns {Node}
  4929. */
  4930. const pow4 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4931. /**
  4932. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4933. *
  4934. * @tsl
  4935. * @function
  4936. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4937. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4938. * @returns {Node}
  4939. */
  4940. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4941. /**
  4942. * Returns the cube root of a number.
  4943. *
  4944. * @tsl
  4945. * @function
  4946. * @param {Node | number} a - The first parameter.
  4947. * @returns {Node}
  4948. */
  4949. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4950. /**
  4951. * Calculate the squared length of a vector.
  4952. *
  4953. * @tsl
  4954. * @function
  4955. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4956. * @returns {Node<float>}
  4957. */
  4958. const lengthSq = ( a ) => dot( a, a );
  4959. /**
  4960. * Linearly interpolates between two values.
  4961. *
  4962. * @tsl
  4963. * @function
  4964. * @param {Node | number} a - The first parameter.
  4965. * @param {Node | number} b - The second parameter.
  4966. * @param {Node | number} t - The interpolation value.
  4967. * @returns {Node}
  4968. */
  4969. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4970. /**
  4971. * Constrains a value to lie between two further values.
  4972. *
  4973. * @tsl
  4974. * @function
  4975. * @param {Node | number} value - The value to constrain.
  4976. * @param {Node | number} [low=0] - The lower bound.
  4977. * @param {Node | number} [high=1] - The upper bound.
  4978. * @returns {Node}
  4979. */
  4980. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4981. /**
  4982. * Constrains a value between `0` and `1`.
  4983. *
  4984. * @tsl
  4985. * @function
  4986. * @param {Node | number} value - The value to constrain.
  4987. * @returns {Node}
  4988. */
  4989. const saturate = ( value ) => clamp( value );
  4990. /**
  4991. * Calculates the refraction direction for an incident vector.
  4992. *
  4993. * @tsl
  4994. * @function
  4995. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4996. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4997. * @param {Node<float>} eta - The ratio of indices of refraction.
  4998. * @returns {Node<vec2|vec3|vec4>}
  4999. */
  5000. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5001. /**
  5002. * Performs a Hermite interpolation between two values.
  5003. *
  5004. * @tsl
  5005. * @function
  5006. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5007. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5008. * @param {Node | number} x - The source value for interpolation.
  5009. * @returns {Node}
  5010. */
  5011. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5012. /**
  5013. * Returns a vector pointing in the same direction as another.
  5014. *
  5015. * @tsl
  5016. * @function
  5017. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5018. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5019. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5020. * @returns {Node<vec2|vec3|vec4>}
  5021. */
  5022. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5023. /**
  5024. * Returns a random value for the given uv.
  5025. *
  5026. * @tsl
  5027. * @function
  5028. * @param {Node<vec2>} uv - The uv node.
  5029. * @returns {Node<float>}
  5030. */
  5031. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5032. const a = 12.9898, b = 78.233, c = 43758.5453;
  5033. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5034. return fract( sin( sn ).mul( c ) );
  5035. } );
  5036. /**
  5037. * Alias for `mix()` with a different parameter order.
  5038. *
  5039. * @tsl
  5040. * @function
  5041. * @param {Node | number} t - The interpolation value.
  5042. * @param {Node | number} e1 - The first parameter.
  5043. * @param {Node | number} e2 - The second parameter.
  5044. * @returns {Node}
  5045. */
  5046. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5047. /**
  5048. * Alias for `smoothstep()` with a different parameter order.
  5049. *
  5050. * @tsl
  5051. * @function
  5052. * @param {Node | number} x - The source value for interpolation.
  5053. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5054. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5055. * @returns {Node}
  5056. */
  5057. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5058. /**
  5059. * Alias for `step()` with a different parameter order.
  5060. *
  5061. * @tsl
  5062. * @function
  5063. * @param {Node | number} x - The source value for interpolation.
  5064. * @param {Node | number} edge - The edge value.
  5065. * @returns {Node}
  5066. */
  5067. const stepElement = ( x, edge ) => step( edge, x );
  5068. /**
  5069. * Returns the arc-tangent of the quotient of its parameters.
  5070. *
  5071. * @tsl
  5072. * @function
  5073. * @deprecated since r172. Use {@link atan} instead.
  5074. *
  5075. * @param {Node | number} y - The y parameter.
  5076. * @param {Node | number} x - The x parameter.
  5077. * @returns {Node}
  5078. */
  5079. const atan2 = ( y, x ) => { // @deprecated, r172
  5080. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  5081. return atan( y, x );
  5082. };
  5083. // GLSL alias function
  5084. const faceforward = faceForward;
  5085. const inversesqrt = inverseSqrt;
  5086. // Method chaining
  5087. addMethodChaining( 'all', all );
  5088. addMethodChaining( 'any', any );
  5089. addMethodChaining( 'equals', equals );
  5090. addMethodChaining( 'radians', radians );
  5091. addMethodChaining( 'degrees', degrees );
  5092. addMethodChaining( 'exp', exp );
  5093. addMethodChaining( 'exp2', exp2 );
  5094. addMethodChaining( 'log', log );
  5095. addMethodChaining( 'log2', log2 );
  5096. addMethodChaining( 'sqrt', sqrt );
  5097. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5098. addMethodChaining( 'floor', floor );
  5099. addMethodChaining( 'ceil', ceil );
  5100. addMethodChaining( 'normalize', normalize );
  5101. addMethodChaining( 'fract', fract );
  5102. addMethodChaining( 'sin', sin );
  5103. addMethodChaining( 'cos', cos );
  5104. addMethodChaining( 'tan', tan );
  5105. addMethodChaining( 'asin', asin );
  5106. addMethodChaining( 'acos', acos );
  5107. addMethodChaining( 'atan', atan );
  5108. addMethodChaining( 'abs', abs );
  5109. addMethodChaining( 'sign', sign );
  5110. addMethodChaining( 'length', length );
  5111. addMethodChaining( 'lengthSq', lengthSq );
  5112. addMethodChaining( 'negate', negate );
  5113. addMethodChaining( 'oneMinus', oneMinus );
  5114. addMethodChaining( 'dFdx', dFdx );
  5115. addMethodChaining( 'dFdy', dFdy );
  5116. addMethodChaining( 'round', round );
  5117. addMethodChaining( 'reciprocal', reciprocal );
  5118. addMethodChaining( 'trunc', trunc );
  5119. addMethodChaining( 'fwidth', fwidth );
  5120. addMethodChaining( 'atan2', atan2 );
  5121. addMethodChaining( 'min', min$1 );
  5122. addMethodChaining( 'max', max$1 );
  5123. addMethodChaining( 'step', stepElement );
  5124. addMethodChaining( 'reflect', reflect );
  5125. addMethodChaining( 'distance', distance );
  5126. addMethodChaining( 'dot', dot );
  5127. addMethodChaining( 'cross', cross );
  5128. addMethodChaining( 'pow', pow );
  5129. addMethodChaining( 'pow2', pow2 );
  5130. addMethodChaining( 'pow3', pow3 );
  5131. addMethodChaining( 'pow4', pow4 );
  5132. addMethodChaining( 'transformDirection', transformDirection );
  5133. addMethodChaining( 'mix', mixElement );
  5134. addMethodChaining( 'clamp', clamp );
  5135. addMethodChaining( 'refract', refract );
  5136. addMethodChaining( 'smoothstep', smoothstepElement );
  5137. addMethodChaining( 'faceForward', faceForward );
  5138. addMethodChaining( 'difference', difference );
  5139. addMethodChaining( 'saturate', saturate );
  5140. addMethodChaining( 'cbrt', cbrt );
  5141. addMethodChaining( 'transpose', transpose );
  5142. addMethodChaining( 'determinant', determinant );
  5143. addMethodChaining( 'inverse', inverse );
  5144. addMethodChaining( 'rand', rand );
  5145. /**
  5146. * Represents a logical `if/else` statement. Can be used as an alternative
  5147. * to the `If()`/`Else()` syntax.
  5148. *
  5149. * The corresponding TSL `select()` looks like so:
  5150. * ```js
  5151. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5152. * ```
  5153. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5154. * determine the outcome of the entire statement.
  5155. *
  5156. * @augments Node
  5157. */
  5158. class ConditionalNode extends Node {
  5159. static get type() {
  5160. return 'ConditionalNode';
  5161. }
  5162. /**
  5163. * Constructs a new conditional node.
  5164. *
  5165. * @param {Node} condNode - The node that defines the condition.
  5166. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5167. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5168. */
  5169. constructor( condNode, ifNode, elseNode = null ) {
  5170. super();
  5171. /**
  5172. * The node that defines the condition.
  5173. *
  5174. * @type {Node}
  5175. */
  5176. this.condNode = condNode;
  5177. /**
  5178. * The node that is evaluate when the condition ends up `true`.
  5179. *
  5180. * @type {Node}
  5181. */
  5182. this.ifNode = ifNode;
  5183. /**
  5184. * The node that is evaluate when the condition ends up `false`.
  5185. *
  5186. * @type {?Node}
  5187. * @default null
  5188. */
  5189. this.elseNode = elseNode;
  5190. }
  5191. /**
  5192. * This method is overwritten since the node type is inferred from the if/else
  5193. * nodes.
  5194. *
  5195. * @param {NodeBuilder} builder - The current node builder.
  5196. * @return {string} The node type.
  5197. */
  5198. getNodeType( builder ) {
  5199. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5200. if ( ifNode === undefined ) {
  5201. // fallback setup
  5202. builder.flowBuildStage( this, 'setup' );
  5203. return this.getNodeType( builder );
  5204. }
  5205. const ifType = ifNode.getNodeType( builder );
  5206. if ( elseNode !== null ) {
  5207. const elseType = elseNode.getNodeType( builder );
  5208. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5209. return elseType;
  5210. }
  5211. }
  5212. return ifType;
  5213. }
  5214. setup( builder ) {
  5215. const condNode = this.condNode.cache();
  5216. const ifNode = this.ifNode.cache();
  5217. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  5218. //
  5219. const currentNodeBlock = builder.context.nodeBlock;
  5220. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5221. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5222. //
  5223. const isUniformFlow = builder.context.uniformFlow;
  5224. const properties = builder.getNodeProperties( this );
  5225. properties.condNode = condNode;
  5226. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5227. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5228. }
  5229. generate( builder, output ) {
  5230. const type = this.getNodeType( builder );
  5231. const nodeData = builder.getDataFromNode( this );
  5232. if ( nodeData.nodeProperty !== undefined ) {
  5233. return nodeData.nodeProperty;
  5234. }
  5235. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5236. const functionNode = builder.currentFunctionNode;
  5237. const needsOutput = output !== 'void';
  5238. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5239. nodeData.nodeProperty = nodeProperty;
  5240. const nodeSnippet = condNode.build( builder, 'bool' );
  5241. const isUniformFlow = builder.context.uniformFlow;
  5242. if ( isUniformFlow && elseNode !== null ) {
  5243. const ifSnippet = ifNode.build( builder, type );
  5244. const elseSnippet = elseNode.build( builder, type );
  5245. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5246. // TODO: If node property already exists return something else
  5247. return builder.format( mathSnippet, type, output );
  5248. }
  5249. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5250. let ifSnippet = ifNode.build( builder, type );
  5251. if ( ifSnippet ) {
  5252. if ( needsOutput ) {
  5253. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5254. } else {
  5255. ifSnippet = 'return ' + ifSnippet + ';';
  5256. if ( functionNode === null ) {
  5257. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5258. ifSnippet = '// ' + ifSnippet;
  5259. }
  5260. }
  5261. }
  5262. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5263. if ( elseNode !== null ) {
  5264. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5265. let elseSnippet = elseNode.build( builder, type );
  5266. if ( elseSnippet ) {
  5267. if ( needsOutput ) {
  5268. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5269. } else {
  5270. elseSnippet = 'return ' + elseSnippet + ';';
  5271. if ( functionNode === null ) {
  5272. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5273. elseSnippet = '// ' + elseSnippet;
  5274. }
  5275. }
  5276. }
  5277. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5278. } else {
  5279. builder.addFlowCode( '\n\n' );
  5280. }
  5281. return builder.format( nodeProperty, type, output );
  5282. }
  5283. }
  5284. /**
  5285. * TSL function for creating a conditional node.
  5286. *
  5287. * @tsl
  5288. * @function
  5289. * @param {Node} condNode - The node that defines the condition.
  5290. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5291. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5292. * @returns {ConditionalNode}
  5293. */
  5294. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5295. addMethodChaining( 'select', select );
  5296. /**
  5297. * This node can be used as a context management component for another node.
  5298. * {@link NodeBuilder} performs its node building process in a specific context and
  5299. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5300. *
  5301. * ```js
  5302. *node.context( { getUV: () => customCoord } );
  5303. *```
  5304. * @augments Node
  5305. */
  5306. class ContextNode extends Node {
  5307. static get type() {
  5308. return 'ContextNode';
  5309. }
  5310. /**
  5311. * Constructs a new context node.
  5312. *
  5313. * @param {Node} node - The node whose context should be modified.
  5314. * @param {Object} [value={}] - The modified context data.
  5315. */
  5316. constructor( node, value = {} ) {
  5317. super();
  5318. /**
  5319. * This flag can be used for type testing.
  5320. *
  5321. * @type {boolean}
  5322. * @readonly
  5323. * @default true
  5324. */
  5325. this.isContextNode = true;
  5326. /**
  5327. * The node whose context should be modified.
  5328. *
  5329. * @type {Node}
  5330. */
  5331. this.node = node;
  5332. /**
  5333. * The modified context data.
  5334. *
  5335. * @type {Object}
  5336. * @default {}
  5337. */
  5338. this.value = value;
  5339. }
  5340. /**
  5341. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5342. *
  5343. * @return {Node} A reference to {@link ContextNode#node}.
  5344. */
  5345. getScope() {
  5346. return this.node.getScope();
  5347. }
  5348. /**
  5349. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5350. *
  5351. * @param {NodeBuilder} builder - The current node builder.
  5352. * @return {string} The node type.
  5353. */
  5354. getNodeType( builder ) {
  5355. return this.node.getNodeType( builder );
  5356. }
  5357. /**
  5358. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5359. *
  5360. * @param {NodeBuilder} builder - The current node builder.
  5361. * @param {string} name - The member name.
  5362. * @returns {string} The member type.
  5363. */
  5364. getMemberType( builder, name ) {
  5365. return this.node.getMemberType( builder, name );
  5366. }
  5367. analyze( builder ) {
  5368. const previousContext = builder.getContext();
  5369. builder.setContext( { ...builder.context, ...this.value } );
  5370. this.node.build( builder );
  5371. builder.setContext( previousContext );
  5372. }
  5373. setup( builder ) {
  5374. const previousContext = builder.getContext();
  5375. builder.setContext( { ...builder.context, ...this.value } );
  5376. this.node.build( builder );
  5377. builder.setContext( previousContext );
  5378. }
  5379. generate( builder, output ) {
  5380. const previousContext = builder.getContext();
  5381. builder.setContext( { ...builder.context, ...this.value } );
  5382. const snippet = this.node.build( builder, output );
  5383. builder.setContext( previousContext );
  5384. return snippet;
  5385. }
  5386. }
  5387. /**
  5388. * TSL function for creating a context node.
  5389. *
  5390. * @tsl
  5391. * @function
  5392. * @param {Node} node - The node whose context should be modified.
  5393. * @param {Object} [value={}] - The modified context data.
  5394. * @returns {ContextNode}
  5395. */
  5396. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5397. /**
  5398. * TSL function for defining a uniformFlow context value for a given node.
  5399. *
  5400. * @tsl
  5401. * @function
  5402. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5403. * @returns {ContextNode}
  5404. */
  5405. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5406. /**
  5407. * TSL function for defining a name for the context value for a given node.
  5408. *
  5409. * @tsl
  5410. * @function
  5411. * @param {Node} node - The node whose context should be modified.
  5412. * @param {string} name - The name to set.
  5413. * @returns {ContextNode}
  5414. */
  5415. const setName = ( node, name ) => context( node, { nodeName: name } );
  5416. /**
  5417. * TSL function for defining a label context value for a given node.
  5418. *
  5419. * @tsl
  5420. * @function
  5421. * @deprecated
  5422. * @param {Node} node - The node whose context should be modified.
  5423. * @param {string} name - The name/label to set.
  5424. * @returns {ContextNode}
  5425. */
  5426. function label( node, name ) {
  5427. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5428. return setName( node, name );
  5429. }
  5430. addMethodChaining( 'context', context );
  5431. addMethodChaining( 'label', label );
  5432. addMethodChaining( 'uniformFlow', uniformFlow );
  5433. addMethodChaining( 'setName', setName );
  5434. /**
  5435. * Class for representing shader variables as nodes. Variables are created from
  5436. * existing nodes like the following:
  5437. *
  5438. * ```js
  5439. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5440. * ```
  5441. *
  5442. * @augments Node
  5443. */
  5444. class VarNode extends Node {
  5445. static get type() {
  5446. return 'VarNode';
  5447. }
  5448. /**
  5449. * Constructs a new variable node.
  5450. *
  5451. * @param {Node} node - The node for which a variable should be created.
  5452. * @param {?string} [name=null] - The name of the variable in the shader.
  5453. * @param {boolean} [readOnly=false] - The read-only flag.
  5454. */
  5455. constructor( node, name = null, readOnly = false ) {
  5456. super();
  5457. /**
  5458. * The node for which a variable should be created.
  5459. *
  5460. * @type {Node}
  5461. */
  5462. this.node = node;
  5463. /**
  5464. * The name of the variable in the shader. If no name is defined,
  5465. * the node system auto-generates one.
  5466. *
  5467. * @type {?string}
  5468. * @default null
  5469. */
  5470. this.name = name;
  5471. /**
  5472. * `VarNode` sets this property to `true` by default.
  5473. *
  5474. * @type {boolean}
  5475. * @default true
  5476. */
  5477. this.global = true;
  5478. /**
  5479. * This flag can be used for type testing.
  5480. *
  5481. * @type {boolean}
  5482. * @readonly
  5483. * @default true
  5484. */
  5485. this.isVarNode = true;
  5486. /**
  5487. *
  5488. * The read-only flag.
  5489. *
  5490. * @type {boolean}
  5491. * @default false
  5492. */
  5493. this.readOnly = readOnly;
  5494. /**
  5495. *
  5496. * Add this flag to the node system to indicate that this node require parents.
  5497. *
  5498. * @type {boolean}
  5499. * @default true
  5500. */
  5501. this.parents = true;
  5502. /**
  5503. * This flag is used to indicate that this node is used for intent.
  5504. *
  5505. * @type {boolean}
  5506. * @default false
  5507. */
  5508. this.intent = false;
  5509. }
  5510. /**
  5511. * Sets the intent flag for this node.
  5512. *
  5513. * This flag is used to indicate that this node is used for intent
  5514. * and should not be built directly. Instead, it is used to indicate that
  5515. * the node should be treated as a variable intent.
  5516. *
  5517. * It's useful for assigning variables without needing creating a new variable node.
  5518. *
  5519. * @param {boolean} value - The value to set for the intent flag.
  5520. * @returns {VarNode} This node.
  5521. */
  5522. setIntent( value ) {
  5523. this.intent = value;
  5524. return this;
  5525. }
  5526. /**
  5527. * Returns the intent flag of this node.
  5528. *
  5529. * @return {boolean} The intent flag.
  5530. */
  5531. getIntent() {
  5532. return this.intent;
  5533. }
  5534. getMemberType( builder, name ) {
  5535. return this.node.getMemberType( builder, name );
  5536. }
  5537. getElementType( builder ) {
  5538. return this.node.getElementType( builder );
  5539. }
  5540. getNodeType( builder ) {
  5541. return this.node.getNodeType( builder );
  5542. }
  5543. getArrayCount( builder ) {
  5544. return this.node.getArrayCount( builder );
  5545. }
  5546. build( ...params ) {
  5547. if ( this.intent === true ) {
  5548. const builder = params[ 0 ];
  5549. const properties = builder.getNodeProperties( this );
  5550. if ( properties.assign !== true ) {
  5551. return this.node.build( ...params );
  5552. }
  5553. }
  5554. return super.build( ...params );
  5555. }
  5556. generate( builder ) {
  5557. const { node, name, readOnly } = this;
  5558. const { renderer } = builder;
  5559. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5560. let isDeterministic = false;
  5561. let shouldTreatAsReadOnly = false;
  5562. if ( readOnly ) {
  5563. isDeterministic = builder.isDeterministic( node );
  5564. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5565. }
  5566. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5567. const snippet = node.build( builder, vectorType );
  5568. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5569. const propertyName = builder.getPropertyName( nodeVar );
  5570. let declarationPrefix = propertyName;
  5571. if ( shouldTreatAsReadOnly ) {
  5572. if ( isWebGPUBackend ) {
  5573. declarationPrefix = isDeterministic
  5574. ? `const ${ propertyName }`
  5575. : `let ${ propertyName }`;
  5576. } else {
  5577. const count = node.getArrayCount( builder );
  5578. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5579. }
  5580. }
  5581. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5582. return propertyName;
  5583. }
  5584. }
  5585. /**
  5586. * TSL function for creating a var node.
  5587. *
  5588. * @tsl
  5589. * @function
  5590. * @param {Node} node - The node for which a variable should be created.
  5591. * @param {?string} name - The name of the variable in the shader.
  5592. * @returns {VarNode}
  5593. */
  5594. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5595. /**
  5596. * TSL function for creating a var node.
  5597. *
  5598. * @tsl
  5599. * @function
  5600. * @param {Node} node - The node for which a variable should be created.
  5601. * @param {?string} name - The name of the variable in the shader.
  5602. * @returns {VarNode}
  5603. */
  5604. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5605. /**
  5606. * TSL function for creating a const node.
  5607. *
  5608. * @tsl
  5609. * @function
  5610. * @param {Node} node - The node for which a constant should be created.
  5611. * @param {?string} name - The name of the constant in the shader.
  5612. * @returns {VarNode}
  5613. */
  5614. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5615. //
  5616. //
  5617. /**
  5618. * TSL function for creating a var intent node.
  5619. *
  5620. * @tsl
  5621. * @function
  5622. * @param {Node} node - The node for which a variable should be created.
  5623. * @param {?string} name - The name of the variable in the shader.
  5624. * @returns {VarNode}
  5625. */
  5626. const VarIntent = ( node ) => {
  5627. if ( getCurrentStack() === null ) {
  5628. return node;
  5629. }
  5630. return createVar( node ).setIntent( true ).toStack();
  5631. };
  5632. // Method chaining
  5633. addMethodChaining( 'toVar', Var );
  5634. addMethodChaining( 'toConst', Const );
  5635. addMethodChaining( 'toVarIntent', VarIntent );
  5636. /**
  5637. * This node is used to build a sub-build in the node system.
  5638. *
  5639. * @augments Node
  5640. * @param {Node} node - The node to be built in the sub-build.
  5641. * @param {string} name - The name of the sub-build.
  5642. * @param {string|null} [nodeType=null] - The type of the node, if known.
  5643. */
  5644. class SubBuildNode extends Node {
  5645. static get type() {
  5646. return 'SubBuild';
  5647. }
  5648. constructor( node, name, nodeType = null ) {
  5649. super( nodeType );
  5650. /**
  5651. * The node to be built in the sub-build.
  5652. *
  5653. * @type {Node}
  5654. */
  5655. this.node = node;
  5656. /**
  5657. * The name of the sub-build.
  5658. *
  5659. * @type {string}
  5660. */
  5661. this.name = name;
  5662. /**
  5663. * This flag can be used for type testing.
  5664. *
  5665. * @type {boolean}
  5666. * @readonly
  5667. * @default true
  5668. */
  5669. this.isSubBuildNode = true;
  5670. }
  5671. getNodeType( builder ) {
  5672. if ( this.nodeType !== null ) return this.nodeType;
  5673. builder.addSubBuild( this.name );
  5674. const nodeType = this.node.getNodeType( builder );
  5675. builder.removeSubBuild();
  5676. return nodeType;
  5677. }
  5678. build( builder, ...params ) {
  5679. builder.addSubBuild( this.name );
  5680. const data = this.node.build( builder, ...params );
  5681. builder.removeSubBuild();
  5682. return data;
  5683. }
  5684. }
  5685. /**
  5686. * Creates a new sub-build node.
  5687. *
  5688. * @tsl
  5689. * @function
  5690. * @param {Node} node - The node to be built in the sub-build.
  5691. * @param {string} name - The name of the sub-build.
  5692. * @param {string|null} [type=null] - The type of the node, if known.
  5693. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5694. */
  5695. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5696. /**
  5697. * Class for representing shader varyings as nodes. Varyings are create from
  5698. * existing nodes like the following:
  5699. *
  5700. * ```js
  5701. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5702. * ```
  5703. *
  5704. * @augments Node
  5705. */
  5706. class VaryingNode extends Node {
  5707. static get type() {
  5708. return 'VaryingNode';
  5709. }
  5710. /**
  5711. * Constructs a new varying node.
  5712. *
  5713. * @param {Node} node - The node for which a varying should be created.
  5714. * @param {?string} name - The name of the varying in the shader.
  5715. */
  5716. constructor( node, name = null ) {
  5717. super();
  5718. /**
  5719. * The node for which a varying should be created.
  5720. *
  5721. * @type {Node}
  5722. */
  5723. this.node = node;
  5724. /**
  5725. * The name of the varying in the shader. If no name is defined,
  5726. * the node system auto-generates one.
  5727. *
  5728. * @type {?string}
  5729. * @default null
  5730. */
  5731. this.name = name;
  5732. /**
  5733. * This flag can be used for type testing.
  5734. *
  5735. * @type {boolean}
  5736. * @readonly
  5737. * @default true
  5738. */
  5739. this.isVaryingNode = true;
  5740. /**
  5741. * The interpolation type of the varying data.
  5742. *
  5743. * @type {?string}
  5744. * @default null
  5745. */
  5746. this.interpolationType = null;
  5747. /**
  5748. * The interpolation sampling type of varying data.
  5749. *
  5750. * @type {?string}
  5751. * @default null
  5752. */
  5753. this.interpolationSampling = null;
  5754. /**
  5755. * This flag is used for global cache.
  5756. *
  5757. * @type {boolean}
  5758. * @default true
  5759. */
  5760. this.global = true;
  5761. }
  5762. /**
  5763. * Defines the interpolation type of the varying.
  5764. *
  5765. * @param {string} type - The interpolation type.
  5766. * @param {?string} sampling - The interpolation sampling type
  5767. * @return {VaryingNode} A reference to this node.
  5768. */
  5769. setInterpolation( type, sampling = null ) {
  5770. this.interpolationType = type;
  5771. this.interpolationSampling = sampling;
  5772. return this;
  5773. }
  5774. getHash( builder ) {
  5775. return this.name || super.getHash( builder );
  5776. }
  5777. getNodeType( builder ) {
  5778. // VaryingNode is auto type
  5779. return this.node.getNodeType( builder );
  5780. }
  5781. /**
  5782. * This method performs the setup of a varying node with the current node builder.
  5783. *
  5784. * @param {NodeBuilder} builder - The current node builder.
  5785. * @return {NodeVarying} The node varying from the node builder.
  5786. */
  5787. setupVarying( builder ) {
  5788. const properties = builder.getNodeProperties( this );
  5789. let varying = properties.varying;
  5790. if ( varying === undefined ) {
  5791. const name = this.name;
  5792. const type = this.getNodeType( builder );
  5793. const interpolationType = this.interpolationType;
  5794. const interpolationSampling = this.interpolationSampling;
  5795. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5796. properties.node = subBuild( this.node, 'VERTEX' );
  5797. }
  5798. // this property can be used to check if the varying can be optimized for a variable
  5799. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5800. return varying;
  5801. }
  5802. setup( builder ) {
  5803. this.setupVarying( builder );
  5804. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5805. }
  5806. analyze( builder ) {
  5807. this.setupVarying( builder );
  5808. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5809. }
  5810. generate( builder ) {
  5811. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5812. const properties = builder.getNodeProperties( this );
  5813. const varying = this.setupVarying( builder );
  5814. if ( properties[ propertyKey ] === undefined ) {
  5815. const type = this.getNodeType( builder );
  5816. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5817. // force node run in vertex stage
  5818. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5819. properties[ propertyKey ] = propertyName;
  5820. }
  5821. return builder.getPropertyName( varying );
  5822. }
  5823. }
  5824. /**
  5825. * TSL function for creating a varying node.
  5826. *
  5827. * @tsl
  5828. * @function
  5829. * @param {Node} node - The node for which a varying should be created.
  5830. * @param {?string} name - The name of the varying in the shader.
  5831. * @returns {VaryingNode}
  5832. */
  5833. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5834. /**
  5835. * Computes a node in the vertex stage.
  5836. *
  5837. * @tsl
  5838. * @function
  5839. * @param {Node} node - The node which should be executed in the vertex stage.
  5840. * @returns {VaryingNode}
  5841. */
  5842. const vertexStage = ( node ) => varying( node );
  5843. addMethodChaining( 'toVarying', varying );
  5844. addMethodChaining( 'toVertexStage', vertexStage );
  5845. // Deprecated
  5846. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5847. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5848. return varying( ...params );
  5849. } );
  5850. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5851. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5852. return varying( ...params );
  5853. } );
  5854. /**
  5855. * Converts the given color value from sRGB to linear-sRGB color space.
  5856. *
  5857. * @tsl
  5858. * @function
  5859. * @param {Node<vec3>} color - The sRGB color.
  5860. * @return {Node<vec3>} The linear-sRGB color.
  5861. */
  5862. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5863. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5864. const b = color.mul( 0.0773993808 );
  5865. const factor = color.lessThanEqual( 0.04045 );
  5866. const rgbResult = mix( a, b, factor );
  5867. return rgbResult;
  5868. } ).setLayout( {
  5869. name: 'sRGBTransferEOTF',
  5870. type: 'vec3',
  5871. inputs: [
  5872. { name: 'color', type: 'vec3' }
  5873. ]
  5874. } );
  5875. /**
  5876. * Converts the given color value from linear-sRGB to sRGB color space.
  5877. *
  5878. * @tsl
  5879. * @function
  5880. * @param {Node<vec3>} color - The linear-sRGB color.
  5881. * @return {Node<vec3>} The sRGB color.
  5882. */
  5883. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5884. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5885. const b = color.mul( 12.92 );
  5886. const factor = color.lessThanEqual( 0.0031308 );
  5887. const rgbResult = mix( a, b, factor );
  5888. return rgbResult;
  5889. } ).setLayout( {
  5890. name: 'sRGBTransferOETF',
  5891. type: 'vec3',
  5892. inputs: [
  5893. { name: 'color', type: 'vec3' }
  5894. ]
  5895. } );
  5896. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5897. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5898. /**
  5899. * This node represents a color space conversion. Meaning it converts
  5900. * a color value from a source to a target color space.
  5901. *
  5902. * @augments TempNode
  5903. */
  5904. class ColorSpaceNode extends TempNode {
  5905. static get type() {
  5906. return 'ColorSpaceNode';
  5907. }
  5908. /**
  5909. * Constructs a new color space node.
  5910. *
  5911. * @param {Node} colorNode - Represents the color to convert.
  5912. * @param {string} source - The source color space.
  5913. * @param {string} target - The target color space.
  5914. */
  5915. constructor( colorNode, source, target ) {
  5916. super( 'vec4' );
  5917. /**
  5918. * Represents the color to convert.
  5919. *
  5920. * @type {Node}
  5921. */
  5922. this.colorNode = colorNode;
  5923. /**
  5924. * The source color space.
  5925. *
  5926. * @type {string}
  5927. */
  5928. this.source = source;
  5929. /**
  5930. * The target color space.
  5931. *
  5932. * @type {string}
  5933. */
  5934. this.target = target;
  5935. }
  5936. /**
  5937. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5938. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5939. * color management and renderer.
  5940. *
  5941. * @param {NodeBuilder} builder - The current node builder.
  5942. * @param {string} colorSpace - The color space to resolve.
  5943. * @return {string} The resolved color space.
  5944. */
  5945. resolveColorSpace( builder, colorSpace ) {
  5946. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5947. return ColorManagement.workingColorSpace;
  5948. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5949. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5950. }
  5951. return colorSpace;
  5952. }
  5953. setup( builder ) {
  5954. const { colorNode } = this;
  5955. const source = this.resolveColorSpace( builder, this.source );
  5956. const target = this.resolveColorSpace( builder, this.target );
  5957. let outputNode = colorNode;
  5958. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5959. return outputNode;
  5960. }
  5961. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5962. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5963. }
  5964. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5965. outputNode = vec4(
  5966. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5967. outputNode.a
  5968. );
  5969. }
  5970. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5971. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5972. }
  5973. return outputNode;
  5974. }
  5975. }
  5976. /**
  5977. * TSL function for converting a given color node from the current working color space to the given color space.
  5978. *
  5979. * @tsl
  5980. * @function
  5981. * @param {Node} node - Represents the node to convert.
  5982. * @param {string} targetColorSpace - The target color space.
  5983. * @returns {ColorSpaceNode}
  5984. */
  5985. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  5986. /**
  5987. * TSL function for converting a given color node from the given color space to the current working color space.
  5988. *
  5989. * @tsl
  5990. * @function
  5991. * @param {Node} node - Represents the node to convert.
  5992. * @param {string} sourceColorSpace - The source color space.
  5993. * @returns {ColorSpaceNode}
  5994. */
  5995. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  5996. /**
  5997. * TSL function for converting a given color node from one color space to another one.
  5998. *
  5999. * @tsl
  6000. * @function
  6001. * @param {Node} node - Represents the node to convert.
  6002. * @param {string} sourceColorSpace - The source color space.
  6003. * @param {string} targetColorSpace - The target color space.
  6004. * @returns {ColorSpaceNode}
  6005. */
  6006. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6007. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6008. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6009. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6010. /**
  6011. * This class is only relevant if the referenced property is array-like.
  6012. * In this case, `ReferenceElementNode` allows to refer to a specific
  6013. * element inside the data structure via an index.
  6014. *
  6015. * @augments ArrayElementNode
  6016. */
  6017. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6018. static get type() {
  6019. return 'ReferenceElementNode';
  6020. }
  6021. /**
  6022. * Constructs a new reference element node.
  6023. *
  6024. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6025. * @param {Node} indexNode - The index node that defines the element access.
  6026. */
  6027. constructor( referenceNode, indexNode ) {
  6028. super( referenceNode, indexNode );
  6029. /**
  6030. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6031. * property references to the current node.
  6032. *
  6033. * @type {?ReferenceBaseNode}
  6034. * @default null
  6035. */
  6036. this.referenceNode = referenceNode;
  6037. /**
  6038. * This flag can be used for type testing.
  6039. *
  6040. * @type {boolean}
  6041. * @readonly
  6042. * @default true
  6043. */
  6044. this.isReferenceElementNode = true;
  6045. }
  6046. /**
  6047. * This method is overwritten since the node type is inferred from
  6048. * the uniform type of the reference node.
  6049. *
  6050. * @return {string} The node type.
  6051. */
  6052. getNodeType() {
  6053. return this.referenceNode.uniformType;
  6054. }
  6055. generate( builder ) {
  6056. const snippet = super.generate( builder );
  6057. const arrayType = this.referenceNode.getNodeType();
  6058. const elementType = this.getNodeType();
  6059. return builder.format( snippet, arrayType, elementType );
  6060. }
  6061. };
  6062. /**
  6063. * Base class for nodes which establishes a reference to a property of another object.
  6064. * In this way, the value of the node is automatically linked to the value of
  6065. * referenced object. Reference nodes internally represent the linked value
  6066. * as a uniform.
  6067. *
  6068. * @augments Node
  6069. */
  6070. class ReferenceBaseNode extends Node {
  6071. static get type() {
  6072. return 'ReferenceBaseNode';
  6073. }
  6074. /**
  6075. * Constructs a new reference base node.
  6076. *
  6077. * @param {string} property - The name of the property the node refers to.
  6078. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6079. * @param {?Object} [object=null] - The object the property belongs to.
  6080. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6081. */
  6082. constructor( property, uniformType, object = null, count = null ) {
  6083. super();
  6084. /**
  6085. * The name of the property the node refers to.
  6086. *
  6087. * @type {string}
  6088. */
  6089. this.property = property;
  6090. /**
  6091. * The uniform type that should be used to represent the property value.
  6092. *
  6093. * @type {string}
  6094. */
  6095. this.uniformType = uniformType;
  6096. /**
  6097. * The object the property belongs to.
  6098. *
  6099. * @type {?Object}
  6100. * @default null
  6101. */
  6102. this.object = object;
  6103. /**
  6104. * When the linked property is an array, this parameter defines its length.
  6105. *
  6106. * @type {?number}
  6107. * @default null
  6108. */
  6109. this.count = count;
  6110. /**
  6111. * The property name might have dots so nested properties can be referred.
  6112. * The hierarchy of the names is stored inside this array.
  6113. *
  6114. * @type {Array<string>}
  6115. */
  6116. this.properties = property.split( '.' );
  6117. /**
  6118. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6119. * since the final reference might be updated from calling code.
  6120. *
  6121. * @type {?Object}
  6122. * @default null
  6123. */
  6124. this.reference = object;
  6125. /**
  6126. * The uniform node that holds the value of the reference node.
  6127. *
  6128. * @type {UniformNode}
  6129. * @default null
  6130. */
  6131. this.node = null;
  6132. /**
  6133. * The uniform group of the internal uniform.
  6134. *
  6135. * @type {UniformGroupNode}
  6136. * @default null
  6137. */
  6138. this.group = null;
  6139. /**
  6140. * Overwritten since reference nodes are updated per object.
  6141. *
  6142. * @type {string}
  6143. * @default 'object'
  6144. */
  6145. this.updateType = NodeUpdateType.OBJECT;
  6146. }
  6147. /**
  6148. * Sets the uniform group for this reference node.
  6149. *
  6150. * @param {UniformGroupNode} group - The uniform group to set.
  6151. * @return {ReferenceBaseNode} A reference to this node.
  6152. */
  6153. setGroup( group ) {
  6154. this.group = group;
  6155. return this;
  6156. }
  6157. /**
  6158. * When the referred property is array-like, this method can be used
  6159. * to access elements via an index node.
  6160. *
  6161. * @param {IndexNode} indexNode - indexNode.
  6162. * @return {ReferenceElementNode} A reference to an element.
  6163. */
  6164. element( indexNode ) {
  6165. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6166. }
  6167. /**
  6168. * Sets the node type which automatically defines the internal
  6169. * uniform type.
  6170. *
  6171. * @param {string} uniformType - The type to set.
  6172. */
  6173. setNodeType( uniformType ) {
  6174. const node = uniform( null, uniformType ).getSelf();
  6175. if ( this.group !== null ) {
  6176. node.setGroup( this.group );
  6177. }
  6178. this.node = node;
  6179. }
  6180. /**
  6181. * This method is overwritten since the node type is inferred from
  6182. * the type of the reference node.
  6183. *
  6184. * @param {NodeBuilder} builder - The current node builder.
  6185. * @return {string} The node type.
  6186. */
  6187. getNodeType( builder ) {
  6188. if ( this.node === null ) {
  6189. this.updateReference( builder );
  6190. this.updateValue();
  6191. }
  6192. return this.node.getNodeType( builder );
  6193. }
  6194. /**
  6195. * Returns the property value from the given referred object.
  6196. *
  6197. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6198. * @return {any} The value.
  6199. */
  6200. getValueFromReference( object = this.reference ) {
  6201. const { properties } = this;
  6202. let value = object[ properties[ 0 ] ];
  6203. for ( let i = 1; i < properties.length; i ++ ) {
  6204. value = value[ properties[ i ] ];
  6205. }
  6206. return value;
  6207. }
  6208. /**
  6209. * Allows to update the reference based on the given state. The state is only
  6210. * evaluated {@link ReferenceBaseNode#object} is not set.
  6211. *
  6212. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6213. * @return {Object} The updated reference.
  6214. */
  6215. updateReference( state ) {
  6216. this.reference = this.object !== null ? this.object : state.object;
  6217. return this.reference;
  6218. }
  6219. /**
  6220. * The output of the reference node is the internal uniform node.
  6221. *
  6222. * @return {UniformNode} The output node.
  6223. */
  6224. setup() {
  6225. this.updateValue();
  6226. return this.node;
  6227. }
  6228. /**
  6229. * Overwritten to update the internal uniform value.
  6230. *
  6231. * @param {NodeFrame} frame - A reference to the current node frame.
  6232. */
  6233. update( /*frame*/ ) {
  6234. this.updateValue();
  6235. }
  6236. /**
  6237. * Retrieves the value from the referred object property and uses it
  6238. * to updated the internal uniform.
  6239. */
  6240. updateValue() {
  6241. if ( this.node === null ) this.setNodeType( this.uniformType );
  6242. const value = this.getValueFromReference();
  6243. if ( Array.isArray( value ) ) {
  6244. this.node.array = value;
  6245. } else {
  6246. this.node.value = value;
  6247. }
  6248. }
  6249. }
  6250. /**
  6251. * TSL function for creating a reference base node.
  6252. *
  6253. * @tsl
  6254. * @function
  6255. * @param {string} name - The name of the property the node refers to.
  6256. * @param {string} type - The uniform type that should be used to represent the property value.
  6257. * @param {Object} object - The object the property belongs to.
  6258. * @returns {ReferenceBaseNode}
  6259. */
  6260. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6261. /**
  6262. * This node is a special type of reference node which is intended
  6263. * for linking renderer properties with node values.
  6264. * ```js
  6265. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6266. * ```
  6267. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6268. * automatically be updated.
  6269. *
  6270. * @augments ReferenceBaseNode
  6271. */
  6272. class RendererReferenceNode extends ReferenceBaseNode {
  6273. static get type() {
  6274. return 'RendererReferenceNode';
  6275. }
  6276. /**
  6277. * Constructs a new renderer reference node.
  6278. *
  6279. * @param {string} property - The name of the property the node refers to.
  6280. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6281. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6282. * the node refers to the renderer of the current state.
  6283. */
  6284. constructor( property, inputType, renderer = null ) {
  6285. super( property, inputType, renderer );
  6286. /**
  6287. * The renderer the property belongs to. When no renderer is set,
  6288. * the node refers to the renderer of the current state.
  6289. *
  6290. * @type {?Renderer}
  6291. * @default null
  6292. */
  6293. this.renderer = renderer;
  6294. this.setGroup( renderGroup );
  6295. }
  6296. /**
  6297. * Updates the reference based on the given state. The state is only evaluated
  6298. * {@link RendererReferenceNode#renderer} is not set.
  6299. *
  6300. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6301. * @return {Object} The updated reference.
  6302. */
  6303. updateReference( state ) {
  6304. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6305. return this.reference;
  6306. }
  6307. }
  6308. /**
  6309. * TSL function for creating a renderer reference node.
  6310. *
  6311. * @tsl
  6312. * @function
  6313. * @param {string} name - The name of the property the node refers to.
  6314. * @param {string} type - The uniform type that should be used to represent the property value.
  6315. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6316. * the node refers to the renderer of the current state.
  6317. * @returns {RendererReferenceNode}
  6318. */
  6319. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6320. /**
  6321. * This node represents a tone mapping operation.
  6322. *
  6323. * @augments TempNode
  6324. */
  6325. class ToneMappingNode extends TempNode {
  6326. static get type() {
  6327. return 'ToneMappingNode';
  6328. }
  6329. /**
  6330. * Constructs a new tone mapping node.
  6331. *
  6332. * @param {number} toneMapping - The tone mapping type.
  6333. * @param {Node} exposureNode - The tone mapping exposure.
  6334. * @param {Node} [colorNode=null] - The color node to process.
  6335. */
  6336. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6337. super( 'vec3' );
  6338. /**
  6339. * The tone mapping type.
  6340. *
  6341. * @type {number}
  6342. */
  6343. this.toneMapping = toneMapping;
  6344. /**
  6345. * The tone mapping exposure.
  6346. *
  6347. * @type {Node}
  6348. * @default null
  6349. */
  6350. this.exposureNode = exposureNode;
  6351. /**
  6352. * Represents the color to process.
  6353. *
  6354. * @type {?Node}
  6355. * @default null
  6356. */
  6357. this.colorNode = colorNode;
  6358. }
  6359. /**
  6360. * Overwrites the default `customCacheKey()` implementation by including the tone
  6361. * mapping type into the cache key.
  6362. *
  6363. * @return {number} The hash.
  6364. */
  6365. customCacheKey() {
  6366. return hash$1( this.toneMapping );
  6367. }
  6368. setup( builder ) {
  6369. const colorNode = this.colorNode || builder.context.color;
  6370. const toneMapping = this.toneMapping;
  6371. if ( toneMapping === NoToneMapping ) return colorNode;
  6372. let outputNode = null;
  6373. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6374. if ( toneMappingFn !== null ) {
  6375. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6376. } else {
  6377. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6378. outputNode = colorNode;
  6379. }
  6380. return outputNode;
  6381. }
  6382. }
  6383. /**
  6384. * TSL function for creating a tone mapping node.
  6385. *
  6386. * @tsl
  6387. * @function
  6388. * @param {number} mapping - The tone mapping type.
  6389. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6390. * @param {Node<vec3> | Color} color - The color node to process.
  6391. * @returns {ToneMappingNode<vec3>}
  6392. */
  6393. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6394. /**
  6395. * TSL object that represents the global tone mapping exposure of the renderer.
  6396. *
  6397. * @tsl
  6398. * @type {RendererReferenceNode<vec3>}
  6399. */
  6400. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6401. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6402. /**
  6403. * In earlier `three.js` versions it was only possible to define attribute data
  6404. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6405. * on the node level.
  6406. * ```js
  6407. * const geometry = new THREE.PlaneGeometry();
  6408. * const positionAttribute = geometry.getAttribute( 'position' );
  6409. *
  6410. * const colors = [];
  6411. * for ( let i = 0; i < position.count; i ++ ) {
  6412. * colors.push( 1, 0, 0 );
  6413. * }
  6414. *
  6415. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6416. * ```
  6417. * This new approach is especially interesting when geometry data are generated via
  6418. * compute shaders. The below line converts a storage buffer into an attribute node.
  6419. * ```js
  6420. * material.positionNode = positionBuffer.toAttribute();
  6421. * ```
  6422. * @augments InputNode
  6423. */
  6424. class BufferAttributeNode extends InputNode {
  6425. static get type() {
  6426. return 'BufferAttributeNode';
  6427. }
  6428. /**
  6429. * Constructs a new buffer attribute node.
  6430. *
  6431. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6432. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6433. * @param {number} [bufferStride=0] - The buffer stride.
  6434. * @param {number} [bufferOffset=0] - The buffer offset.
  6435. */
  6436. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6437. super( value, bufferType );
  6438. /**
  6439. * This flag can be used for type testing.
  6440. *
  6441. * @type {boolean}
  6442. * @readonly
  6443. * @default true
  6444. */
  6445. this.isBufferNode = true;
  6446. /**
  6447. * The buffer type (e.g. `'vec3'`).
  6448. *
  6449. * @type {?string}
  6450. * @default null
  6451. */
  6452. this.bufferType = bufferType;
  6453. /**
  6454. * The buffer stride.
  6455. *
  6456. * @type {number}
  6457. * @default 0
  6458. */
  6459. this.bufferStride = bufferStride;
  6460. /**
  6461. * The buffer offset.
  6462. *
  6463. * @type {number}
  6464. * @default 0
  6465. */
  6466. this.bufferOffset = bufferOffset;
  6467. /**
  6468. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6469. * if you are planning to update the attribute data per frame.
  6470. *
  6471. * @type {number}
  6472. * @default StaticDrawUsage
  6473. */
  6474. this.usage = StaticDrawUsage;
  6475. /**
  6476. * Whether the attribute is instanced or not.
  6477. *
  6478. * @type {boolean}
  6479. * @default false
  6480. */
  6481. this.instanced = false;
  6482. /**
  6483. * A reference to the buffer attribute.
  6484. *
  6485. * @type {?BufferAttribute}
  6486. * @default null
  6487. */
  6488. this.attribute = null;
  6489. /**
  6490. * `BufferAttributeNode` sets this property to `true` by default.
  6491. *
  6492. * @type {boolean}
  6493. * @default true
  6494. */
  6495. this.global = true;
  6496. if ( value && value.isBufferAttribute === true ) {
  6497. this.attribute = value;
  6498. this.usage = value.usage;
  6499. this.instanced = value.isInstancedBufferAttribute;
  6500. }
  6501. }
  6502. /**
  6503. * This method is overwritten since the attribute data might be shared
  6504. * and thus the hash should be shared as well.
  6505. *
  6506. * @param {NodeBuilder} builder - The current node builder.
  6507. * @return {string} The hash.
  6508. */
  6509. getHash( builder ) {
  6510. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6511. let bufferData = builder.globalCache.getData( this.value );
  6512. if ( bufferData === undefined ) {
  6513. bufferData = {
  6514. node: this
  6515. };
  6516. builder.globalCache.setData( this.value, bufferData );
  6517. }
  6518. return bufferData.node.uuid;
  6519. }
  6520. return this.uuid;
  6521. }
  6522. /**
  6523. * This method is overwritten since the node type is inferred from
  6524. * the buffer attribute.
  6525. *
  6526. * @param {NodeBuilder} builder - The current node builder.
  6527. * @return {string} The node type.
  6528. */
  6529. getNodeType( builder ) {
  6530. if ( this.bufferType === null ) {
  6531. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6532. }
  6533. return this.bufferType;
  6534. }
  6535. /**
  6536. * Depending on which value was passed to the node, `setup()` behaves
  6537. * differently. If no instance of `BufferAttribute` was passed, the method
  6538. * creates an internal attribute and configures it respectively.
  6539. *
  6540. * @param {NodeBuilder} builder - The current node builder.
  6541. */
  6542. setup( builder ) {
  6543. if ( this.attribute !== null ) return;
  6544. const type = this.getNodeType( builder );
  6545. const array = this.value;
  6546. const itemSize = builder.getTypeLength( type );
  6547. const stride = this.bufferStride || itemSize;
  6548. const offset = this.bufferOffset;
  6549. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6550. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6551. buffer.setUsage( this.usage );
  6552. this.attribute = bufferAttribute;
  6553. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6554. }
  6555. /**
  6556. * Generates the code snippet of the buffer attribute node.
  6557. *
  6558. * @param {NodeBuilder} builder - The current node builder.
  6559. * @return {string} The generated code snippet.
  6560. */
  6561. generate( builder ) {
  6562. const nodeType = this.getNodeType( builder );
  6563. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6564. const propertyName = builder.getPropertyName( nodeAttribute );
  6565. let output = null;
  6566. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6567. this.name = propertyName;
  6568. output = propertyName;
  6569. } else {
  6570. const nodeVarying = varying( this );
  6571. output = nodeVarying.build( builder, nodeType );
  6572. }
  6573. return output;
  6574. }
  6575. /**
  6576. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6577. *
  6578. * @param {NodeBuilder} builder - The current node builder.
  6579. * @return {string} The input type.
  6580. */
  6581. getInputType( /*builder*/ ) {
  6582. return 'bufferAttribute';
  6583. }
  6584. /**
  6585. * Sets the `usage` property to the given value.
  6586. *
  6587. * @param {number} value - The usage to set.
  6588. * @return {BufferAttributeNode} A reference to this node.
  6589. */
  6590. setUsage( value ) {
  6591. this.usage = value;
  6592. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6593. this.attribute.usage = value;
  6594. }
  6595. return this;
  6596. }
  6597. /**
  6598. * Sets the `instanced` property to the given value.
  6599. *
  6600. * @param {boolean} value - The value to set.
  6601. * @return {BufferAttributeNode} A reference to this node.
  6602. */
  6603. setInstanced( value ) {
  6604. this.instanced = value;
  6605. return this;
  6606. }
  6607. }
  6608. /**
  6609. * TSL function for creating a buffer attribute node.
  6610. *
  6611. * @tsl
  6612. * @function
  6613. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6614. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6615. * @param {number} [stride=0] - The buffer stride.
  6616. * @param {number} [offset=0] - The buffer offset.
  6617. * @returns {BufferAttributeNode}
  6618. */
  6619. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6620. /**
  6621. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6622. * Use this function if attribute data are updated per frame.
  6623. *
  6624. * @tsl
  6625. * @function
  6626. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6627. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6628. * @param {number} [stride=0] - The buffer stride.
  6629. * @param {number} [offset=0] - The buffer offset.
  6630. * @returns {BufferAttributeNode}
  6631. */
  6632. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6633. /**
  6634. * TSL function for creating a buffer attribute node but with enabled instancing
  6635. *
  6636. * @tsl
  6637. * @function
  6638. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6639. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6640. * @param {number} [stride=0] - The buffer stride.
  6641. * @param {number} [offset=0] - The buffer offset.
  6642. * @returns {BufferAttributeNode}
  6643. */
  6644. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6645. /**
  6646. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6647. *
  6648. * @tsl
  6649. * @function
  6650. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6651. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6652. * @param {number} [stride=0] - The buffer stride.
  6653. * @param {number} [offset=0] - The buffer offset.
  6654. * @returns {BufferAttributeNode}
  6655. */
  6656. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6657. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6658. /**
  6659. * TODO
  6660. *
  6661. * @augments Node
  6662. */
  6663. class ComputeNode extends Node {
  6664. static get type() {
  6665. return 'ComputeNode';
  6666. }
  6667. /**
  6668. * Constructs a new compute node.
  6669. *
  6670. * @param {Node} computeNode - TODO
  6671. * @param {Array<number>} workgroupSize - TODO.
  6672. */
  6673. constructor( computeNode, workgroupSize ) {
  6674. super( 'void' );
  6675. /**
  6676. * This flag can be used for type testing.
  6677. *
  6678. * @type {boolean}
  6679. * @readonly
  6680. * @default true
  6681. */
  6682. this.isComputeNode = true;
  6683. /**
  6684. * TODO
  6685. *
  6686. * @type {Node}
  6687. */
  6688. this.computeNode = computeNode;
  6689. /**
  6690. * TODO
  6691. *
  6692. * @type {Array<number>}
  6693. * @default [ 64 ]
  6694. */
  6695. this.workgroupSize = workgroupSize;
  6696. /**
  6697. * TODO
  6698. *
  6699. * @type {number}
  6700. */
  6701. this.count = null;
  6702. /**
  6703. * TODO
  6704. *
  6705. * @type {number}
  6706. */
  6707. this.version = 1;
  6708. /**
  6709. * The name or label of the uniform.
  6710. *
  6711. * @type {string}
  6712. * @default ''
  6713. */
  6714. this.name = '';
  6715. /**
  6716. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6717. * is executed once per object by default.
  6718. *
  6719. * @type {string}
  6720. * @default 'object'
  6721. */
  6722. this.updateBeforeType = NodeUpdateType.OBJECT;
  6723. /**
  6724. * TODO
  6725. *
  6726. * @type {?Function}
  6727. */
  6728. this.onInitFunction = null;
  6729. }
  6730. setCount( count ) {
  6731. this.count = count;
  6732. return this;
  6733. }
  6734. getCount() {
  6735. return this.count;
  6736. }
  6737. /**
  6738. * Executes the `dispose` event for this node.
  6739. */
  6740. dispose() {
  6741. this.dispatchEvent( { type: 'dispose' } );
  6742. }
  6743. /**
  6744. * Sets the {@link ComputeNode#name} property.
  6745. *
  6746. * @param {string} name - The name of the uniform.
  6747. * @return {ComputeNode} A reference to this node.
  6748. */
  6749. setName( name ) {
  6750. this.name = name;
  6751. return this;
  6752. }
  6753. /**
  6754. * Sets the {@link ComputeNode#name} property.
  6755. *
  6756. * @deprecated
  6757. * @param {string} name - The name of the uniform.
  6758. * @return {ComputeNode} A reference to this node.
  6759. */
  6760. label( name ) {
  6761. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6762. return this.setName( name );
  6763. }
  6764. /**
  6765. * TODO
  6766. *
  6767. * @param {Function} callback - TODO.
  6768. * @return {ComputeNode} A reference to this node.
  6769. */
  6770. onInit( callback ) {
  6771. this.onInitFunction = callback;
  6772. return this;
  6773. }
  6774. /**
  6775. * The method execute the compute for this node.
  6776. *
  6777. * @param {NodeFrame} frame - A reference to the current node frame.
  6778. */
  6779. updateBefore( { renderer } ) {
  6780. renderer.compute( this );
  6781. }
  6782. setup( builder ) {
  6783. const result = this.computeNode.build( builder );
  6784. if ( result ) {
  6785. const properties = builder.getNodeProperties( this );
  6786. properties.outputComputeNode = result.outputNode;
  6787. result.outputNode = null;
  6788. }
  6789. return result;
  6790. }
  6791. generate( builder, output ) {
  6792. const { shaderStage } = builder;
  6793. if ( shaderStage === 'compute' ) {
  6794. const snippet = this.computeNode.build( builder, 'void' );
  6795. if ( snippet !== '' ) {
  6796. builder.addLineFlowCode( snippet, this );
  6797. }
  6798. } else {
  6799. const properties = builder.getNodeProperties( this );
  6800. const outputComputeNode = properties.outputComputeNode;
  6801. if ( outputComputeNode ) {
  6802. return outputComputeNode.build( builder, output );
  6803. }
  6804. }
  6805. }
  6806. }
  6807. /**
  6808. * TSL function for creating a compute kernel node.
  6809. *
  6810. * @tsl
  6811. * @function
  6812. * @param {Node} node - TODO
  6813. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6814. * @returns {AtomicFunctionNode}
  6815. */
  6816. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6817. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6818. console.error( 'THREE.TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6819. }
  6820. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6821. const val = workgroupSize[ i ];
  6822. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6823. console.error( `THREE.TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6824. }
  6825. }
  6826. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6827. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6828. //
  6829. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6830. };
  6831. /**
  6832. * TSL function for creating a compute node.
  6833. *
  6834. * @tsl
  6835. * @function
  6836. * @param {Node} node - TODO
  6837. * @param {number} count - TODO.
  6838. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6839. * @returns {AtomicFunctionNode}
  6840. */
  6841. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  6842. addMethodChaining( 'compute', compute );
  6843. addMethodChaining( 'computeKernel', computeKernel );
  6844. /**
  6845. * This node can be used as a cache management component for another node.
  6846. * Caching is in general used by default in {@link NodeBuilder} but this node
  6847. * allows the usage of a shared parent cache during the build process.
  6848. *
  6849. * @augments Node
  6850. */
  6851. class CacheNode extends Node {
  6852. static get type() {
  6853. return 'CacheNode';
  6854. }
  6855. /**
  6856. * Constructs a new cache node.
  6857. *
  6858. * @param {Node} node - The node that should be cached.
  6859. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6860. */
  6861. constructor( node, parent = true ) {
  6862. super();
  6863. /**
  6864. * The node that should be cached.
  6865. *
  6866. * @type {Node}
  6867. */
  6868. this.node = node;
  6869. /**
  6870. * Whether this node refers to a shared parent cache or not.
  6871. *
  6872. * @type {boolean}
  6873. * @default true
  6874. */
  6875. this.parent = parent;
  6876. /**
  6877. * This flag can be used for type testing.
  6878. *
  6879. * @type {boolean}
  6880. * @readonly
  6881. * @default true
  6882. */
  6883. this.isCacheNode = true;
  6884. }
  6885. getNodeType( builder ) {
  6886. const previousCache = builder.getCache();
  6887. const cache = builder.getCacheFromNode( this, this.parent );
  6888. builder.setCache( cache );
  6889. const nodeType = this.node.getNodeType( builder );
  6890. builder.setCache( previousCache );
  6891. return nodeType;
  6892. }
  6893. build( builder, ...params ) {
  6894. const previousCache = builder.getCache();
  6895. const cache = builder.getCacheFromNode( this, this.parent );
  6896. builder.setCache( cache );
  6897. const data = this.node.build( builder, ...params );
  6898. builder.setCache( previousCache );
  6899. return data;
  6900. }
  6901. }
  6902. /**
  6903. * TSL function for creating a cache node.
  6904. *
  6905. * @tsl
  6906. * @function
  6907. * @param {Node} node - The node that should be cached.
  6908. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6909. * @returns {CacheNode}
  6910. */
  6911. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6912. addMethodChaining( 'cache', cache );
  6913. /**
  6914. * The class generates the code of a given node but returns another node in the output.
  6915. * This can be used to call a method or node that does not return a value, i.e.
  6916. * type `void` on an input where returning a value is required. Example:
  6917. *
  6918. * ```js
  6919. * material.colorNode = myColor.bypass( runVoidFn() )
  6920. *```
  6921. *
  6922. * @augments Node
  6923. */
  6924. class BypassNode extends Node {
  6925. static get type() {
  6926. return 'BypassNode';
  6927. }
  6928. /**
  6929. * Constructs a new bypass node.
  6930. *
  6931. * @param {Node} outputNode - The output node.
  6932. * @param {Node} callNode - The call node.
  6933. */
  6934. constructor( outputNode, callNode ) {
  6935. super();
  6936. /**
  6937. * This flag can be used for type testing.
  6938. *
  6939. * @type {boolean}
  6940. * @readonly
  6941. * @default true
  6942. */
  6943. this.isBypassNode = true;
  6944. /**
  6945. * The output node.
  6946. *
  6947. * @type {Node}
  6948. */
  6949. this.outputNode = outputNode;
  6950. /**
  6951. * The call node.
  6952. *
  6953. * @type {Node}
  6954. */
  6955. this.callNode = callNode;
  6956. }
  6957. getNodeType( builder ) {
  6958. return this.outputNode.getNodeType( builder );
  6959. }
  6960. generate( builder ) {
  6961. const snippet = this.callNode.build( builder, 'void' );
  6962. if ( snippet !== '' ) {
  6963. builder.addLineFlowCode( snippet, this );
  6964. }
  6965. return this.outputNode.build( builder );
  6966. }
  6967. }
  6968. /**
  6969. * TSL function for creating a bypass node.
  6970. *
  6971. * @tsl
  6972. * @function
  6973. * @param {Node} outputNode - The output node.
  6974. * @param {Node} callNode - The call node.
  6975. * @returns {BypassNode}
  6976. */
  6977. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6978. addMethodChaining( 'bypass', bypass );
  6979. /**
  6980. * This node allows to remap a node value from one range into another. E.g a value of
  6981. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6982. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6983. *
  6984. * @augments Node
  6985. */
  6986. class RemapNode extends Node {
  6987. static get type() {
  6988. return 'RemapNode';
  6989. }
  6990. /**
  6991. * Constructs a new remap node.
  6992. *
  6993. * @param {Node} node - The node that should be remapped.
  6994. * @param {Node} inLowNode - The source or current lower bound of the range.
  6995. * @param {Node} inHighNode - The source or current upper bound of the range.
  6996. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6997. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6998. */
  6999. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7000. super();
  7001. /**
  7002. * The node that should be remapped.
  7003. *
  7004. * @type {Node}
  7005. */
  7006. this.node = node;
  7007. /**
  7008. * The source or current lower bound of the range.
  7009. *
  7010. * @type {Node}
  7011. */
  7012. this.inLowNode = inLowNode;
  7013. /**
  7014. * The source or current upper bound of the range.
  7015. *
  7016. * @type {Node}
  7017. */
  7018. this.inHighNode = inHighNode;
  7019. /**
  7020. * The target lower bound of the range.
  7021. *
  7022. * @type {Node}
  7023. * @default float(0)
  7024. */
  7025. this.outLowNode = outLowNode;
  7026. /**
  7027. * The target upper bound of the range.
  7028. *
  7029. * @type {Node}
  7030. * @default float(1)
  7031. */
  7032. this.outHighNode = outHighNode;
  7033. /**
  7034. * Whether the node value should be clamped before
  7035. * remapping it to the target range.
  7036. *
  7037. * @type {boolean}
  7038. * @default true
  7039. */
  7040. this.doClamp = true;
  7041. }
  7042. setup() {
  7043. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7044. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7045. if ( doClamp === true ) t = t.clamp();
  7046. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7047. }
  7048. }
  7049. /**
  7050. * TSL function for creating a remap node.
  7051. *
  7052. * @tsl
  7053. * @function
  7054. * @param {Node} node - The node that should be remapped.
  7055. * @param {Node} inLowNode - The source or current lower bound of the range.
  7056. * @param {Node} inHighNode - The source or current upper bound of the range.
  7057. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7058. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7059. * @returns {RemapNode}
  7060. */
  7061. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7062. /**
  7063. * TSL function for creating a remap node, but with enabled clamping.
  7064. *
  7065. * @tsl
  7066. * @function
  7067. * @param {Node} node - The node that should be remapped.
  7068. * @param {Node} inLowNode - The source or current lower bound of the range.
  7069. * @param {Node} inHighNode - The source or current upper bound of the range.
  7070. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7071. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7072. * @returns {RemapNode}
  7073. */
  7074. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7075. addMethodChaining( 'remap', remap );
  7076. addMethodChaining( 'remapClamp', remapClamp );
  7077. /**
  7078. * This class can be used to implement basic expressions in shader code.
  7079. * Basic examples for that are `return`, `continue` or `discard` statements.
  7080. *
  7081. * @augments Node
  7082. */
  7083. class ExpressionNode extends Node {
  7084. static get type() {
  7085. return 'ExpressionNode';
  7086. }
  7087. /**
  7088. * Constructs a new expression node.
  7089. *
  7090. * @param {string} [snippet=''] - The native code snippet.
  7091. * @param {string} [nodeType='void'] - The node type.
  7092. */
  7093. constructor( snippet = '', nodeType = 'void' ) {
  7094. super( nodeType );
  7095. /**
  7096. * The native code snippet.
  7097. *
  7098. * @type {string}
  7099. * @default ''
  7100. */
  7101. this.snippet = snippet;
  7102. }
  7103. generate( builder, output ) {
  7104. const type = this.getNodeType( builder );
  7105. const snippet = this.snippet;
  7106. if ( type === 'void' ) {
  7107. builder.addLineFlowCode( snippet, this );
  7108. } else {
  7109. return builder.format( snippet, type, output );
  7110. }
  7111. }
  7112. }
  7113. /**
  7114. * TSL function for creating an expression node.
  7115. *
  7116. * @tsl
  7117. * @function
  7118. * @param {string} [snippet] - The native code snippet.
  7119. * @param {?string} [nodeType='void'] - The node type.
  7120. * @returns {ExpressionNode}
  7121. */
  7122. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7123. /**
  7124. * Represents a `discard` shader operation in TSL.
  7125. *
  7126. * @tsl
  7127. * @function
  7128. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7129. * @return {Node} The `discard` expression.
  7130. */
  7131. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7132. /**
  7133. * Represents a `return` shader operation in TSL.
  7134. *
  7135. * @tsl
  7136. * @function
  7137. * @return {ExpressionNode} The `return` expression.
  7138. */
  7139. const Return = () => expression( 'return' ).toStack();
  7140. addMethodChaining( 'discard', Discard );
  7141. /**
  7142. * Normally, tone mapping and color conversion happens automatically
  7143. * before outputting pixel too the default (screen) framebuffer. In certain
  7144. * post processing setups this happens to late because certain effects
  7145. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7146. * to apply tone mapping and color space conversion at an arbitrary point
  7147. * in the effect chain.
  7148. *
  7149. * When applying tone mapping and color space conversion manually with this node,
  7150. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7151. *
  7152. * ```js
  7153. * const postProcessing = new PostProcessing( renderer );
  7154. * postProcessing.outputColorTransform = false;
  7155. *
  7156. * const scenePass = pass( scene, camera );
  7157. * const outputPass = renderOutput( scenePass );
  7158. *
  7159. * postProcessing.outputNode = outputPass;
  7160. * ```
  7161. *
  7162. * @augments TempNode
  7163. */
  7164. class RenderOutputNode extends TempNode {
  7165. static get type() {
  7166. return 'RenderOutputNode';
  7167. }
  7168. /**
  7169. * Constructs a new render output node.
  7170. *
  7171. * @param {Node} colorNode - The color node to process.
  7172. * @param {?number} toneMapping - The tone mapping type.
  7173. * @param {?string} outputColorSpace - The output color space.
  7174. */
  7175. constructor( colorNode, toneMapping, outputColorSpace ) {
  7176. super( 'vec4' );
  7177. /**
  7178. * The color node to process.
  7179. *
  7180. * @type {Node}
  7181. */
  7182. this.colorNode = colorNode;
  7183. /**
  7184. * The tone mapping type.
  7185. *
  7186. * @type {?number}
  7187. */
  7188. this.toneMapping = toneMapping;
  7189. /**
  7190. * The output color space.
  7191. *
  7192. * @type {?string}
  7193. */
  7194. this.outputColorSpace = outputColorSpace;
  7195. /**
  7196. * This flag can be used for type testing.
  7197. *
  7198. * @type {boolean}
  7199. * @readonly
  7200. * @default true
  7201. */
  7202. this.isRenderOutputNode = true;
  7203. }
  7204. setup( { context } ) {
  7205. let outputNode = this.colorNode || context.color;
  7206. // tone mapping
  7207. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  7208. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7209. if ( toneMapping !== NoToneMapping ) {
  7210. outputNode = outputNode.toneMapping( toneMapping );
  7211. }
  7212. // working to output color space
  7213. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7214. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7215. }
  7216. return outputNode;
  7217. }
  7218. }
  7219. /**
  7220. * TSL function for creating a posterize node.
  7221. *
  7222. * @tsl
  7223. * @function
  7224. * @param {Node} color - The color node to process.
  7225. * @param {?number} [toneMapping=null] - The tone mapping type.
  7226. * @param {?string} [outputColorSpace=null] - The output color space.
  7227. * @returns {RenderOutputNode}
  7228. */
  7229. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7230. addMethodChaining( 'renderOutput', renderOutput );
  7231. class DebugNode extends TempNode {
  7232. static get type() {
  7233. return 'DebugNode';
  7234. }
  7235. constructor( node, callback = null ) {
  7236. super();
  7237. this.node = node;
  7238. this.callback = callback;
  7239. }
  7240. getNodeType( builder ) {
  7241. return this.node.getNodeType( builder );
  7242. }
  7243. setup( builder ) {
  7244. return this.node.build( builder );
  7245. }
  7246. analyze( builder ) {
  7247. return this.node.build( builder );
  7248. }
  7249. generate( builder ) {
  7250. const callback = this.callback;
  7251. const snippet = this.node.build( builder );
  7252. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7253. const border = '-'.repeat( title.length );
  7254. let code = '';
  7255. code += '// #' + title + '#\n';
  7256. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7257. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7258. code += '// #' + border + '#\n';
  7259. if ( callback !== null ) {
  7260. callback( builder, code );
  7261. } else {
  7262. console.log( code );
  7263. }
  7264. return snippet;
  7265. }
  7266. }
  7267. /**
  7268. * TSL function for creating a debug node.
  7269. *
  7270. * @tsl
  7271. * @function
  7272. * @param {Node} node - The node to debug.
  7273. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7274. * @returns {DebugNode}
  7275. */
  7276. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7277. addMethodChaining( 'debug', debug );
  7278. // Non-PURE exports list, side-effects are required here.
  7279. // TSL Base Syntax
  7280. function addNodeElement( name/*, nodeElement*/ ) {
  7281. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7282. }
  7283. /**
  7284. * Base class for representing shader attributes as nodes.
  7285. *
  7286. * @augments Node
  7287. */
  7288. class AttributeNode extends Node {
  7289. static get type() {
  7290. return 'AttributeNode';
  7291. }
  7292. /**
  7293. * Constructs a new attribute node.
  7294. *
  7295. * @param {string} attributeName - The name of the attribute.
  7296. * @param {?string} nodeType - The node type.
  7297. */
  7298. constructor( attributeName, nodeType = null ) {
  7299. super( nodeType );
  7300. /**
  7301. * `AttributeNode` sets this property to `true` by default.
  7302. *
  7303. * @type {boolean}
  7304. * @default true
  7305. */
  7306. this.global = true;
  7307. this._attributeName = attributeName;
  7308. }
  7309. getHash( builder ) {
  7310. return this.getAttributeName( builder );
  7311. }
  7312. getNodeType( builder ) {
  7313. let nodeType = this.nodeType;
  7314. if ( nodeType === null ) {
  7315. const attributeName = this.getAttributeName( builder );
  7316. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7317. const attribute = builder.geometry.getAttribute( attributeName );
  7318. nodeType = builder.getTypeFromAttribute( attribute );
  7319. } else {
  7320. nodeType = 'float';
  7321. }
  7322. }
  7323. return nodeType;
  7324. }
  7325. /**
  7326. * Sets the attribute name to the given value. The method can be
  7327. * overwritten in derived classes if the final name must be computed
  7328. * analytically.
  7329. *
  7330. * @param {string} attributeName - The name of the attribute.
  7331. * @return {AttributeNode} A reference to this node.
  7332. */
  7333. setAttributeName( attributeName ) {
  7334. this._attributeName = attributeName;
  7335. return this;
  7336. }
  7337. /**
  7338. * Returns the attribute name of this node. The method can be
  7339. * overwritten in derived classes if the final name must be computed
  7340. * analytically.
  7341. *
  7342. * @param {NodeBuilder} builder - The current node builder.
  7343. * @return {string} The attribute name.
  7344. */
  7345. getAttributeName( /*builder*/ ) {
  7346. return this._attributeName;
  7347. }
  7348. generate( builder ) {
  7349. const attributeName = this.getAttributeName( builder );
  7350. const nodeType = this.getNodeType( builder );
  7351. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7352. if ( geometryAttribute === true ) {
  7353. const attribute = builder.geometry.getAttribute( attributeName );
  7354. const attributeType = builder.getTypeFromAttribute( attribute );
  7355. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7356. if ( builder.shaderStage === 'vertex' ) {
  7357. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7358. } else {
  7359. const nodeVarying = varying( this );
  7360. return nodeVarying.build( builder, nodeType );
  7361. }
  7362. } else {
  7363. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7364. return builder.generateConst( nodeType );
  7365. }
  7366. }
  7367. serialize( data ) {
  7368. super.serialize( data );
  7369. data.global = this.global;
  7370. data._attributeName = this._attributeName;
  7371. }
  7372. deserialize( data ) {
  7373. super.deserialize( data );
  7374. this.global = data.global;
  7375. this._attributeName = data._attributeName;
  7376. }
  7377. }
  7378. /**
  7379. * TSL function for creating an attribute node.
  7380. *
  7381. * @tsl
  7382. * @function
  7383. * @param {string} name - The name of the attribute.
  7384. * @param {?string} [nodeType=null] - The node type.
  7385. * @returns {AttributeNode}
  7386. */
  7387. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7388. /**
  7389. * TSL function for creating an uv attribute node with the given index.
  7390. *
  7391. * @tsl
  7392. * @function
  7393. * @param {number} [index=0] - The uv index.
  7394. * @return {AttributeNode<vec2>} The uv attribute node.
  7395. */
  7396. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7397. /**
  7398. * A node that represents the dimensions of a texture. The texture size is
  7399. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7400. * or `textureSize()`.
  7401. *
  7402. * @augments Node
  7403. */
  7404. class TextureSizeNode extends Node {
  7405. static get type() {
  7406. return 'TextureSizeNode';
  7407. }
  7408. /**
  7409. * Constructs a new texture size node.
  7410. *
  7411. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7412. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7413. */
  7414. constructor( textureNode, levelNode = null ) {
  7415. super( 'uvec2' );
  7416. /**
  7417. * This flag can be used for type testing.
  7418. *
  7419. * @type {boolean}
  7420. * @readonly
  7421. * @default true
  7422. */
  7423. this.isTextureSizeNode = true;
  7424. /**
  7425. * A texture node which size should be retrieved.
  7426. *
  7427. * @type {TextureNode}
  7428. */
  7429. this.textureNode = textureNode;
  7430. /**
  7431. * A level node which defines the requested mip.
  7432. *
  7433. * @type {Node<int>}
  7434. * @default null
  7435. */
  7436. this.levelNode = levelNode;
  7437. }
  7438. generate( builder, output ) {
  7439. const textureProperty = this.textureNode.build( builder, 'property' );
  7440. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7441. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7442. }
  7443. }
  7444. /**
  7445. * TSL function for creating a texture size node.
  7446. *
  7447. * @tsl
  7448. * @function
  7449. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7450. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7451. * @returns {TextureSizeNode}
  7452. */
  7453. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7454. /**
  7455. * A special type of uniform node that computes the
  7456. * maximum mipmap level for a given texture node.
  7457. *
  7458. * ```js
  7459. * const level = maxMipLevel( textureNode );
  7460. * ```
  7461. *
  7462. * @augments UniformNode
  7463. */
  7464. class MaxMipLevelNode extends UniformNode {
  7465. static get type() {
  7466. return 'MaxMipLevelNode';
  7467. }
  7468. /**
  7469. * Constructs a new max mip level node.
  7470. *
  7471. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7472. */
  7473. constructor( textureNode ) {
  7474. super( 0 );
  7475. /**
  7476. * The texture node to compute the max mip level for.
  7477. *
  7478. * @private
  7479. * @type {TextureNode}
  7480. */
  7481. this._textureNode = textureNode;
  7482. /**
  7483. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7484. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7485. *
  7486. * @type {string}
  7487. * @default 'frame'
  7488. */
  7489. this.updateType = NodeUpdateType.FRAME;
  7490. }
  7491. /**
  7492. * The texture node to compute the max mip level for.
  7493. *
  7494. * @readonly
  7495. * @type {TextureNode}
  7496. */
  7497. get textureNode() {
  7498. return this._textureNode;
  7499. }
  7500. /**
  7501. * The texture.
  7502. *
  7503. * @readonly
  7504. * @type {Texture}
  7505. */
  7506. get texture() {
  7507. return this._textureNode.value;
  7508. }
  7509. update() {
  7510. const texture = this.texture;
  7511. const images = texture.images;
  7512. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7513. if ( image && image.width !== undefined ) {
  7514. const { width, height } = image;
  7515. this.value = Math.log2( Math.max( width, height ) );
  7516. }
  7517. }
  7518. }
  7519. /**
  7520. * TSL function for creating a max mip level node.
  7521. *
  7522. * @tsl
  7523. * @function
  7524. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7525. * @returns {MaxMipLevelNode}
  7526. */
  7527. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7528. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7529. /**
  7530. * This type of uniform node represents a 2D texture.
  7531. *
  7532. * @augments UniformNode
  7533. */
  7534. class TextureNode extends UniformNode {
  7535. static get type() {
  7536. return 'TextureNode';
  7537. }
  7538. /**
  7539. * Constructs a new texture node.
  7540. *
  7541. * @param {Texture} [value=EmptyTexture] - The texture.
  7542. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7543. * @param {?Node<int>} [levelNode=null] - The level node.
  7544. * @param {?Node<float>} [biasNode=null] - The bias node.
  7545. */
  7546. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7547. super( value );
  7548. /**
  7549. * This flag can be used for type testing.
  7550. *
  7551. * @type {boolean}
  7552. * @readonly
  7553. * @default true
  7554. */
  7555. this.isTextureNode = true;
  7556. /**
  7557. * Represents the texture coordinates.
  7558. *
  7559. * @type {?Node<vec2|vec3>}
  7560. * @default null
  7561. */
  7562. this.uvNode = uvNode;
  7563. /**
  7564. * Represents the mip level that should be selected.
  7565. *
  7566. * @type {?Node<int>}
  7567. * @default null
  7568. */
  7569. this.levelNode = levelNode;
  7570. /**
  7571. * Represents the bias to be applied during level-of-detail computation.
  7572. *
  7573. * @type {?Node<float>}
  7574. * @default null
  7575. */
  7576. this.biasNode = biasNode;
  7577. /**
  7578. * Represents a reference value a texture sample is compared to.
  7579. *
  7580. * @type {?Node<float>}
  7581. * @default null
  7582. */
  7583. this.compareNode = null;
  7584. /**
  7585. * When using texture arrays, the depth node defines the layer to select.
  7586. *
  7587. * @type {?Node<int>}
  7588. * @default null
  7589. */
  7590. this.depthNode = null;
  7591. /**
  7592. * When defined, a texture is sampled using explicit gradients.
  7593. *
  7594. * @type {?Array<Node<vec2>>}
  7595. * @default null
  7596. */
  7597. this.gradNode = null;
  7598. /**
  7599. * Whether texture values should be sampled or fetched.
  7600. *
  7601. * @type {boolean}
  7602. * @default true
  7603. */
  7604. this.sampler = true;
  7605. /**
  7606. * Whether the uv transformation matrix should be
  7607. * automatically updated or not. Use `setUpdateMatrix()`
  7608. * if you want to change the value of the property.
  7609. *
  7610. * @type {boolean}
  7611. * @default false
  7612. */
  7613. this.updateMatrix = false;
  7614. /**
  7615. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7616. * sets the value to `frame` when the uv transformation matrix should
  7617. * automatically be updated.
  7618. *
  7619. * @type {string}
  7620. * @default 'none'
  7621. */
  7622. this.updateType = NodeUpdateType.NONE;
  7623. /**
  7624. * The reference node.
  7625. *
  7626. * @type {?Node}
  7627. * @default null
  7628. */
  7629. this.referenceNode = null;
  7630. /**
  7631. * The texture value is stored in a private property.
  7632. *
  7633. * @private
  7634. * @type {Texture}
  7635. */
  7636. this._value = value;
  7637. /**
  7638. * The uniform node that represents the uv transformation matrix.
  7639. *
  7640. * @private
  7641. * @type {?UniformNode<mat3>}
  7642. */
  7643. this._matrixUniform = null;
  7644. this.setUpdateMatrix( uvNode === null );
  7645. }
  7646. set value( value ) {
  7647. if ( this.referenceNode ) {
  7648. this.referenceNode.value = value;
  7649. } else {
  7650. this._value = value;
  7651. }
  7652. }
  7653. /**
  7654. * The texture value.
  7655. *
  7656. * @type {Texture}
  7657. */
  7658. get value() {
  7659. return this.referenceNode ? this.referenceNode.value : this._value;
  7660. }
  7661. /**
  7662. * Overwritten since the uniform hash is defined by the texture's UUID.
  7663. *
  7664. * @param {NodeBuilder} builder - The current node builder.
  7665. * @return {string} The uniform hash.
  7666. */
  7667. getUniformHash( /*builder*/ ) {
  7668. return this.value.uuid;
  7669. }
  7670. /**
  7671. * Overwritten since the node type is inferred from the texture type.
  7672. *
  7673. * @param {NodeBuilder} builder - The current node builder.
  7674. * @return {string} The node type.
  7675. */
  7676. getNodeType( /*builder*/ ) {
  7677. if ( this.value.isDepthTexture === true ) return 'float';
  7678. if ( this.value.type === UnsignedIntType ) {
  7679. return 'uvec4';
  7680. } else if ( this.value.type === IntType ) {
  7681. return 'ivec4';
  7682. }
  7683. return 'vec4';
  7684. }
  7685. /**
  7686. * Overwrites the default implementation to return a fixed value `'texture'`.
  7687. *
  7688. * @param {NodeBuilder} builder - The current node builder.
  7689. * @return {string} The input type.
  7690. */
  7691. getInputType( /*builder*/ ) {
  7692. return 'texture';
  7693. }
  7694. /**
  7695. * Returns a default uvs based on the current texture's channel.
  7696. *
  7697. * @return {AttributeNode<vec2>} The default uvs.
  7698. */
  7699. getDefaultUV() {
  7700. return uv$1( this.value.channel );
  7701. }
  7702. /**
  7703. * Overwritten to always return the texture reference of the node.
  7704. *
  7705. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7706. * @return {Texture} The texture reference.
  7707. */
  7708. updateReference( /*state*/ ) {
  7709. return this.value;
  7710. }
  7711. /**
  7712. * Transforms the given uv node with the texture transformation matrix.
  7713. *
  7714. * @param {Node} uvNode - The uv node to transform.
  7715. * @return {Node} The transformed uv node.
  7716. */
  7717. getTransformedUV( uvNode ) {
  7718. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7719. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7720. }
  7721. /**
  7722. * Defines whether the uv transformation matrix should automatically be updated or not.
  7723. *
  7724. * @param {boolean} value - The update toggle.
  7725. * @return {TextureNode} A reference to this node.
  7726. */
  7727. setUpdateMatrix( value ) {
  7728. this.updateMatrix = value;
  7729. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7730. return this;
  7731. }
  7732. /**
  7733. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7734. * to modify the uv node for correct sampling.
  7735. *
  7736. * @param {NodeBuilder} builder - The current node builder.
  7737. * @param {Node} uvNode - The uv node to setup.
  7738. * @return {Node} The updated uv node.
  7739. */
  7740. setupUV( builder, uvNode ) {
  7741. const texture = this.value;
  7742. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7743. if ( this.sampler ) {
  7744. uvNode = uvNode.flipY();
  7745. } else {
  7746. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7747. }
  7748. }
  7749. return uvNode;
  7750. }
  7751. /**
  7752. * Setups texture node by preparing the internal nodes for code generation.
  7753. *
  7754. * @param {NodeBuilder} builder - The current node builder.
  7755. */
  7756. setup( builder ) {
  7757. const properties = builder.getNodeProperties( this );
  7758. properties.referenceNode = this.referenceNode;
  7759. //
  7760. const texture = this.value;
  7761. if ( ! texture || texture.isTexture !== true ) {
  7762. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7763. }
  7764. //
  7765. let uvNode = this.uvNode;
  7766. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7767. uvNode = builder.context.getUV( this, builder );
  7768. }
  7769. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7770. if ( this.updateMatrix === true ) {
  7771. uvNode = this.getTransformedUV( uvNode );
  7772. }
  7773. uvNode = this.setupUV( builder, uvNode );
  7774. //
  7775. let levelNode = this.levelNode;
  7776. if ( levelNode === null && builder.context.getTextureLevel ) {
  7777. levelNode = builder.context.getTextureLevel( this );
  7778. }
  7779. //
  7780. properties.uvNode = uvNode;
  7781. properties.levelNode = levelNode;
  7782. properties.biasNode = this.biasNode;
  7783. properties.compareNode = this.compareNode;
  7784. properties.gradNode = this.gradNode;
  7785. properties.depthNode = this.depthNode;
  7786. }
  7787. /**
  7788. * Generates the uv code snippet.
  7789. *
  7790. * @param {NodeBuilder} builder - The current node builder.
  7791. * @param {Node} uvNode - The uv node to generate code for.
  7792. * @return {string} The generated code snippet.
  7793. */
  7794. generateUV( builder, uvNode ) {
  7795. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7796. }
  7797. /**
  7798. * Generates the snippet for the texture sampling.
  7799. *
  7800. * @param {NodeBuilder} builder - The current node builder.
  7801. * @param {string} textureProperty - The texture property.
  7802. * @param {string} uvSnippet - The uv snippet.
  7803. * @param {?string} levelSnippet - The level snippet.
  7804. * @param {?string} biasSnippet - The bias snippet.
  7805. * @param {?string} depthSnippet - The depth snippet.
  7806. * @param {?string} compareSnippet - The compare snippet.
  7807. * @param {?Array<string>} gradSnippet - The grad snippet.
  7808. * @return {string} The generated code snippet.
  7809. */
  7810. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7811. const texture = this.value;
  7812. let snippet;
  7813. if ( levelSnippet ) {
  7814. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7815. } else if ( biasSnippet ) {
  7816. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7817. } else if ( gradSnippet ) {
  7818. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7819. } else if ( compareSnippet ) {
  7820. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7821. } else if ( this.sampler === false ) {
  7822. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7823. } else {
  7824. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7825. }
  7826. return snippet;
  7827. }
  7828. /**
  7829. * Generates the code snippet of the texture node.
  7830. *
  7831. * @param {NodeBuilder} builder - The current node builder.
  7832. * @param {string} output - The current output.
  7833. * @return {string} The generated code snippet.
  7834. */
  7835. generate( builder, output ) {
  7836. const texture = this.value;
  7837. const properties = builder.getNodeProperties( this );
  7838. const textureProperty = super.generate( builder, 'property' );
  7839. if ( /^sampler/.test( output ) ) {
  7840. return textureProperty + '_sampler';
  7841. } else if ( builder.isReference( output ) ) {
  7842. return textureProperty;
  7843. } else {
  7844. const nodeData = builder.getDataFromNode( this );
  7845. let propertyName = nodeData.propertyName;
  7846. if ( propertyName === undefined ) {
  7847. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7848. const uvSnippet = this.generateUV( builder, uvNode );
  7849. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7850. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7851. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7852. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7853. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7854. const nodeVar = builder.getVarFromNode( this );
  7855. propertyName = builder.getPropertyName( nodeVar );
  7856. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7857. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7858. nodeData.snippet = snippet;
  7859. nodeData.propertyName = propertyName;
  7860. }
  7861. let snippet = propertyName;
  7862. const nodeType = this.getNodeType( builder );
  7863. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7864. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7865. }
  7866. return builder.format( snippet, nodeType, output );
  7867. }
  7868. }
  7869. /**
  7870. * Sets the sampler value.
  7871. *
  7872. * @param {boolean} value - The sampler value to set.
  7873. * @return {TextureNode} A reference to this texture node.
  7874. */
  7875. setSampler( value ) {
  7876. this.sampler = value;
  7877. return this;
  7878. }
  7879. /**
  7880. * Returns the sampler value.
  7881. *
  7882. * @return {boolean} The sampler value.
  7883. */
  7884. getSampler() {
  7885. return this.sampler;
  7886. }
  7887. // @TODO: Move to TSL
  7888. /**
  7889. * @function
  7890. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7891. *
  7892. * @param {Node} uvNode - The uv node.
  7893. * @return {TextureNode} A texture node representing the texture sample.
  7894. */
  7895. uv( uvNode ) { // @deprecated, r172
  7896. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7897. return this.sample( uvNode );
  7898. }
  7899. /**
  7900. * Samples the texture with the given uv node.
  7901. *
  7902. * @param {Node} uvNode - The uv node.
  7903. * @return {TextureNode} A texture node representing the texture sample.
  7904. */
  7905. sample( uvNode ) {
  7906. const textureNode = this.clone();
  7907. textureNode.uvNode = nodeObject( uvNode );
  7908. textureNode.referenceNode = this.getBase();
  7909. return nodeObject( textureNode );
  7910. }
  7911. /**
  7912. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7913. *
  7914. * @param {Node<uvec2>} uvNode - The uv node.
  7915. * @returns {TextureNode} A texture node representing the texture load.
  7916. */
  7917. load( uvNode ) {
  7918. return this.sample( uvNode ).setSampler( false );
  7919. }
  7920. /**
  7921. * Samples a blurred version of the texture by defining an internal bias.
  7922. *
  7923. * @param {Node<float>} amountNode - How blurred the texture should be.
  7924. * @return {TextureNode} A texture node representing the texture sample.
  7925. */
  7926. blur( amountNode ) {
  7927. const textureNode = this.clone();
  7928. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7929. textureNode.referenceNode = this.getBase();
  7930. const map = textureNode.value;
  7931. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7932. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7933. textureNode.biasNode = null;
  7934. }
  7935. return nodeObject( textureNode );
  7936. }
  7937. /**
  7938. * Samples a specific mip of the texture.
  7939. *
  7940. * @param {Node<int>} levelNode - The mip level to sample.
  7941. * @return {TextureNode} A texture node representing the texture sample.
  7942. */
  7943. level( levelNode ) {
  7944. const textureNode = this.clone();
  7945. textureNode.levelNode = nodeObject( levelNode );
  7946. textureNode.referenceNode = this.getBase();
  7947. return nodeObject( textureNode );
  7948. }
  7949. /**
  7950. * Returns the texture size of the requested level.
  7951. *
  7952. * @param {Node<int>} levelNode - The level to compute the size for.
  7953. * @return {TextureSizeNode} The texture size.
  7954. */
  7955. size( levelNode ) {
  7956. return textureSize( this, levelNode );
  7957. }
  7958. /**
  7959. * Samples the texture with the given bias.
  7960. *
  7961. * @param {Node<float>} biasNode - The bias node.
  7962. * @return {TextureNode} A texture node representing the texture sample.
  7963. */
  7964. bias( biasNode ) {
  7965. const textureNode = this.clone();
  7966. textureNode.biasNode = nodeObject( biasNode );
  7967. textureNode.referenceNode = this.getBase();
  7968. return nodeObject( textureNode );
  7969. }
  7970. /**
  7971. * Returns the base texture of this node.
  7972. * @return {TextureNode} The base texture node.
  7973. */
  7974. getBase() {
  7975. return this.referenceNode ? this.referenceNode.getBase() : this.getSelf();
  7976. }
  7977. /**
  7978. * Samples the texture by executing a compare operation.
  7979. *
  7980. * @param {Node<float>} compareNode - The node that defines the compare value.
  7981. * @return {TextureNode} A texture node representing the texture sample.
  7982. */
  7983. compare( compareNode ) {
  7984. const textureNode = this.clone();
  7985. textureNode.compareNode = nodeObject( compareNode );
  7986. textureNode.referenceNode = this.getBase();
  7987. return nodeObject( textureNode );
  7988. }
  7989. /**
  7990. * Samples the texture using an explicit gradient.
  7991. *
  7992. * @param {Node<vec2>} gradNodeX - The gradX node.
  7993. * @param {Node<vec2>} gradNodeY - The gradY node.
  7994. * @return {TextureNode} A texture node representing the texture sample.
  7995. */
  7996. grad( gradNodeX, gradNodeY ) {
  7997. const textureNode = this.clone();
  7998. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7999. textureNode.referenceNode = this.getBase();
  8000. return nodeObject( textureNode );
  8001. }
  8002. /**
  8003. * Samples the texture by defining a depth node.
  8004. *
  8005. * @param {Node<int>} depthNode - The depth node.
  8006. * @return {TextureNode} A texture node representing the texture sample.
  8007. */
  8008. depth( depthNode ) {
  8009. const textureNode = this.clone();
  8010. textureNode.depthNode = nodeObject( depthNode );
  8011. textureNode.referenceNode = this.getBase();
  8012. return nodeObject( textureNode );
  8013. }
  8014. // --
  8015. serialize( data ) {
  8016. super.serialize( data );
  8017. data.value = this.value.toJSON( data.meta ).uuid;
  8018. data.sampler = this.sampler;
  8019. data.updateMatrix = this.updateMatrix;
  8020. data.updateType = this.updateType;
  8021. }
  8022. deserialize( data ) {
  8023. super.deserialize( data );
  8024. this.value = data.meta.textures[ data.value ];
  8025. this.sampler = data.sampler;
  8026. this.updateMatrix = data.updateMatrix;
  8027. this.updateType = data.updateType;
  8028. }
  8029. /**
  8030. * The update is used to implement the update of the uv transformation matrix.
  8031. */
  8032. update() {
  8033. const texture = this.value;
  8034. const matrixUniform = this._matrixUniform;
  8035. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8036. if ( texture.matrixAutoUpdate === true ) {
  8037. texture.updateMatrix();
  8038. }
  8039. }
  8040. /**
  8041. * Clones the texture node.
  8042. *
  8043. * @return {TextureNode} The cloned texture node.
  8044. */
  8045. clone() {
  8046. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8047. newNode.sampler = this.sampler;
  8048. newNode.depthNode = this.depthNode;
  8049. newNode.compareNode = this.compareNode;
  8050. newNode.gradNode = this.gradNode;
  8051. return newNode;
  8052. }
  8053. }
  8054. /**
  8055. * TSL function for creating a texture node.
  8056. *
  8057. * @tsl
  8058. * @function
  8059. * @param {?Texture} value - The texture.
  8060. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8061. * @param {?Node<int>} [levelNode=null] - The level node.
  8062. * @param {?Node<float>} [biasNode=null] - The bias node.
  8063. * @returns {TextureNode}
  8064. */
  8065. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8066. /**
  8067. * TSL function for creating a texture node or sample a texture node already existing.
  8068. *
  8069. * @tsl
  8070. * @function
  8071. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  8072. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8073. * @param {?Node<int>} [levelNode=null] - The level node.
  8074. * @param {?Node<float>} [biasNode=null] - The bias node.
  8075. * @returns {TextureNode}
  8076. */
  8077. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8078. let textureNode;
  8079. if ( value && value.isTextureNode === true ) {
  8080. textureNode = nodeObject( value.clone() );
  8081. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8082. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8083. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8084. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8085. } else {
  8086. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8087. }
  8088. return textureNode;
  8089. };
  8090. /**
  8091. * TSL function for creating a uniform texture node.
  8092. *
  8093. * @tsl
  8094. * @function
  8095. * @param {?Texture} value - The texture.
  8096. * @returns {TextureNode}
  8097. */
  8098. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8099. /**
  8100. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8101. *
  8102. * @tsl
  8103. * @function
  8104. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  8105. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8106. * @param {?Node<int>} [levelNode=null] - The level node.
  8107. * @param {?Node<float>} [biasNode=null] - The bias node.
  8108. * @returns {TextureNode}
  8109. */
  8110. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8111. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8112. /**
  8113. * Converts a texture or texture node to a sampler.
  8114. *
  8115. * @tsl
  8116. * @function
  8117. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8118. * @returns {Node}
  8119. */
  8120. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8121. /**
  8122. * Converts a texture or texture node to a sampler comparison.
  8123. *
  8124. * @tsl
  8125. * @function
  8126. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8127. * @returns {Node}
  8128. */
  8129. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8130. /**
  8131. * A special type of uniform node which represents array-like data
  8132. * as uniform buffers. The access usually happens via `element()`
  8133. * which returns an instance of {@link ArrayElementNode}. For example:
  8134. *
  8135. * ```js
  8136. * const bufferNode = buffer( array, 'mat4', count );
  8137. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8138. * ```
  8139. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8140. * since it handles more input types and automatically cares about buffer paddings.
  8141. *
  8142. * @augments UniformNode
  8143. */
  8144. class BufferNode extends UniformNode {
  8145. static get type() {
  8146. return 'BufferNode';
  8147. }
  8148. /**
  8149. * Constructs a new buffer node.
  8150. *
  8151. * @param {Array<number>} value - Array-like buffer data.
  8152. * @param {string} bufferType - The data type of the buffer.
  8153. * @param {number} [bufferCount=0] - The count of buffer elements.
  8154. */
  8155. constructor( value, bufferType, bufferCount = 0 ) {
  8156. super( value, bufferType );
  8157. /**
  8158. * This flag can be used for type testing.
  8159. *
  8160. * @type {boolean}
  8161. * @readonly
  8162. * @default true
  8163. */
  8164. this.isBufferNode = true;
  8165. /**
  8166. * The data type of the buffer.
  8167. *
  8168. * @type {string}
  8169. */
  8170. this.bufferType = bufferType;
  8171. /**
  8172. * The uniform node that holds the value of the reference node.
  8173. *
  8174. * @type {number}
  8175. * @default 0
  8176. */
  8177. this.bufferCount = bufferCount;
  8178. }
  8179. /**
  8180. * The data type of the buffer elements.
  8181. *
  8182. * @param {NodeBuilder} builder - The current node builder.
  8183. * @return {string} The element type.
  8184. */
  8185. getElementType( builder ) {
  8186. return this.getNodeType( builder );
  8187. }
  8188. /**
  8189. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8190. *
  8191. * @param {NodeBuilder} builder - The current node builder.
  8192. * @return {string} The input type.
  8193. */
  8194. getInputType( /*builder*/ ) {
  8195. return 'buffer';
  8196. }
  8197. }
  8198. /**
  8199. * TSL function for creating a buffer node.
  8200. *
  8201. * @tsl
  8202. * @function
  8203. * @param {Array} value - Array-like buffer data.
  8204. * @param {string} type - The data type of a buffer element.
  8205. * @param {number} count - The count of buffer elements.
  8206. * @returns {BufferNode}
  8207. */
  8208. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8209. /**
  8210. * Represents the element access on uniform array nodes.
  8211. *
  8212. * @augments ArrayElementNode
  8213. */
  8214. class UniformArrayElementNode extends ArrayElementNode {
  8215. static get type() {
  8216. return 'UniformArrayElementNode';
  8217. }
  8218. /**
  8219. * Constructs a new buffer node.
  8220. *
  8221. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8222. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8223. */
  8224. constructor( uniformArrayNode, indexNode ) {
  8225. super( uniformArrayNode, indexNode );
  8226. /**
  8227. * This flag can be used for type testing.
  8228. *
  8229. * @type {boolean}
  8230. * @readonly
  8231. * @default true
  8232. */
  8233. this.isArrayBufferElementNode = true;
  8234. }
  8235. generate( builder ) {
  8236. const snippet = super.generate( builder );
  8237. const type = this.getNodeType();
  8238. const paddedType = this.node.getPaddedType();
  8239. return builder.format( snippet, paddedType, type );
  8240. }
  8241. }
  8242. /**
  8243. * Similar to {@link BufferNode} this module represents array-like data as
  8244. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8245. * data types in the array (e.g `three.js` primitives) and automatically
  8246. * manage buffer padding. It should be the first choice when working with
  8247. * uniforms buffers.
  8248. * ```js
  8249. * const tintColors = uniformArray( [
  8250. * new Color( 1, 0, 0 ),
  8251. * new Color( 0, 1, 0 ),
  8252. * new Color( 0, 0, 1 )
  8253. * ], 'color' );
  8254. *
  8255. * const redColor = tintColors.element( 0 );
  8256. *
  8257. * @augments BufferNode
  8258. */
  8259. class UniformArrayNode extends BufferNode {
  8260. static get type() {
  8261. return 'UniformArrayNode';
  8262. }
  8263. /**
  8264. * Constructs a new uniform array node.
  8265. *
  8266. * @param {Array<any>} value - Array holding the buffer data.
  8267. * @param {?string} [elementType=null] - The data type of a buffer element.
  8268. */
  8269. constructor( value, elementType = null ) {
  8270. super( null );
  8271. /**
  8272. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8273. * hold number primitives as well as three.js objects like vectors, matrices
  8274. * or colors.
  8275. *
  8276. * @type {Array<any>}
  8277. */
  8278. this.array = value;
  8279. /**
  8280. * The data type of an array element.
  8281. *
  8282. * @type {string}
  8283. */
  8284. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8285. /**
  8286. * The padded type. Uniform buffers must conform to a certain buffer layout
  8287. * so a separate type is computed to ensure correct buffer size.
  8288. *
  8289. * @type {string}
  8290. */
  8291. this.paddedType = this.getPaddedType();
  8292. /**
  8293. * Overwritten since uniform array nodes are updated per render.
  8294. *
  8295. * @type {string}
  8296. * @default 'render'
  8297. */
  8298. this.updateType = NodeUpdateType.RENDER;
  8299. /**
  8300. * This flag can be used for type testing.
  8301. *
  8302. * @type {boolean}
  8303. * @readonly
  8304. * @default true
  8305. */
  8306. this.isArrayBufferNode = true;
  8307. }
  8308. /**
  8309. * This method is overwritten since the node type is inferred from the
  8310. * {@link UniformArrayNode#paddedType}.
  8311. *
  8312. * @param {NodeBuilder} builder - The current node builder.
  8313. * @return {string} The node type.
  8314. */
  8315. getNodeType( /*builder*/ ) {
  8316. return this.paddedType;
  8317. }
  8318. /**
  8319. * The data type of the array elements.
  8320. *
  8321. * @param {NodeBuilder} builder - The current node builder.
  8322. * @return {string} The element type.
  8323. */
  8324. getElementType() {
  8325. return this.elementType;
  8326. }
  8327. /**
  8328. * Returns the padded type based on the element type.
  8329. *
  8330. * @return {string} The padded type.
  8331. */
  8332. getPaddedType() {
  8333. const elementType = this.elementType;
  8334. let paddedType = 'vec4';
  8335. if ( elementType === 'mat2' ) {
  8336. paddedType = 'mat2';
  8337. } else if ( /mat/.test( elementType ) === true ) {
  8338. paddedType = 'mat4';
  8339. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8340. paddedType = 'ivec4';
  8341. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8342. paddedType = 'uvec4';
  8343. }
  8344. return paddedType;
  8345. }
  8346. /**
  8347. * The update makes sure to correctly transfer the data from the (complex) objects
  8348. * in the array to the internal, correctly padded value buffer.
  8349. *
  8350. * @param {NodeFrame} frame - A reference to the current node frame.
  8351. */
  8352. update( /*frame*/ ) {
  8353. const { array, value } = this;
  8354. const elementType = this.elementType;
  8355. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8356. for ( let i = 0; i < array.length; i ++ ) {
  8357. const index = i * 4;
  8358. value[ index ] = array[ i ];
  8359. }
  8360. } else if ( elementType === 'color' ) {
  8361. for ( let i = 0; i < array.length; i ++ ) {
  8362. const index = i * 4;
  8363. const vector = array[ i ];
  8364. value[ index ] = vector.r;
  8365. value[ index + 1 ] = vector.g;
  8366. value[ index + 2 ] = vector.b || 0;
  8367. //value[ index + 3 ] = vector.a || 0;
  8368. }
  8369. } else if ( elementType === 'mat2' ) {
  8370. for ( let i = 0; i < array.length; i ++ ) {
  8371. const index = i * 4;
  8372. const matrix = array[ i ];
  8373. value[ index ] = matrix.elements[ 0 ];
  8374. value[ index + 1 ] = matrix.elements[ 1 ];
  8375. value[ index + 2 ] = matrix.elements[ 2 ];
  8376. value[ index + 3 ] = matrix.elements[ 3 ];
  8377. }
  8378. } else if ( elementType === 'mat3' ) {
  8379. for ( let i = 0; i < array.length; i ++ ) {
  8380. const index = i * 16;
  8381. const matrix = array[ i ];
  8382. value[ index ] = matrix.elements[ 0 ];
  8383. value[ index + 1 ] = matrix.elements[ 1 ];
  8384. value[ index + 2 ] = matrix.elements[ 2 ];
  8385. value[ index + 4 ] = matrix.elements[ 3 ];
  8386. value[ index + 5 ] = matrix.elements[ 4 ];
  8387. value[ index + 6 ] = matrix.elements[ 5 ];
  8388. value[ index + 8 ] = matrix.elements[ 6 ];
  8389. value[ index + 9 ] = matrix.elements[ 7 ];
  8390. value[ index + 10 ] = matrix.elements[ 8 ];
  8391. value[ index + 15 ] = 1;
  8392. }
  8393. } else if ( elementType === 'mat4' ) {
  8394. for ( let i = 0; i < array.length; i ++ ) {
  8395. const index = i * 16;
  8396. const matrix = array[ i ];
  8397. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8398. value[ index + i ] = matrix.elements[ i ];
  8399. }
  8400. }
  8401. } else {
  8402. for ( let i = 0; i < array.length; i ++ ) {
  8403. const index = i * 4;
  8404. const vector = array[ i ];
  8405. value[ index ] = vector.x;
  8406. value[ index + 1 ] = vector.y;
  8407. value[ index + 2 ] = vector.z || 0;
  8408. value[ index + 3 ] = vector.w || 0;
  8409. }
  8410. }
  8411. }
  8412. /**
  8413. * Implement the value buffer creation based on the array data.
  8414. *
  8415. * @param {NodeBuilder} builder - A reference to the current node builder.
  8416. * @return {null}
  8417. */
  8418. setup( builder ) {
  8419. const length = this.array.length;
  8420. const elementType = this.elementType;
  8421. let arrayType = Float32Array;
  8422. const paddedType = this.paddedType;
  8423. const paddedElementLength = builder.getTypeLength( paddedType );
  8424. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8425. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8426. this.value = new arrayType( length * paddedElementLength );
  8427. this.bufferCount = length;
  8428. this.bufferType = paddedType;
  8429. return super.setup( builder );
  8430. }
  8431. /**
  8432. * Overwrites the default `element()` method to provide element access
  8433. * based on {@link UniformArrayNode}.
  8434. *
  8435. * @param {IndexNode} indexNode - The index node.
  8436. * @return {UniformArrayElementNode}
  8437. */
  8438. element( indexNode ) {
  8439. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8440. }
  8441. }
  8442. /**
  8443. * TSL function for creating an uniform array node.
  8444. *
  8445. * @tsl
  8446. * @function
  8447. * @param {Array<any>} values - Array-like data.
  8448. * @param {?string} [nodeType] - The data type of the array elements.
  8449. * @returns {UniformArrayNode}
  8450. */
  8451. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8452. /**
  8453. * The node allows to set values for built-in shader variables. That is
  8454. * required for features like hardware-accelerated vertex clipping.
  8455. *
  8456. * @augments Node
  8457. */
  8458. class BuiltinNode extends Node {
  8459. /**
  8460. * Constructs a new builtin node.
  8461. *
  8462. * @param {string} name - The name of the built-in shader variable.
  8463. */
  8464. constructor( name ) {
  8465. super( 'float' );
  8466. /**
  8467. * The name of the built-in shader variable.
  8468. *
  8469. * @type {string}
  8470. */
  8471. this.name = name;
  8472. /**
  8473. * This flag can be used for type testing.
  8474. *
  8475. * @type {boolean}
  8476. * @readonly
  8477. * @default true
  8478. */
  8479. this.isBuiltinNode = true;
  8480. }
  8481. /**
  8482. * Generates the code snippet of the builtin node.
  8483. *
  8484. * @param {NodeBuilder} builder - The current node builder.
  8485. * @return {string} The generated code snippet.
  8486. */
  8487. generate( /* builder */ ) {
  8488. return this.name;
  8489. }
  8490. }
  8491. /**
  8492. * TSL function for creating a builtin node.
  8493. *
  8494. * @tsl
  8495. * @function
  8496. * @param {string} name - The name of the built-in shader variable.
  8497. * @returns {BuiltinNode}
  8498. */
  8499. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8500. let screenSizeVec, viewportVec;
  8501. /**
  8502. * This node provides a collection of screen related metrics.
  8503. * Depending on {@link ScreenNode#scope}, the nodes can represent
  8504. * resolution or viewport data as well as fragment or uv coordinates.
  8505. *
  8506. * @augments Node
  8507. */
  8508. class ScreenNode extends Node {
  8509. static get type() {
  8510. return 'ScreenNode';
  8511. }
  8512. /**
  8513. * Constructs a new screen node.
  8514. *
  8515. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  8516. */
  8517. constructor( scope ) {
  8518. super();
  8519. /**
  8520. * The node represents different metric depending on which scope is selected.
  8521. *
  8522. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  8523. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  8524. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  8525. * - `ScreenNode.UV`: Normalized coordinates.
  8526. *
  8527. * @type {('coordinate'|'viewport'|'size'|'uv')}
  8528. */
  8529. this.scope = scope;
  8530. /**
  8531. * This flag can be used for type testing.
  8532. *
  8533. * @type {boolean}
  8534. * @readonly
  8535. * @default true
  8536. */
  8537. this.isViewportNode = true;
  8538. }
  8539. /**
  8540. * This method is overwritten since the node type depends on the selected scope.
  8541. *
  8542. * @return {('vec2'|'vec4')} The node type.
  8543. */
  8544. getNodeType() {
  8545. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  8546. else return 'vec2';
  8547. }
  8548. /**
  8549. * This method is overwritten since the node's update type depends on the selected scope.
  8550. *
  8551. * @return {NodeUpdateType} The update type.
  8552. */
  8553. getUpdateType() {
  8554. let updateType = NodeUpdateType.NONE;
  8555. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  8556. updateType = NodeUpdateType.RENDER;
  8557. }
  8558. this.updateType = updateType;
  8559. return updateType;
  8560. }
  8561. /**
  8562. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  8563. * from the current renderer.
  8564. *
  8565. * @param {NodeFrame} frame - A reference to the current node frame.
  8566. */
  8567. update( { renderer } ) {
  8568. const renderTarget = renderer.getRenderTarget();
  8569. if ( this.scope === ScreenNode.VIEWPORT ) {
  8570. if ( renderTarget !== null ) {
  8571. viewportVec.copy( renderTarget.viewport );
  8572. } else {
  8573. renderer.getViewport( viewportVec );
  8574. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  8575. }
  8576. } else {
  8577. if ( renderTarget !== null ) {
  8578. screenSizeVec.width = renderTarget.width;
  8579. screenSizeVec.height = renderTarget.height;
  8580. } else {
  8581. renderer.getDrawingBufferSize( screenSizeVec );
  8582. }
  8583. }
  8584. }
  8585. setup( /*builder*/ ) {
  8586. const scope = this.scope;
  8587. let output = null;
  8588. if ( scope === ScreenNode.SIZE ) {
  8589. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  8590. } else if ( scope === ScreenNode.VIEWPORT ) {
  8591. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  8592. } else {
  8593. output = vec2( screenCoordinate.div( screenSize ) );
  8594. }
  8595. return output;
  8596. }
  8597. generate( builder ) {
  8598. if ( this.scope === ScreenNode.COORDINATE ) {
  8599. let coord = builder.getFragCoord();
  8600. if ( builder.isFlipY() ) {
  8601. // follow webgpu standards
  8602. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  8603. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  8604. }
  8605. return coord;
  8606. }
  8607. return super.generate( builder );
  8608. }
  8609. }
  8610. ScreenNode.COORDINATE = 'coordinate';
  8611. ScreenNode.VIEWPORT = 'viewport';
  8612. ScreenNode.SIZE = 'size';
  8613. ScreenNode.UV = 'uv';
  8614. // Screen
  8615. /**
  8616. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  8617. *
  8618. * @tsl
  8619. * @type {ScreenNode<vec2>}
  8620. */
  8621. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  8622. /**
  8623. * TSL object that represents the screen resolution in physical pixel units.
  8624. *
  8625. * @tsl
  8626. * @type {ScreenNode<vec2>}
  8627. */
  8628. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  8629. /**
  8630. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  8631. *
  8632. * @tsl
  8633. * @type {ScreenNode<vec2>}
  8634. */
  8635. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  8636. // Viewport
  8637. /**
  8638. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  8639. *
  8640. * @tsl
  8641. * @type {ScreenNode<vec4>}
  8642. */
  8643. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  8644. /**
  8645. * TSL object that represents the viewport resolution in physical pixel units.
  8646. *
  8647. * @tsl
  8648. * @type {ScreenNode<vec2>}
  8649. */
  8650. const viewportSize = viewport.zw;
  8651. /**
  8652. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  8653. *
  8654. * @tsl
  8655. * @type {ScreenNode<vec2>}
  8656. */
  8657. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  8658. /**
  8659. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  8660. *
  8661. * @tsl
  8662. * @type {ScreenNode<vec2>}
  8663. */
  8664. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  8665. // Deprecated
  8666. /**
  8667. * @deprecated since r169. Use {@link screenSize} instead.
  8668. */
  8669. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  8670. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  8671. return screenSize;
  8672. }, 'vec2' ).once() )();
  8673. /**
  8674. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8675. *
  8676. * @tsl
  8677. * @type {UniformNode<uint>}
  8678. */
  8679. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8680. /**
  8681. * TSL object that represents the `near` value of the camera used for the current render.
  8682. *
  8683. * @tsl
  8684. * @type {UniformNode<float>}
  8685. */
  8686. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8687. /**
  8688. * TSL object that represents the `far` value of the camera used for the current render.
  8689. *
  8690. * @tsl
  8691. * @type {UniformNode<float>}
  8692. */
  8693. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8694. /**
  8695. * TSL object that represents the projection matrix of the camera used for the current render.
  8696. *
  8697. * @tsl
  8698. * @type {UniformNode<mat4>}
  8699. */
  8700. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8701. let cameraProjectionMatrix;
  8702. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8703. const matrices = [];
  8704. for ( const subCamera of camera.cameras ) {
  8705. matrices.push( subCamera.projectionMatrix );
  8706. }
  8707. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  8708. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  8709. } else {
  8710. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8711. }
  8712. return cameraProjectionMatrix;
  8713. } ).once() )();
  8714. /**
  8715. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8716. *
  8717. * @tsl
  8718. * @type {UniformNode<mat4>}
  8719. */
  8720. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8721. let cameraProjectionMatrixInverse;
  8722. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8723. const matrices = [];
  8724. for ( const subCamera of camera.cameras ) {
  8725. matrices.push( subCamera.projectionMatrixInverse );
  8726. }
  8727. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  8728. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  8729. } else {
  8730. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8731. }
  8732. return cameraProjectionMatrixInverse;
  8733. } ).once() )();
  8734. /**
  8735. * TSL object that represents the view matrix of the camera used for the current render.
  8736. *
  8737. * @tsl
  8738. * @type {UniformNode<mat4>}
  8739. */
  8740. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8741. let cameraViewMatrix;
  8742. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8743. const matrices = [];
  8744. for ( const subCamera of camera.cameras ) {
  8745. matrices.push( subCamera.matrixWorldInverse );
  8746. }
  8747. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  8748. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  8749. } else {
  8750. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8751. }
  8752. return cameraViewMatrix;
  8753. } ).once() )();
  8754. /**
  8755. * TSL object that represents the world matrix of the camera used for the current render.
  8756. *
  8757. * @tsl
  8758. * @type {UniformNode<mat4>}
  8759. */
  8760. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8761. let cameraWorldMatrix;
  8762. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8763. const matrices = [];
  8764. for ( const subCamera of camera.cameras ) {
  8765. matrices.push( subCamera.matrixWorld );
  8766. }
  8767. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  8768. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  8769. } else {
  8770. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8771. }
  8772. return cameraWorldMatrix;
  8773. } ).once() )();
  8774. /**
  8775. * TSL object that represents the normal matrix of the camera used for the current render.
  8776. *
  8777. * @tsl
  8778. * @type {UniformNode<mat3>}
  8779. */
  8780. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8781. let cameraNormalMatrix;
  8782. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8783. const matrices = [];
  8784. for ( const subCamera of camera.cameras ) {
  8785. matrices.push( subCamera.normalMatrix );
  8786. }
  8787. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  8788. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  8789. } else {
  8790. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8791. }
  8792. return cameraNormalMatrix;
  8793. } ).once() )();
  8794. /**
  8795. * TSL object that represents the position in world space of the camera used for the current render.
  8796. *
  8797. * @tsl
  8798. * @type {UniformNode<vec3>}
  8799. */
  8800. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8801. let cameraPosition;
  8802. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8803. const positions = [];
  8804. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  8805. positions.push( new Vector3() );
  8806. }
  8807. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  8808. const subCameras = camera.cameras;
  8809. const array = self.array;
  8810. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  8811. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  8812. }
  8813. } );
  8814. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  8815. } else {
  8816. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8817. }
  8818. return cameraPosition;
  8819. } ).once() )();
  8820. /**
  8821. * TSL object that represents the viewport of the camera used for the current render.
  8822. *
  8823. * @tsl
  8824. * @type {UniformNode<vec4>}
  8825. */
  8826. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8827. let cameraViewport;
  8828. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8829. const viewports = [];
  8830. for ( const subCamera of camera.cameras ) {
  8831. viewports.push( subCamera.viewport );
  8832. }
  8833. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  8834. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  8835. } else {
  8836. // Fallback for single camera
  8837. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  8838. }
  8839. return cameraViewport;
  8840. } ).once() )();
  8841. const _sphere = /*@__PURE__*/ new Sphere();
  8842. /**
  8843. * This node can be used to access transformation related metrics of 3D objects.
  8844. * Depending on the selected scope, a different metric is represented as a uniform
  8845. * in the shader. The following scopes are supported:
  8846. *
  8847. * - `POSITION`: The object's position in world space.
  8848. * - `VIEW_POSITION`: The object's position in view/camera space.
  8849. * - `DIRECTION`: The object's direction in world space.
  8850. * - `SCALE`: The object's scale in world space.
  8851. * - `WORLD_MATRIX`: The object's matrix in world space.
  8852. *
  8853. * @augments Node
  8854. */
  8855. class Object3DNode extends Node {
  8856. static get type() {
  8857. return 'Object3DNode';
  8858. }
  8859. /**
  8860. * Constructs a new object 3D node.
  8861. *
  8862. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8863. * @param {?Object3D} [object3d=null] - The 3D object.
  8864. */
  8865. constructor( scope, object3d = null ) {
  8866. super();
  8867. /**
  8868. * The node reports a different type of transformation depending on the scope.
  8869. *
  8870. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8871. */
  8872. this.scope = scope;
  8873. /**
  8874. * The 3D object.
  8875. *
  8876. * @type {?Object3D}
  8877. * @default null
  8878. */
  8879. this.object3d = object3d;
  8880. /**
  8881. * Overwritten since this type of node is updated per object.
  8882. *
  8883. * @type {string}
  8884. * @default 'object'
  8885. */
  8886. this.updateType = NodeUpdateType.OBJECT;
  8887. /**
  8888. * Holds the value of the node as a uniform.
  8889. *
  8890. * @type {UniformNode}
  8891. */
  8892. this.uniformNode = new UniformNode( null );
  8893. }
  8894. /**
  8895. * Overwritten since the node type is inferred from the scope.
  8896. *
  8897. * @return {string} The node type.
  8898. */
  8899. getNodeType() {
  8900. const scope = this.scope;
  8901. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8902. return 'mat4';
  8903. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8904. return 'vec3';
  8905. } else if ( scope === Object3DNode.RADIUS ) {
  8906. return 'float';
  8907. }
  8908. }
  8909. /**
  8910. * Updates the uniform value depending on the scope.
  8911. *
  8912. * @param {NodeFrame} frame - The current node frame.
  8913. */
  8914. update( frame ) {
  8915. const object = this.object3d;
  8916. const uniformNode = this.uniformNode;
  8917. const scope = this.scope;
  8918. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8919. uniformNode.value = object.matrixWorld;
  8920. } else if ( scope === Object3DNode.POSITION ) {
  8921. uniformNode.value = uniformNode.value || new Vector3();
  8922. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8923. } else if ( scope === Object3DNode.SCALE ) {
  8924. uniformNode.value = uniformNode.value || new Vector3();
  8925. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8926. } else if ( scope === Object3DNode.DIRECTION ) {
  8927. uniformNode.value = uniformNode.value || new Vector3();
  8928. object.getWorldDirection( uniformNode.value );
  8929. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8930. const camera = frame.camera;
  8931. uniformNode.value = uniformNode.value || new Vector3();
  8932. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8933. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8934. } else if ( scope === Object3DNode.RADIUS ) {
  8935. const geometry = frame.object.geometry;
  8936. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8937. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8938. uniformNode.value = _sphere.radius;
  8939. }
  8940. }
  8941. /**
  8942. * Generates the code snippet of the uniform node. The node type of the uniform
  8943. * node also depends on the selected scope.
  8944. *
  8945. * @param {NodeBuilder} builder - The current node builder.
  8946. * @return {string} The generated code snippet.
  8947. */
  8948. generate( builder ) {
  8949. const scope = this.scope;
  8950. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8951. this.uniformNode.nodeType = 'mat4';
  8952. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8953. this.uniformNode.nodeType = 'vec3';
  8954. } else if ( scope === Object3DNode.RADIUS ) {
  8955. this.uniformNode.nodeType = 'float';
  8956. }
  8957. return this.uniformNode.build( builder );
  8958. }
  8959. serialize( data ) {
  8960. super.serialize( data );
  8961. data.scope = this.scope;
  8962. }
  8963. deserialize( data ) {
  8964. super.deserialize( data );
  8965. this.scope = data.scope;
  8966. }
  8967. }
  8968. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8969. Object3DNode.POSITION = 'position';
  8970. Object3DNode.SCALE = 'scale';
  8971. Object3DNode.VIEW_POSITION = 'viewPosition';
  8972. Object3DNode.DIRECTION = 'direction';
  8973. Object3DNode.RADIUS = 'radius';
  8974. /**
  8975. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8976. *
  8977. * @tsl
  8978. * @function
  8979. * @param {?Object3D} [object3d] - The 3D object.
  8980. * @returns {Object3DNode<vec3>}
  8981. */
  8982. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8983. /**
  8984. * TSL function for creating an object 3D node that represents the object's world matrix.
  8985. *
  8986. * @tsl
  8987. * @function
  8988. * @param {?Object3D} [object3d] - The 3D object.
  8989. * @returns {Object3DNode<mat4>}
  8990. */
  8991. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  8992. /**
  8993. * TSL function for creating an object 3D node that represents the object's position in world space.
  8994. *
  8995. * @tsl
  8996. * @function
  8997. * @param {?Object3D} [object3d] - The 3D object.
  8998. * @returns {Object3DNode<vec3>}
  8999. */
  9000. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9001. /**
  9002. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9003. *
  9004. * @tsl
  9005. * @function
  9006. * @param {?Object3D} [object3d] - The 3D object.
  9007. * @returns {Object3DNode<vec3>}
  9008. */
  9009. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9010. /**
  9011. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9012. *
  9013. * @tsl
  9014. * @function
  9015. * @param {?Object3D} [object3d] - The 3D object.
  9016. * @returns {Object3DNode<vec3>}
  9017. */
  9018. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9019. /**
  9020. * TSL function for creating an object 3D node that represents the object's radius.
  9021. *
  9022. * @tsl
  9023. * @function
  9024. * @param {?Object3D} [object3d] - The 3D object.
  9025. * @returns {Object3DNode<float>}
  9026. */
  9027. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9028. /**
  9029. * This type of node is a specialized version of `Object3DNode`
  9030. * with larger set of model related metrics. Unlike `Object3DNode`,
  9031. * `ModelNode` extracts the reference to the 3D object from the
  9032. * current node frame state.
  9033. *
  9034. * @augments Object3DNode
  9035. */
  9036. class ModelNode extends Object3DNode {
  9037. static get type() {
  9038. return 'ModelNode';
  9039. }
  9040. /**
  9041. * Constructs a new object model node.
  9042. *
  9043. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9044. */
  9045. constructor( scope ) {
  9046. super( scope );
  9047. }
  9048. /**
  9049. * Extracts the model reference from the frame state and then
  9050. * updates the uniform value depending on the scope.
  9051. *
  9052. * @param {NodeFrame} frame - The current node frame.
  9053. */
  9054. update( frame ) {
  9055. this.object3d = frame.object;
  9056. super.update( frame );
  9057. }
  9058. }
  9059. /**
  9060. * TSL object that represents the object's direction in world space.
  9061. *
  9062. * @tsl
  9063. * @type {ModelNode<vec3>}
  9064. */
  9065. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9066. /**
  9067. * TSL object that represents the object's world matrix.
  9068. *
  9069. * @tsl
  9070. * @type {ModelNode<mat4>}
  9071. */
  9072. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9073. /**
  9074. * TSL object that represents the object's position in world space.
  9075. *
  9076. * @tsl
  9077. * @type {ModelNode<vec3>}
  9078. */
  9079. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9080. /**
  9081. * TSL object that represents the object's scale in world space.
  9082. *
  9083. * @tsl
  9084. * @type {ModelNode<vec3>}
  9085. */
  9086. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9087. /**
  9088. * TSL object that represents the object's position in view/camera space.
  9089. *
  9090. * @tsl
  9091. * @type {ModelNode<vec3>}
  9092. */
  9093. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9094. /**
  9095. * TSL object that represents the object's radius.
  9096. *
  9097. * @tsl
  9098. * @type {ModelNode<float>}
  9099. */
  9100. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9101. /**
  9102. * TSL object that represents the object's normal matrix.
  9103. *
  9104. * @tsl
  9105. * @type {UniformNode<mat3>}
  9106. */
  9107. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9108. /**
  9109. * TSL object that represents the object's inverse world matrix.
  9110. *
  9111. * @tsl
  9112. * @type {UniformNode<mat4>}
  9113. */
  9114. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9115. /**
  9116. * TSL object that represents the object's model view matrix.
  9117. *
  9118. * @tsl
  9119. * @type {Node<mat4>}
  9120. */
  9121. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9122. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9123. } ).once() )().toVar( 'modelViewMatrix' );
  9124. // GPU Precision
  9125. /**
  9126. * TSL object that represents the object's model view in `mediump` precision.
  9127. *
  9128. * @tsl
  9129. * @type {Node<mat4>}
  9130. */
  9131. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9132. // CPU Precision
  9133. /**
  9134. * TSL object that represents the object's model view in `highp` precision
  9135. * which is achieved by computing the matrix in JS and not in the shader.
  9136. *
  9137. * @tsl
  9138. * @type {Node<mat4>}
  9139. */
  9140. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9141. builder.context.isHighPrecisionModelViewMatrix = true;
  9142. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9143. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9144. } );
  9145. } ).once() )().toVar( 'highpModelViewMatrix' );
  9146. /**
  9147. * TSL object that represents the object's model normal view in `highp` precision
  9148. * which is achieved by computing the matrix in JS and not in the shader.
  9149. *
  9150. * @tsl
  9151. * @type {Node<mat3>}
  9152. */
  9153. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9154. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9155. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9156. if ( isHighPrecisionModelViewMatrix !== true ) {
  9157. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9158. }
  9159. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9160. } );
  9161. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9162. /**
  9163. * TSL object that represents the position attribute of the current rendered object.
  9164. *
  9165. * @tsl
  9166. * @type {AttributeNode<vec3>}
  9167. */
  9168. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9169. /**
  9170. * TSL object that represents the vertex position in local space of the current rendered object.
  9171. *
  9172. * @tsl
  9173. * @type {AttributeNode<vec3>}
  9174. */
  9175. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9176. /**
  9177. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9178. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9179. *
  9180. * @tsl
  9181. * @type {AttributeNode<vec3>}
  9182. */
  9183. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9184. /**
  9185. * TSL object that represents the vertex position in world space of the current rendered object.
  9186. *
  9187. * @tsl
  9188. * @type {VaryingNode<vec3>}
  9189. */
  9190. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9191. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9192. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9193. /**
  9194. * TSL object that represents the position world direction of the current rendered object.
  9195. *
  9196. * @tsl
  9197. * @type {Node<vec3>}
  9198. */
  9199. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9200. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9201. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9202. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9203. /**
  9204. * TSL object that represents the vertex position in view space of the current rendered object.
  9205. *
  9206. * @tsl
  9207. * @type {VaryingNode<vec3>}
  9208. */
  9209. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9210. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9211. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9212. /**
  9213. * TSL object that represents the position view direction of the current rendered object.
  9214. *
  9215. * @tsl
  9216. * @type {VaryingNode<vec3>}
  9217. */
  9218. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  9219. /**
  9220. * This node can be used to evaluate whether a primitive is front or back facing.
  9221. *
  9222. * @augments Node
  9223. */
  9224. class FrontFacingNode extends Node {
  9225. static get type() {
  9226. return 'FrontFacingNode';
  9227. }
  9228. /**
  9229. * Constructs a new front facing node.
  9230. */
  9231. constructor() {
  9232. super( 'bool' );
  9233. /**
  9234. * This flag can be used for type testing.
  9235. *
  9236. * @type {boolean}
  9237. * @readonly
  9238. * @default true
  9239. */
  9240. this.isFrontFacingNode = true;
  9241. }
  9242. generate( builder ) {
  9243. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9244. //
  9245. const { renderer, material } = builder;
  9246. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  9247. if ( material.side === BackSide ) {
  9248. return 'false';
  9249. }
  9250. }
  9251. return builder.getFrontFacing();
  9252. }
  9253. }
  9254. /**
  9255. * TSL object that represents whether a primitive is front or back facing
  9256. *
  9257. * @tsl
  9258. * @type {FrontFacingNode<bool>}
  9259. */
  9260. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9261. /**
  9262. * TSL object that represents the front facing status as a number instead of a bool.
  9263. * `1` means front facing, `-1` means back facing.
  9264. *
  9265. * @tsl
  9266. * @type {Node<float>}
  9267. */
  9268. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9269. /**
  9270. * Converts a direction vector to a face direction vector based on the material's side.
  9271. *
  9272. * If the material is set to `BackSide`, the direction is inverted.
  9273. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9274. *
  9275. * @tsl
  9276. * @param {Node<vec3>} direction - The direction vector to convert.
  9277. * @returns {Node<vec3>} The converted direction vector.
  9278. */
  9279. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9280. const side = material.side;
  9281. if ( side === BackSide ) {
  9282. direction = direction.mul( -1 );
  9283. } else if ( side === DoubleSide ) {
  9284. direction = direction.mul( faceDirection );
  9285. }
  9286. return direction;
  9287. } );
  9288. /**
  9289. * TSL object that represents the normal attribute of the current rendered object in local space.
  9290. *
  9291. * @tsl
  9292. * @type {Node<vec3>}
  9293. */
  9294. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9295. /**
  9296. * TSL object that represents the vertex normal of the current rendered object in local space.
  9297. *
  9298. * @tsl
  9299. * @type {Node<vec3>}
  9300. */
  9301. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9302. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9303. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  9304. return vec3( 0, 1, 0 );
  9305. }
  9306. return normalGeometry;
  9307. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9308. /**
  9309. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9310. *
  9311. * @tsl
  9312. * @type {Node<vec3>}
  9313. */
  9314. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9315. /**
  9316. * TSL object that represents the vertex normal of the current rendered object in view space.
  9317. *
  9318. * @tsl
  9319. * @type {Node<vec3>}
  9320. */
  9321. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9322. let node;
  9323. if ( builder.material.flatShading === true ) {
  9324. node = normalFlat;
  9325. } else {
  9326. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9327. }
  9328. return node;
  9329. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9330. /**
  9331. * TSL object that represents the vertex normal of the current rendered object in world space.
  9332. *
  9333. * @tsl
  9334. * @type {Node<vec3>}
  9335. */
  9336. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9337. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9338. if ( builder.material.flatShading !== true ) {
  9339. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9340. }
  9341. return normal.normalize().toVar( 'normalWorldGeometry' );
  9342. }, 'vec3' ).once() )();
  9343. /**
  9344. * TSL object that represents the vertex normal of the current rendered object in view space.
  9345. *
  9346. * @tsl
  9347. * @type {Node<vec3>}
  9348. */
  9349. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9350. let node;
  9351. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9352. node = normalViewGeometry;
  9353. if ( material.flatShading !== true ) {
  9354. node = directionToFaceDirection( node );
  9355. }
  9356. } else {
  9357. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9358. node = context.setupNormal().context( { getUV: null } );
  9359. }
  9360. return node;
  9361. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9362. /**
  9363. * TSL object that represents the vertex normal of the current rendered object in world space.
  9364. *
  9365. * @tsl
  9366. * @type {Node<vec3>}
  9367. */
  9368. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9369. /**
  9370. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9371. *
  9372. * @tsl
  9373. * @type {Node<vec3>}
  9374. */
  9375. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9376. let node;
  9377. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9378. node = normalView;
  9379. } else {
  9380. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9381. node = context.setupClearcoatNormal().context( { getUV: null } );
  9382. }
  9383. return node;
  9384. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9385. /**
  9386. * Transforms the normal with the given matrix.
  9387. *
  9388. * @tsl
  9389. * @function
  9390. * @param {Node<vec3>} normal - The normal.
  9391. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9392. * @return {Node<vec3>} The transformed normal.
  9393. */
  9394. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9395. const m = mat3( matrix );
  9396. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9397. return m.mul( transformedNormal ).xyz;
  9398. } );
  9399. /**
  9400. * Transforms the given normal from local to view space.
  9401. *
  9402. * @tsl
  9403. * @function
  9404. * @param {Node<vec3>} normal - The normal.
  9405. * @param {NodeBuilder} builder - The current node builder.
  9406. * @return {Node<vec3>} The transformed normal.
  9407. */
  9408. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9409. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9410. if ( modelNormalViewMatrix !== null ) {
  9411. return modelNormalViewMatrix.transformDirection( normal );
  9412. }
  9413. //
  9414. const transformedNormal = modelNormalMatrix.mul( normal );
  9415. return cameraViewMatrix.transformDirection( transformedNormal );
  9416. } );
  9417. // Deprecated
  9418. /**
  9419. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9420. *
  9421. * @tsl
  9422. * @type {Node<vec3>}
  9423. * @deprecated since r178. Use `normalView` instead.
  9424. */
  9425. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9426. console.warn( 'THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9427. return normalView;
  9428. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9429. /**
  9430. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9431. *
  9432. * @tsl
  9433. * @type {Node<vec3>}
  9434. * @deprecated since r178. Use `normalWorld` instead.
  9435. */
  9436. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9437. console.warn( 'THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9438. return normalWorld;
  9439. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9440. /**
  9441. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9442. *
  9443. * @tsl
  9444. * @type {Node<vec3>}
  9445. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9446. */
  9447. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9448. console.warn( 'THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9449. return clearcoatNormalView;
  9450. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9451. const _e1$1 = /*@__PURE__*/ new Euler();
  9452. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9453. /**
  9454. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9455. *
  9456. * @tsl
  9457. * @type {UniformNode<float>}
  9458. */
  9459. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9460. /**
  9461. * TSL object that represents the intensity of environment maps of PBR materials.
  9462. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9463. *
  9464. * @tsl
  9465. * @type {Node<float>}
  9466. */
  9467. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9468. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9469. } );
  9470. /**
  9471. * TSL object that represents the rotation of environment maps.
  9472. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9473. * rotation of `scene.environment` instead.
  9474. *
  9475. * @tsl
  9476. * @type {Node<mat4>}
  9477. */
  9478. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9479. return frame.material;
  9480. } ).onObjectUpdate( function ( { material, scene } ) {
  9481. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9482. if ( rotation ) {
  9483. _e1$1.copy( rotation );
  9484. _m1$1.makeRotationFromEuler( _e1$1 );
  9485. } else {
  9486. _m1$1.identity();
  9487. }
  9488. return _m1$1;
  9489. } );
  9490. /**
  9491. * The reflect vector in view space.
  9492. *
  9493. * @tsl
  9494. * @type {Node<vec3>}
  9495. */
  9496. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9497. /**
  9498. * The refract vector in view space.
  9499. *
  9500. * @tsl
  9501. * @type {Node<vec3>}
  9502. */
  9503. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  9504. /**
  9505. * Used for sampling cube maps when using cube reflection mapping.
  9506. *
  9507. * @tsl
  9508. * @type {Node<vec3>}
  9509. */
  9510. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9511. /**
  9512. * Used for sampling cube maps when using cube refraction mapping.
  9513. *
  9514. * @tsl
  9515. * @type {Node<vec3>}
  9516. */
  9517. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9518. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  9519. /**
  9520. * This type of uniform node represents a cube texture.
  9521. *
  9522. * @augments TextureNode
  9523. */
  9524. class CubeTextureNode extends TextureNode {
  9525. static get type() {
  9526. return 'CubeTextureNode';
  9527. }
  9528. /**
  9529. * Constructs a new cube texture node.
  9530. *
  9531. * @param {CubeTexture} value - The cube texture.
  9532. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9533. * @param {?Node<int>} [levelNode=null] - The level node.
  9534. * @param {?Node<float>} [biasNode=null] - The bias node.
  9535. */
  9536. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  9537. super( value, uvNode, levelNode, biasNode );
  9538. /**
  9539. * This flag can be used for type testing.
  9540. *
  9541. * @type {boolean}
  9542. * @readonly
  9543. * @default true
  9544. */
  9545. this.isCubeTextureNode = true;
  9546. }
  9547. /**
  9548. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  9549. *
  9550. * @param {NodeBuilder} builder - The current node builder.
  9551. * @return {string} The input type.
  9552. */
  9553. getInputType( /*builder*/ ) {
  9554. return 'cubeTexture';
  9555. }
  9556. /**
  9557. * Returns a default uvs based on the mapping type of the cube texture.
  9558. *
  9559. * @return {Node<vec3>} The default uv attribute.
  9560. */
  9561. getDefaultUV() {
  9562. const texture = this.value;
  9563. if ( texture.mapping === CubeReflectionMapping ) {
  9564. return reflectVector;
  9565. } else if ( texture.mapping === CubeRefractionMapping ) {
  9566. return refractVector;
  9567. } else {
  9568. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  9569. return vec3( 0, 0, 0 );
  9570. }
  9571. }
  9572. /**
  9573. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  9574. * for cube textures. The uv transformation matrix is not applied to cube textures.
  9575. *
  9576. * @param {boolean} value - The update toggle.
  9577. */
  9578. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  9579. /**
  9580. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  9581. * to modify the uv node for correct sampling.
  9582. *
  9583. * @param {NodeBuilder} builder - The current node builder.
  9584. * @param {Node} uvNode - The uv node to setup.
  9585. * @return {Node} The updated uv node.
  9586. */
  9587. setupUV( builder, uvNode ) {
  9588. const texture = this.value;
  9589. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  9590. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9591. }
  9592. return materialEnvRotation.mul( uvNode );
  9593. }
  9594. /**
  9595. * Generates the uv code snippet.
  9596. *
  9597. * @param {NodeBuilder} builder - The current node builder.
  9598. * @param {Node} cubeUV - The uv node to generate code for.
  9599. * @return {string} The generated code snippet.
  9600. */
  9601. generateUV( builder, cubeUV ) {
  9602. return cubeUV.build( builder, 'vec3' );
  9603. }
  9604. }
  9605. /**
  9606. * TSL function for creating a cube texture node.
  9607. *
  9608. * @tsl
  9609. * @function
  9610. * @param {CubeTexture} value - The cube texture.
  9611. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9612. * @param {?Node<int>} [levelNode=null] - The level node.
  9613. * @param {?Node<float>} [biasNode=null] - The bias node.
  9614. * @returns {CubeTextureNode}
  9615. */
  9616. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  9617. /**
  9618. * TSL function for creating a cube texture uniform node.
  9619. *
  9620. * @tsl
  9621. * @function
  9622. * @param {?CubeTexture|CubeTextureNode} [value=EmptyTexture] - The cube texture.
  9623. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9624. * @param {?Node<int>} [levelNode=null] - The level node.
  9625. * @param {?Node<float>} [biasNode=null] - The bias node.
  9626. * @returns {CubeTextureNode}
  9627. */
  9628. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  9629. let textureNode;
  9630. if ( value && value.isCubeTextureNode === true ) {
  9631. textureNode = nodeObject( value.clone() );
  9632. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  9633. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9634. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9635. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9636. } else {
  9637. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  9638. }
  9639. return textureNode;
  9640. };
  9641. /**
  9642. * TSL function for creating a uniform cube texture node.
  9643. *
  9644. * @tsl
  9645. * @function
  9646. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  9647. * @returns {CubeTextureNode}
  9648. */
  9649. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  9650. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  9651. /**
  9652. * This class is only relevant if the referenced property is array-like.
  9653. * In this case, `ReferenceElementNode` allows to refer to a specific
  9654. * element inside the data structure via an index.
  9655. *
  9656. * @augments ArrayElementNode
  9657. */
  9658. class ReferenceElementNode extends ArrayElementNode {
  9659. static get type() {
  9660. return 'ReferenceElementNode';
  9661. }
  9662. /**
  9663. * Constructs a new reference element node.
  9664. *
  9665. * @param {?ReferenceNode} referenceNode - The reference node.
  9666. * @param {Node} indexNode - The index node that defines the element access.
  9667. */
  9668. constructor( referenceNode, indexNode ) {
  9669. super( referenceNode, indexNode );
  9670. /**
  9671. * Similar to {@link ReferenceNode#reference}, an additional
  9672. * property references to the current node.
  9673. *
  9674. * @type {?ReferenceNode}
  9675. * @default null
  9676. */
  9677. this.referenceNode = referenceNode;
  9678. /**
  9679. * This flag can be used for type testing.
  9680. *
  9681. * @type {boolean}
  9682. * @readonly
  9683. * @default true
  9684. */
  9685. this.isReferenceElementNode = true;
  9686. }
  9687. /**
  9688. * This method is overwritten since the node type is inferred from
  9689. * the uniform type of the reference node.
  9690. *
  9691. * @return {string} The node type.
  9692. */
  9693. getNodeType() {
  9694. return this.referenceNode.uniformType;
  9695. }
  9696. generate( builder ) {
  9697. const snippet = super.generate( builder );
  9698. const arrayType = this.referenceNode.getNodeType();
  9699. const elementType = this.getNodeType();
  9700. return builder.format( snippet, arrayType, elementType );
  9701. }
  9702. }
  9703. /**
  9704. * This type of node establishes a reference to a property of another object.
  9705. * In this way, the value of the node is automatically linked to the value of
  9706. * referenced object. Reference nodes internally represent the linked value
  9707. * as a uniform.
  9708. *
  9709. * @augments Node
  9710. */
  9711. class ReferenceNode extends Node {
  9712. static get type() {
  9713. return 'ReferenceNode';
  9714. }
  9715. /**
  9716. * Constructs a new reference node.
  9717. *
  9718. * @param {string} property - The name of the property the node refers to.
  9719. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  9720. * @param {?Object} [object=null] - The object the property belongs to.
  9721. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  9722. */
  9723. constructor( property, uniformType, object = null, count = null ) {
  9724. super();
  9725. /**
  9726. * The name of the property the node refers to.
  9727. *
  9728. * @type {string}
  9729. */
  9730. this.property = property;
  9731. /**
  9732. * The uniform type that should be used to represent the property value.
  9733. *
  9734. * @type {string}
  9735. */
  9736. this.uniformType = uniformType;
  9737. /**
  9738. * The object the property belongs to.
  9739. *
  9740. * @type {?Object}
  9741. * @default null
  9742. */
  9743. this.object = object;
  9744. /**
  9745. * When the linked property is an array, this parameter defines its length.
  9746. *
  9747. * @type {?number}
  9748. * @default null
  9749. */
  9750. this.count = count;
  9751. /**
  9752. * The property name might have dots so nested properties can be referred.
  9753. * The hierarchy of the names is stored inside this array.
  9754. *
  9755. * @type {Array<string>}
  9756. */
  9757. this.properties = property.split( '.' );
  9758. /**
  9759. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  9760. * since the final reference might be updated from calling code.
  9761. *
  9762. * @type {?Object}
  9763. * @default null
  9764. */
  9765. this.reference = object;
  9766. /**
  9767. * The uniform node that holds the value of the reference node.
  9768. *
  9769. * @type {UniformNode}
  9770. * @default null
  9771. */
  9772. this.node = null;
  9773. /**
  9774. * The uniform group of the internal uniform.
  9775. *
  9776. * @type {UniformGroupNode}
  9777. * @default null
  9778. */
  9779. this.group = null;
  9780. /**
  9781. * An optional label of the internal uniform node.
  9782. *
  9783. * @type {?string}
  9784. * @default null
  9785. */
  9786. this.name = null;
  9787. /**
  9788. * Overwritten since reference nodes are updated per object.
  9789. *
  9790. * @type {string}
  9791. * @default 'object'
  9792. */
  9793. this.updateType = NodeUpdateType.OBJECT;
  9794. }
  9795. /**
  9796. * When the referred property is array-like, this method can be used
  9797. * to access elements via an index node.
  9798. *
  9799. * @param {IndexNode} indexNode - indexNode.
  9800. * @return {ReferenceElementNode} A reference to an element.
  9801. */
  9802. element( indexNode ) {
  9803. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9804. }
  9805. /**
  9806. * Sets the uniform group for this reference node.
  9807. *
  9808. * @param {UniformGroupNode} group - The uniform group to set.
  9809. * @return {ReferenceNode} A reference to this node.
  9810. */
  9811. setGroup( group ) {
  9812. this.group = group;
  9813. return this;
  9814. }
  9815. /**
  9816. * Sets the name for the internal uniform.
  9817. *
  9818. * @param {string} name - The label to set.
  9819. * @return {ReferenceNode} A reference to this node.
  9820. */
  9821. setName( name ) {
  9822. this.name = name;
  9823. return this;
  9824. }
  9825. /**
  9826. * Sets the label for the internal uniform.
  9827. *
  9828. * @deprecated
  9829. * @param {string} name - The label to set.
  9830. * @return {ReferenceNode} A reference to this node.
  9831. */
  9832. label( name ) {
  9833. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  9834. return this.setName( name );
  9835. }
  9836. /**
  9837. * Sets the node type which automatically defines the internal
  9838. * uniform type.
  9839. *
  9840. * @param {string} uniformType - The type to set.
  9841. */
  9842. setNodeType( uniformType ) {
  9843. let node = null;
  9844. if ( this.count !== null ) {
  9845. node = buffer( null, uniformType, this.count );
  9846. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9847. node = uniformArray( null, uniformType );
  9848. } else if ( uniformType === 'texture' ) {
  9849. node = texture( null );
  9850. } else if ( uniformType === 'cubeTexture' ) {
  9851. node = cubeTexture( null );
  9852. } else {
  9853. node = uniform( null, uniformType );
  9854. }
  9855. if ( this.group !== null ) {
  9856. node.setGroup( this.group );
  9857. }
  9858. if ( this.name !== null ) node.setName( this.name );
  9859. this.node = node.getSelf();
  9860. }
  9861. /**
  9862. * This method is overwritten since the node type is inferred from
  9863. * the type of the reference node.
  9864. *
  9865. * @param {NodeBuilder} builder - The current node builder.
  9866. * @return {string} The node type.
  9867. */
  9868. getNodeType( builder ) {
  9869. if ( this.node === null ) {
  9870. this.updateReference( builder );
  9871. this.updateValue();
  9872. }
  9873. return this.node.getNodeType( builder );
  9874. }
  9875. /**
  9876. * Returns the property value from the given referred object.
  9877. *
  9878. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  9879. * @return {any} The value.
  9880. */
  9881. getValueFromReference( object = this.reference ) {
  9882. const { properties } = this;
  9883. let value = object[ properties[ 0 ] ];
  9884. for ( let i = 1; i < properties.length; i ++ ) {
  9885. value = value[ properties[ i ] ];
  9886. }
  9887. return value;
  9888. }
  9889. /**
  9890. * Allows to update the reference based on the given state. The state is only
  9891. * evaluated {@link ReferenceNode#object} is not set.
  9892. *
  9893. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9894. * @return {Object} The updated reference.
  9895. */
  9896. updateReference( state ) {
  9897. this.reference = this.object !== null ? this.object : state.object;
  9898. return this.reference;
  9899. }
  9900. /**
  9901. * The output of the reference node is the internal uniform node.
  9902. *
  9903. * @param {NodeBuilder} builder - The current node builder.
  9904. * @return {UniformNode} The output node.
  9905. */
  9906. setup( /* builder */ ) {
  9907. this.updateValue();
  9908. return this.node;
  9909. }
  9910. /**
  9911. * Overwritten to update the internal uniform value.
  9912. *
  9913. * @param {NodeFrame} frame - A reference to the current node frame.
  9914. */
  9915. update( /*frame*/ ) {
  9916. this.updateValue();
  9917. }
  9918. /**
  9919. * Retrieves the value from the referred object property and uses it
  9920. * to updated the internal uniform.
  9921. */
  9922. updateValue() {
  9923. if ( this.node === null ) this.setNodeType( this.uniformType );
  9924. const value = this.getValueFromReference();
  9925. if ( Array.isArray( value ) ) {
  9926. this.node.array = value;
  9927. } else {
  9928. this.node.value = value;
  9929. }
  9930. }
  9931. }
  9932. /**
  9933. * TSL function for creating a reference node.
  9934. *
  9935. * @tsl
  9936. * @function
  9937. * @param {string} name - The name of the property the node refers to.
  9938. * @param {string} type - The uniform type that should be used to represent the property value.
  9939. * @param {?Object} [object] - The object the property belongs to.
  9940. * @returns {ReferenceNode}
  9941. */
  9942. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9943. /**
  9944. * TSL function for creating a reference node. Use this function if you want need a reference
  9945. * to an array-like property that should be represented as a uniform buffer.
  9946. *
  9947. * @tsl
  9948. * @function
  9949. * @param {string} name - The name of the property the node refers to.
  9950. * @param {string} type - The uniform type that should be used to represent the property value.
  9951. * @param {number} count - The number of value inside the array-like object.
  9952. * @param {Object} object - An array-like object the property belongs to.
  9953. * @returns {ReferenceNode}
  9954. */
  9955. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9956. /**
  9957. * This node is a special type of reference node which is intended
  9958. * for linking material properties with node values.
  9959. * ```js
  9960. * const opacityNode = materialReference( 'opacity', 'float', material );
  9961. * ```
  9962. * When changing `material.opacity`, the node value of `opacityNode` will
  9963. * automatically be updated.
  9964. *
  9965. * @augments ReferenceNode
  9966. */
  9967. class MaterialReferenceNode extends ReferenceNode {
  9968. static get type() {
  9969. return 'MaterialReferenceNode';
  9970. }
  9971. /**
  9972. * Constructs a new material reference node.
  9973. *
  9974. * @param {string} property - The name of the property the node refers to.
  9975. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9976. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9977. * the node refers to the material of the current rendered object.
  9978. */
  9979. constructor( property, inputType, material = null ) {
  9980. super( property, inputType, material );
  9981. /**
  9982. * The material the property belongs to. When no material is set,
  9983. * the node refers to the material of the current rendered object.
  9984. *
  9985. * @type {?Material}
  9986. * @default null
  9987. */
  9988. this.material = material;
  9989. /**
  9990. * This flag can be used for type testing.
  9991. *
  9992. * @type {boolean}
  9993. * @readonly
  9994. * @default true
  9995. */
  9996. this.isMaterialReferenceNode = true;
  9997. }
  9998. /**
  9999. * Updates the reference based on the given state. The state is only evaluated
  10000. * {@link MaterialReferenceNode#material} is not set.
  10001. *
  10002. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10003. * @return {Object} The updated reference.
  10004. */
  10005. updateReference( state ) {
  10006. this.reference = this.material !== null ? this.material : state.material;
  10007. return this.reference;
  10008. }
  10009. }
  10010. /**
  10011. * TSL function for creating a material reference node.
  10012. *
  10013. * @tsl
  10014. * @function
  10015. * @param {string} name - The name of the property the node refers to.
  10016. * @param {string} type - The uniform type that should be used to represent the property value.
  10017. * @param {?Material} [material=null] - The material the property belongs to.
  10018. * When no material is set, the node refers to the material of the current rendered object.
  10019. * @returns {MaterialReferenceNode}
  10020. */
  10021. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10022. // Normal Mapping Without Precomputed Tangents
  10023. // http://www.thetenthplanet.de/archives/1180
  10024. const uv = uv$1();
  10025. const q0 = positionView.dFdx();
  10026. const q1 = positionView.dFdy();
  10027. const st0 = uv.dFdx();
  10028. const st1 = uv.dFdy();
  10029. const N = normalView;
  10030. const q1perp = q1.cross( N );
  10031. const q0perp = N.cross( q0 );
  10032. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10033. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10034. const det = T.dot( T ).max( B.dot( B ) );
  10035. const scale = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10036. /**
  10037. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10038. * Useful for normal mapping without precomputed tangents.
  10039. *
  10040. * Reference: http://www.thetenthplanet.de/archives/1180
  10041. *
  10042. * @tsl
  10043. * @type {Node<vec3>}
  10044. */
  10045. const tangentViewFrame = /*@__PURE__*/ T.mul( scale ).toVar( 'tangentViewFrame' );
  10046. /**
  10047. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10048. * Complements the tangentViewFrame for constructing the tangent space basis.
  10049. *
  10050. * Reference: http://www.thetenthplanet.de/archives/1180
  10051. *
  10052. * @tsl
  10053. * @type {Node<vec3>}
  10054. */
  10055. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale ).toVar( 'bitangentViewFrame' );
  10056. /**
  10057. * TSL object that represents the tangent attribute of the current rendered object.
  10058. *
  10059. * @tsl
  10060. * @type {Node<vec4>}
  10061. */
  10062. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10063. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10064. builder.geometry.computeTangents();
  10065. }
  10066. return attribute( 'tangent', 'vec4' );
  10067. } )();
  10068. /**
  10069. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10070. *
  10071. * @tsl
  10072. * @type {Node<vec3>}
  10073. */
  10074. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10075. /**
  10076. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10077. *
  10078. * @tsl
  10079. * @type {Node<vec3>}
  10080. */
  10081. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10082. let node;
  10083. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10084. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10085. } else {
  10086. node = tangentViewFrame;
  10087. }
  10088. if ( material.flatShading !== true ) {
  10089. node = directionToFaceDirection( node );
  10090. }
  10091. return node;
  10092. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10093. /**
  10094. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10095. *
  10096. * @tsl
  10097. * @type {Node<vec3>}
  10098. */
  10099. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10100. /**
  10101. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10102. *
  10103. * @tsl
  10104. * @private
  10105. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10106. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10107. * @returns {Node<vec3>} The bitangent node.
  10108. */
  10109. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10110. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10111. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10112. bitangent = bitangent.toVarying( varyingName );
  10113. }
  10114. return bitangent;
  10115. } ).once( [ 'NORMAL' ] );
  10116. /**
  10117. * TSL object that represents the bitangent attribute of the current rendered object.
  10118. *
  10119. * @tsl
  10120. * @type {Node<vec3>}
  10121. */
  10122. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10123. /**
  10124. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10125. *
  10126. * @tsl
  10127. * @type {Node<vec3>}
  10128. */
  10129. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10130. /**
  10131. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10132. *
  10133. * @tsl
  10134. * @type {Node<vec3>}
  10135. */
  10136. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10137. let node;
  10138. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10139. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10140. } else {
  10141. node = bitangentViewFrame;
  10142. }
  10143. if ( material.flatShading !== true ) {
  10144. node = directionToFaceDirection( node );
  10145. }
  10146. return node;
  10147. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10148. /**
  10149. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10150. *
  10151. * @tsl
  10152. * @type {Node<vec3>}
  10153. */
  10154. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10155. /**
  10156. * TSL object that represents the TBN matrix in view space.
  10157. *
  10158. * @tsl
  10159. * @type {Node<mat3>}
  10160. */
  10161. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10162. /**
  10163. * TSL object that represents the parallax direction.
  10164. *
  10165. * @tsl
  10166. * @type {Node<mat3>}
  10167. */
  10168. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10169. /**
  10170. * TSL function for computing parallax uv coordinates.
  10171. *
  10172. * @tsl
  10173. * @function
  10174. * @param {Node<vec2>} uv - A uv node.
  10175. * @param {Node<vec2>} scale - A scale node.
  10176. * @returns {Node<vec2>} Parallax uv coordinates.
  10177. */
  10178. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10179. /**
  10180. * TSL function for computing bent normals.
  10181. *
  10182. * @tsl
  10183. * @function
  10184. * @returns {Node<vec3>} Bent normals.
  10185. */
  10186. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10187. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10188. let bentNormal = anisotropyB.cross( positionViewDirection );
  10189. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10190. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10191. return bentNormal;
  10192. } ).once() )();
  10193. /**
  10194. * This class can be used for applying normals maps to materials.
  10195. *
  10196. * ```js
  10197. * material.normalNode = normalMap( texture( normalTex ) );
  10198. * ```
  10199. *
  10200. * @augments TempNode
  10201. */
  10202. class NormalMapNode extends TempNode {
  10203. static get type() {
  10204. return 'NormalMapNode';
  10205. }
  10206. /**
  10207. * Constructs a new normal map node.
  10208. *
  10209. * @param {Node<vec3>} node - Represents the normal map data.
  10210. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10211. */
  10212. constructor( node, scaleNode = null ) {
  10213. super( 'vec3' );
  10214. /**
  10215. * Represents the normal map data.
  10216. *
  10217. * @type {Node<vec3>}
  10218. */
  10219. this.node = node;
  10220. /**
  10221. * Controls the intensity of the effect.
  10222. *
  10223. * @type {?Node<vec2>}
  10224. * @default null
  10225. */
  10226. this.scaleNode = scaleNode;
  10227. /**
  10228. * The normal map type.
  10229. *
  10230. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10231. * @default TangentSpaceNormalMap
  10232. */
  10233. this.normalMapType = TangentSpaceNormalMap;
  10234. }
  10235. setup( { material } ) {
  10236. const { normalMapType, scaleNode } = this;
  10237. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10238. if ( scaleNode !== null ) {
  10239. let scale = scaleNode;
  10240. if ( material.flatShading === true ) {
  10241. scale = directionToFaceDirection( scale );
  10242. }
  10243. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10244. }
  10245. let output = null;
  10246. if ( normalMapType === ObjectSpaceNormalMap ) {
  10247. output = transformNormalToView( normalMap );
  10248. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10249. output = TBNViewMatrix.mul( normalMap ).normalize();
  10250. } else {
  10251. console.error( `THREE.NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10252. output = normalView; // Fallback to default normal view
  10253. }
  10254. return output;
  10255. }
  10256. }
  10257. /**
  10258. * TSL function for creating a normal map node.
  10259. *
  10260. * @tsl
  10261. * @function
  10262. * @param {Node<vec3>} node - Represents the normal map data.
  10263. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10264. * @returns {NormalMapNode}
  10265. */
  10266. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10267. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10268. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10269. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10270. // It's used to preserve the same TextureNode instance
  10271. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10272. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10273. return vec2(
  10274. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10275. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10276. ).mul( bumpScale );
  10277. } );
  10278. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10279. const perturbNormalArb = Fn( ( inputs ) => {
  10280. const { surf_pos, surf_norm, dHdxy } = inputs;
  10281. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10282. const vSigmaX = surf_pos.dFdx().normalize();
  10283. const vSigmaY = surf_pos.dFdy().normalize();
  10284. const vN = surf_norm; // normalized
  10285. const R1 = vSigmaY.cross( vN );
  10286. const R2 = vN.cross( vSigmaX );
  10287. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10288. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10289. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10290. } );
  10291. /**
  10292. * This class can be used for applying bump maps to materials.
  10293. *
  10294. * ```js
  10295. * material.normalNode = bumpMap( texture( bumpTex ) );
  10296. * ```
  10297. *
  10298. * @augments TempNode
  10299. */
  10300. class BumpMapNode extends TempNode {
  10301. static get type() {
  10302. return 'BumpMapNode';
  10303. }
  10304. /**
  10305. * Constructs a new bump map node.
  10306. *
  10307. * @param {Node<float>} textureNode - Represents the bump map data.
  10308. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10309. */
  10310. constructor( textureNode, scaleNode = null ) {
  10311. super( 'vec3' );
  10312. /**
  10313. * Represents the bump map data.
  10314. *
  10315. * @type {Node<float>}
  10316. */
  10317. this.textureNode = textureNode;
  10318. /**
  10319. * Controls the intensity of the bump effect.
  10320. *
  10321. * @type {?Node<float>}
  10322. * @default null
  10323. */
  10324. this.scaleNode = scaleNode;
  10325. }
  10326. setup() {
  10327. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10328. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10329. return perturbNormalArb( {
  10330. surf_pos: positionView,
  10331. surf_norm: normalView,
  10332. dHdxy
  10333. } );
  10334. }
  10335. }
  10336. /**
  10337. * TSL function for creating a bump map node.
  10338. *
  10339. * @tsl
  10340. * @function
  10341. * @param {Node<float>} textureNode - Represents the bump map data.
  10342. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10343. * @returns {BumpMapNode}
  10344. */
  10345. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10346. const _propertyCache = new Map();
  10347. /**
  10348. * This class should simplify the node access to material properties.
  10349. * It internal uses reference nodes to make sure changes to material
  10350. * properties are automatically reflected to predefined TSL objects
  10351. * like e.g. `materialColor`.
  10352. *
  10353. * @augments Node
  10354. */
  10355. class MaterialNode extends Node {
  10356. static get type() {
  10357. return 'MaterialNode';
  10358. }
  10359. /**
  10360. * Constructs a new material node.
  10361. *
  10362. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10363. */
  10364. constructor( scope ) {
  10365. super();
  10366. /**
  10367. * The scope defines what material property is referred by the node.
  10368. *
  10369. * @type {string}
  10370. */
  10371. this.scope = scope;
  10372. }
  10373. /**
  10374. * Returns a cached reference node for the given property and type.
  10375. *
  10376. * @param {string} property - The name of the material property.
  10377. * @param {string} type - The uniform type of the property.
  10378. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10379. */
  10380. getCache( property, type ) {
  10381. let node = _propertyCache.get( property );
  10382. if ( node === undefined ) {
  10383. node = materialReference( property, type );
  10384. _propertyCache.set( property, node );
  10385. }
  10386. return node;
  10387. }
  10388. /**
  10389. * Returns a float-typed material reference node for the given property name.
  10390. *
  10391. * @param {string} property - The name of the material property.
  10392. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10393. */
  10394. getFloat( property ) {
  10395. return this.getCache( property, 'float' );
  10396. }
  10397. /**
  10398. * Returns a color-typed material reference node for the given property name.
  10399. *
  10400. * @param {string} property - The name of the material property.
  10401. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10402. */
  10403. getColor( property ) {
  10404. return this.getCache( property, 'color' );
  10405. }
  10406. /**
  10407. * Returns a texture-typed material reference node for the given property name.
  10408. *
  10409. * @param {string} property - The name of the material property.
  10410. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10411. */
  10412. getTexture( property ) {
  10413. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10414. }
  10415. /**
  10416. * The node setup is done depending on the selected scope. Multiple material properties
  10417. * might be grouped into a single node composition if they logically belong together.
  10418. *
  10419. * @param {NodeBuilder} builder - The current node builder.
  10420. * @return {Node} The node representing the selected scope.
  10421. */
  10422. setup( builder ) {
  10423. const material = builder.context.material;
  10424. const scope = this.scope;
  10425. let node = null;
  10426. if ( scope === MaterialNode.COLOR ) {
  10427. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10428. if ( material.map && material.map.isTexture === true ) {
  10429. node = colorNode.mul( this.getTexture( 'map' ) );
  10430. } else {
  10431. node = colorNode;
  10432. }
  10433. } else if ( scope === MaterialNode.OPACITY ) {
  10434. const opacityNode = this.getFloat( scope );
  10435. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10436. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10437. } else {
  10438. node = opacityNode;
  10439. }
  10440. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10441. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10442. node = this.getTexture( 'specular' ).r;
  10443. } else {
  10444. node = float( 1 );
  10445. }
  10446. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10447. const specularIntensityNode = this.getFloat( scope );
  10448. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10449. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10450. } else {
  10451. node = specularIntensityNode;
  10452. }
  10453. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10454. const specularColorNode = this.getColor( scope );
  10455. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10456. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10457. } else {
  10458. node = specularColorNode;
  10459. }
  10460. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10461. const roughnessNode = this.getFloat( scope );
  10462. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10463. node = roughnessNode.mul( this.getTexture( scope ).g );
  10464. } else {
  10465. node = roughnessNode;
  10466. }
  10467. } else if ( scope === MaterialNode.METALNESS ) {
  10468. const metalnessNode = this.getFloat( scope );
  10469. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10470. node = metalnessNode.mul( this.getTexture( scope ).b );
  10471. } else {
  10472. node = metalnessNode;
  10473. }
  10474. } else if ( scope === MaterialNode.EMISSIVE ) {
  10475. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10476. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10477. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10478. node = emissiveNode.mul( this.getTexture( scope ) );
  10479. } else {
  10480. node = emissiveNode;
  10481. }
  10482. } else if ( scope === MaterialNode.NORMAL ) {
  10483. if ( material.normalMap ) {
  10484. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10485. node.normalMapType = material.normalMapType;
  10486. } else if ( material.bumpMap ) {
  10487. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10488. } else {
  10489. node = normalView;
  10490. }
  10491. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10492. const clearcoatNode = this.getFloat( scope );
  10493. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10494. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10495. } else {
  10496. node = clearcoatNode;
  10497. }
  10498. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  10499. const clearcoatRoughnessNode = this.getFloat( scope );
  10500. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  10501. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  10502. } else {
  10503. node = clearcoatRoughnessNode;
  10504. }
  10505. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  10506. if ( material.clearcoatNormalMap ) {
  10507. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  10508. } else {
  10509. node = normalView;
  10510. }
  10511. } else if ( scope === MaterialNode.SHEEN ) {
  10512. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  10513. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  10514. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  10515. } else {
  10516. node = sheenNode;
  10517. }
  10518. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  10519. const sheenRoughnessNode = this.getFloat( scope );
  10520. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  10521. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  10522. } else {
  10523. node = sheenRoughnessNode;
  10524. }
  10525. node = node.clamp( 0.07, 1.0 );
  10526. } else if ( scope === MaterialNode.ANISOTROPY ) {
  10527. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  10528. const anisotropyPolar = this.getTexture( scope );
  10529. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  10530. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  10531. } else {
  10532. node = materialAnisotropyVector;
  10533. }
  10534. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  10535. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  10536. if ( material.iridescenceThicknessMap ) {
  10537. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  10538. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  10539. } else {
  10540. node = iridescenceThicknessMaximum;
  10541. }
  10542. } else if ( scope === MaterialNode.TRANSMISSION ) {
  10543. const transmissionNode = this.getFloat( scope );
  10544. if ( material.transmissionMap ) {
  10545. node = transmissionNode.mul( this.getTexture( scope ).r );
  10546. } else {
  10547. node = transmissionNode;
  10548. }
  10549. } else if ( scope === MaterialNode.THICKNESS ) {
  10550. const thicknessNode = this.getFloat( scope );
  10551. if ( material.thicknessMap ) {
  10552. node = thicknessNode.mul( this.getTexture( scope ).g );
  10553. } else {
  10554. node = thicknessNode;
  10555. }
  10556. } else if ( scope === MaterialNode.IOR ) {
  10557. node = this.getFloat( scope );
  10558. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  10559. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  10560. } else if ( scope === MaterialNode.AO ) {
  10561. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  10562. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  10563. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  10564. } else {
  10565. const outputType = this.getNodeType( builder );
  10566. node = this.getCache( scope, outputType );
  10567. }
  10568. return node;
  10569. }
  10570. }
  10571. MaterialNode.ALPHA_TEST = 'alphaTest';
  10572. MaterialNode.COLOR = 'color';
  10573. MaterialNode.OPACITY = 'opacity';
  10574. MaterialNode.SHININESS = 'shininess';
  10575. MaterialNode.SPECULAR = 'specular';
  10576. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  10577. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  10578. MaterialNode.SPECULAR_COLOR = 'specularColor';
  10579. MaterialNode.REFLECTIVITY = 'reflectivity';
  10580. MaterialNode.ROUGHNESS = 'roughness';
  10581. MaterialNode.METALNESS = 'metalness';
  10582. MaterialNode.NORMAL = 'normal';
  10583. MaterialNode.CLEARCOAT = 'clearcoat';
  10584. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  10585. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  10586. MaterialNode.EMISSIVE = 'emissive';
  10587. MaterialNode.ROTATION = 'rotation';
  10588. MaterialNode.SHEEN = 'sheen';
  10589. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  10590. MaterialNode.ANISOTROPY = 'anisotropy';
  10591. MaterialNode.IRIDESCENCE = 'iridescence';
  10592. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  10593. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  10594. MaterialNode.IOR = 'ior';
  10595. MaterialNode.TRANSMISSION = 'transmission';
  10596. MaterialNode.THICKNESS = 'thickness';
  10597. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  10598. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  10599. MaterialNode.LINE_SCALE = 'scale';
  10600. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  10601. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  10602. MaterialNode.LINE_WIDTH = 'linewidth';
  10603. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  10604. MaterialNode.POINT_SIZE = 'size';
  10605. MaterialNode.DISPERSION = 'dispersion';
  10606. MaterialNode.LIGHT_MAP = 'light';
  10607. MaterialNode.AO = 'ao';
  10608. /**
  10609. * TSL object that represents alpha test of the current material.
  10610. *
  10611. * @tsl
  10612. * @type {Node<float>}
  10613. */
  10614. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  10615. /**
  10616. * TSL object that represents the diffuse color of the current material.
  10617. * The value is composed via `color` * `map`.
  10618. *
  10619. * @tsl
  10620. * @type {Node<vec3>}
  10621. */
  10622. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  10623. /**
  10624. * TSL object that represents the shininess of the current material.
  10625. *
  10626. * @tsl
  10627. * @type {Node<float>}
  10628. */
  10629. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  10630. /**
  10631. * TSL object that represents the emissive color of the current material.
  10632. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  10633. *
  10634. * @tsl
  10635. * @type {Node<vec3>}
  10636. */
  10637. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  10638. /**
  10639. * TSL object that represents the opacity of the current material.
  10640. * The value is composed via `opacity` * `alphaMap`.
  10641. *
  10642. * @tsl
  10643. * @type {Node<float>}
  10644. */
  10645. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  10646. /**
  10647. * TSL object that represents the specular of the current material.
  10648. *
  10649. * @tsl
  10650. * @type {Node<vec3>}
  10651. */
  10652. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  10653. /**
  10654. * TSL object that represents the specular intensity of the current material.
  10655. * The value is composed via `specularIntensity` * `specularMap.a`.
  10656. *
  10657. * @tsl
  10658. * @type {Node<float>}
  10659. */
  10660. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  10661. /**
  10662. * TSL object that represents the specular color of the current material.
  10663. * The value is composed via `specularColor` * `specularMap.rgb`.
  10664. *
  10665. * @tsl
  10666. * @type {Node<vec3>}
  10667. */
  10668. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  10669. /**
  10670. * TSL object that represents the specular strength of the current material.
  10671. * The value is composed via `specularMap.r`.
  10672. *
  10673. * @tsl
  10674. * @type {Node<float>}
  10675. */
  10676. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  10677. /**
  10678. * TSL object that represents the reflectivity of the current material.
  10679. *
  10680. * @tsl
  10681. * @type {Node<float>}
  10682. */
  10683. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  10684. /**
  10685. * TSL object that represents the roughness of the current material.
  10686. * The value is composed via `roughness` * `roughnessMap.g`.
  10687. *
  10688. * @tsl
  10689. * @type {Node<float>}
  10690. */
  10691. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  10692. /**
  10693. * TSL object that represents the metalness of the current material.
  10694. * The value is composed via `metalness` * `metalnessMap.b`.
  10695. *
  10696. * @tsl
  10697. * @type {Node<float>}
  10698. */
  10699. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  10700. /**
  10701. * TSL object that represents the normal of the current material.
  10702. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  10703. *
  10704. * @tsl
  10705. * @type {Node<vec3>}
  10706. */
  10707. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  10708. /**
  10709. * TSL object that represents the clearcoat of the current material.
  10710. * The value is composed via `clearcoat` * `clearcoatMap.r`
  10711. *
  10712. * @tsl
  10713. * @type {Node<float>}
  10714. */
  10715. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  10716. /**
  10717. * TSL object that represents the clearcoat roughness of the current material.
  10718. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  10719. *
  10720. * @tsl
  10721. * @type {Node<float>}
  10722. */
  10723. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  10724. /**
  10725. * TSL object that represents the clearcoat normal of the current material.
  10726. * The value will be either `clearcoatNormalMap` or `normalView`.
  10727. *
  10728. * @tsl
  10729. * @type {Node<vec3>}
  10730. */
  10731. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  10732. /**
  10733. * TSL object that represents the rotation of the current sprite material.
  10734. *
  10735. * @tsl
  10736. * @type {Node<float>}
  10737. */
  10738. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  10739. /**
  10740. * TSL object that represents the sheen color of the current material.
  10741. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  10742. *
  10743. * @tsl
  10744. * @type {Node<vec3>}
  10745. */
  10746. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  10747. /**
  10748. * TSL object that represents the sheen roughness of the current material.
  10749. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  10750. *
  10751. * @tsl
  10752. * @type {Node<float>}
  10753. */
  10754. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  10755. /**
  10756. * TSL object that represents the anisotropy of the current material.
  10757. *
  10758. * @tsl
  10759. * @type {Node<vec2>}
  10760. */
  10761. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  10762. /**
  10763. * TSL object that represents the iridescence of the current material.
  10764. *
  10765. * @tsl
  10766. * @type {Node<float>}
  10767. */
  10768. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  10769. /**
  10770. * TSL object that represents the iridescence IOR of the current material.
  10771. *
  10772. * @tsl
  10773. * @type {Node<float>}
  10774. */
  10775. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  10776. /**
  10777. * TSL object that represents the iridescence thickness of the current material.
  10778. *
  10779. * @tsl
  10780. * @type {Node<float>}
  10781. */
  10782. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  10783. /**
  10784. * TSL object that represents the transmission of the current material.
  10785. * The value is composed via `transmission` * `transmissionMap.r`.
  10786. *
  10787. * @tsl
  10788. * @type {Node<float>}
  10789. */
  10790. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  10791. /**
  10792. * TSL object that represents the thickness of the current material.
  10793. * The value is composed via `thickness` * `thicknessMap.g`.
  10794. *
  10795. * @tsl
  10796. * @type {Node<float>}
  10797. */
  10798. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  10799. /**
  10800. * TSL object that represents the IOR of the current material.
  10801. *
  10802. * @tsl
  10803. * @type {Node<float>}
  10804. */
  10805. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10806. /**
  10807. * TSL object that represents the attenuation distance of the current material.
  10808. *
  10809. * @tsl
  10810. * @type {Node<float>}
  10811. */
  10812. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10813. /**
  10814. * TSL object that represents the attenuation color of the current material.
  10815. *
  10816. * @tsl
  10817. * @type {Node<vec3>}
  10818. */
  10819. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10820. /**
  10821. * TSL object that represents the scale of the current dashed line material.
  10822. *
  10823. * @tsl
  10824. * @type {Node<float>}
  10825. */
  10826. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10827. /**
  10828. * TSL object that represents the dash size of the current dashed line material.
  10829. *
  10830. * @tsl
  10831. * @type {Node<float>}
  10832. */
  10833. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10834. /**
  10835. * TSL object that represents the gap size of the current dashed line material.
  10836. *
  10837. * @tsl
  10838. * @type {Node<float>}
  10839. */
  10840. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10841. /**
  10842. * TSL object that represents the line width of the current line material.
  10843. *
  10844. * @tsl
  10845. * @type {Node<float>}
  10846. */
  10847. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10848. /**
  10849. * TSL object that represents the dash offset of the current line material.
  10850. *
  10851. * @tsl
  10852. * @type {Node<float>}
  10853. */
  10854. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  10855. /**
  10856. * TSL object that represents the point size of the current points material.
  10857. *
  10858. * @tsl
  10859. * @type {Node<float>}
  10860. */
  10861. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  10862. /**
  10863. * TSL object that represents the dispersion of the current material.
  10864. *
  10865. * @tsl
  10866. * @type {Node<float>}
  10867. */
  10868. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  10869. /**
  10870. * TSL object that represents the light map of the current material.
  10871. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  10872. *
  10873. * @tsl
  10874. * @type {Node<vec3>}
  10875. */
  10876. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  10877. /**
  10878. * TSL object that represents the ambient occlusion map of the current material.
  10879. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  10880. *
  10881. * @tsl
  10882. * @type {Node<float>}
  10883. */
  10884. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  10885. /**
  10886. * TSL object that represents the anisotropy vector of the current material.
  10887. *
  10888. * @tsl
  10889. * @type {Node<vec2>}
  10890. */
  10891. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  10892. return frame.material;
  10893. } ).onRenderUpdate( function ( { material } ) {
  10894. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  10895. } );
  10896. /**
  10897. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  10898. *
  10899. * @tsl
  10900. * @type {VaryingNode<vec4>}
  10901. */
  10902. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10903. return builder.context.setupModelViewProjection();
  10904. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10905. /**
  10906. * This class represents shader indices of different types. The following predefined node
  10907. * objects cover frequent use cases:
  10908. *
  10909. * - `vertexIndex`: The index of a vertex within a mesh.
  10910. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10911. * - `drawIndex`: The index of a draw call.
  10912. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10913. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10914. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10915. *
  10916. * @augments Node
  10917. */
  10918. class IndexNode extends Node {
  10919. static get type() {
  10920. return 'IndexNode';
  10921. }
  10922. /**
  10923. * Constructs a new index node.
  10924. *
  10925. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10926. */
  10927. constructor( scope ) {
  10928. super( 'uint' );
  10929. /**
  10930. * The scope of the index node.
  10931. *
  10932. * @type {string}
  10933. */
  10934. this.scope = scope;
  10935. /**
  10936. * This flag can be used for type testing.
  10937. *
  10938. * @type {boolean}
  10939. * @readonly
  10940. * @default true
  10941. */
  10942. this.isIndexNode = true;
  10943. }
  10944. generate( builder ) {
  10945. const nodeType = this.getNodeType( builder );
  10946. const scope = this.scope;
  10947. let propertyName;
  10948. if ( scope === IndexNode.VERTEX ) {
  10949. propertyName = builder.getVertexIndex();
  10950. } else if ( scope === IndexNode.INSTANCE ) {
  10951. propertyName = builder.getInstanceIndex();
  10952. } else if ( scope === IndexNode.DRAW ) {
  10953. propertyName = builder.getDrawIndex();
  10954. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10955. propertyName = builder.getInvocationLocalIndex();
  10956. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10957. propertyName = builder.getInvocationSubgroupIndex();
  10958. } else if ( scope === IndexNode.SUBGROUP ) {
  10959. propertyName = builder.getSubgroupIndex();
  10960. } else {
  10961. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10962. }
  10963. let output;
  10964. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10965. output = propertyName;
  10966. } else {
  10967. const nodeVarying = varying( this );
  10968. output = nodeVarying.build( builder, nodeType );
  10969. }
  10970. return output;
  10971. }
  10972. }
  10973. IndexNode.VERTEX = 'vertex';
  10974. IndexNode.INSTANCE = 'instance';
  10975. IndexNode.SUBGROUP = 'subgroup';
  10976. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10977. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10978. IndexNode.DRAW = 'draw';
  10979. /**
  10980. * TSL object that represents the index of a vertex within a mesh.
  10981. *
  10982. * @tsl
  10983. * @type {IndexNode}
  10984. */
  10985. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10986. /**
  10987. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10988. *
  10989. * @tsl
  10990. * @type {IndexNode}
  10991. */
  10992. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  10993. /**
  10994. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  10995. *
  10996. * @tsl
  10997. * @type {IndexNode}
  10998. */
  10999. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11000. /**
  11001. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11002. *
  11003. * @tsl
  11004. * @type {IndexNode}
  11005. */
  11006. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11007. /**
  11008. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11009. *
  11010. * @tsl
  11011. * @type {IndexNode}
  11012. */
  11013. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11014. /**
  11015. * TSL object that represents the index of a draw call.
  11016. *
  11017. * @tsl
  11018. * @type {IndexNode}
  11019. */
  11020. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11021. /**
  11022. * This node implements the vertex shader logic which is required
  11023. * when rendering 3D objects via instancing. The code makes sure
  11024. * vertex positions, normals and colors can be modified via instanced
  11025. * data.
  11026. *
  11027. * @augments Node
  11028. */
  11029. class InstanceNode extends Node {
  11030. static get type() {
  11031. return 'InstanceNode';
  11032. }
  11033. /**
  11034. * Constructs a new instance node.
  11035. *
  11036. * @param {number} count - The number of instances.
  11037. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11038. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11039. */
  11040. constructor( count, instanceMatrix, instanceColor = null ) {
  11041. super( 'void' );
  11042. /**
  11043. * The number of instances.
  11044. *
  11045. * @type {number}
  11046. */
  11047. this.count = count;
  11048. /**
  11049. * Instanced buffer attribute representing the transformation of instances.
  11050. *
  11051. * @type {InstancedBufferAttribute}
  11052. */
  11053. this.instanceMatrix = instanceMatrix;
  11054. /**
  11055. * Instanced buffer attribute representing the color of instances.
  11056. *
  11057. * @type {InstancedBufferAttribute}
  11058. */
  11059. this.instanceColor = instanceColor;
  11060. /**
  11061. * The node that represents the instance matrix data.
  11062. *
  11063. * @type {?Node}
  11064. */
  11065. this.instanceMatrixNode = null;
  11066. /**
  11067. * The node that represents the instance color data.
  11068. *
  11069. * @type {?Node}
  11070. * @default null
  11071. */
  11072. this.instanceColorNode = null;
  11073. /**
  11074. * The update type is set to `frame` since an update
  11075. * of instanced buffer data must be checked per frame.
  11076. *
  11077. * @type {string}
  11078. * @default 'frame'
  11079. */
  11080. this.updateType = NodeUpdateType.FRAME;
  11081. /**
  11082. * A reference to a buffer that is used by `instanceMatrixNode`.
  11083. *
  11084. * @type {?InstancedInterleavedBuffer}
  11085. */
  11086. this.buffer = null;
  11087. /**
  11088. * A reference to a buffer that is used by `instanceColorNode`.
  11089. *
  11090. * @type {?InstancedBufferAttribute}
  11091. */
  11092. this.bufferColor = null;
  11093. }
  11094. /**
  11095. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11096. * to predefined node variables for accumulation. That follows the same patterns
  11097. * like with morph and skinning nodes.
  11098. *
  11099. * @param {NodeBuilder} builder - The current node builder.
  11100. */
  11101. setup( builder ) {
  11102. const { instanceMatrix, instanceColor } = this;
  11103. const { count } = instanceMatrix;
  11104. let { instanceMatrixNode, instanceColorNode } = this;
  11105. if ( instanceMatrixNode === null ) {
  11106. // 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.
  11107. if ( count <= 1000 ) {
  11108. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11109. } else {
  11110. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11111. this.buffer = buffer;
  11112. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11113. const instanceBuffers = [
  11114. // F.Signature -> bufferAttribute( array, type, stride, offset )
  11115. bufferFn( buffer, 'vec4', 16, 0 ),
  11116. bufferFn( buffer, 'vec4', 16, 4 ),
  11117. bufferFn( buffer, 'vec4', 16, 8 ),
  11118. bufferFn( buffer, 'vec4', 16, 12 )
  11119. ];
  11120. instanceMatrixNode = mat4( ...instanceBuffers );
  11121. }
  11122. this.instanceMatrixNode = instanceMatrixNode;
  11123. }
  11124. if ( instanceColor && instanceColorNode === null ) {
  11125. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11126. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11127. this.bufferColor = buffer;
  11128. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11129. this.instanceColorNode = instanceColorNode;
  11130. }
  11131. // POSITION
  11132. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11133. positionLocal.assign( instancePosition );
  11134. // NORMAL
  11135. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11136. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11137. // ASSIGNS
  11138. normalLocal.assign( instanceNormal );
  11139. }
  11140. // COLOR
  11141. if ( this.instanceColorNode !== null ) {
  11142. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11143. }
  11144. }
  11145. /**
  11146. * Checks if the internal buffers required an update.
  11147. *
  11148. * @param {NodeFrame} frame - The current node frame.
  11149. */
  11150. update( /*frame*/ ) {
  11151. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  11152. this.buffer.version = this.instanceMatrix.version;
  11153. }
  11154. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  11155. this.bufferColor.version = this.instanceColor.version;
  11156. }
  11157. }
  11158. }
  11159. /**
  11160. * TSL function for creating an instance node.
  11161. *
  11162. * @tsl
  11163. * @function
  11164. * @param {number} count - The number of instances.
  11165. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11166. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11167. * @returns {InstanceNode}
  11168. */
  11169. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11170. /**
  11171. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11172. * It allows an easier setup of the instance node.
  11173. *
  11174. * @augments InstanceNode
  11175. */
  11176. class InstancedMeshNode extends InstanceNode {
  11177. static get type() {
  11178. return 'InstancedMeshNode';
  11179. }
  11180. /**
  11181. * Constructs a new instanced mesh node.
  11182. *
  11183. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11184. */
  11185. constructor( instancedMesh ) {
  11186. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11187. super( count, instanceMatrix, instanceColor );
  11188. /**
  11189. * A reference to the instanced mesh.
  11190. *
  11191. * @type {InstancedMesh}
  11192. */
  11193. this.instancedMesh = instancedMesh;
  11194. }
  11195. }
  11196. /**
  11197. * TSL function for creating an instanced mesh node.
  11198. *
  11199. * @tsl
  11200. * @function
  11201. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11202. * @returns {InstancedMeshNode}
  11203. */
  11204. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11205. /**
  11206. * This node implements the vertex shader logic which is required
  11207. * when rendering 3D objects via batching. `BatchNode` must be used
  11208. * with instances of {@link BatchedMesh}.
  11209. *
  11210. * @augments Node
  11211. */
  11212. class BatchNode extends Node {
  11213. static get type() {
  11214. return 'BatchNode';
  11215. }
  11216. /**
  11217. * Constructs a new batch node.
  11218. *
  11219. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11220. */
  11221. constructor( batchMesh ) {
  11222. super( 'void' );
  11223. /**
  11224. * A reference to batched mesh.
  11225. *
  11226. * @type {BatchedMesh}
  11227. */
  11228. this.batchMesh = batchMesh;
  11229. /**
  11230. * The batching index node.
  11231. *
  11232. * @type {?IndexNode}
  11233. * @default null
  11234. */
  11235. this.batchingIdNode = null;
  11236. }
  11237. /**
  11238. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11239. * to predefined node variables for accumulation. That follows the same patterns
  11240. * like with morph and skinning nodes.
  11241. *
  11242. * @param {NodeBuilder} builder - The current node builder.
  11243. */
  11244. setup( builder ) {
  11245. if ( this.batchingIdNode === null ) {
  11246. if ( builder.getDrawIndex() === null ) {
  11247. this.batchingIdNode = instanceIndex;
  11248. } else {
  11249. this.batchingIdNode = drawIndex;
  11250. }
  11251. }
  11252. const getIndirectIndex = Fn( ( [ id ] ) => {
  11253. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  11254. const x = int( id ).mod( size );
  11255. const y = int( id ).div( size );
  11256. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11257. } ).setLayout( {
  11258. name: 'getIndirectIndex',
  11259. type: 'uint',
  11260. inputs: [
  11261. { name: 'id', type: 'int' }
  11262. ]
  11263. } );
  11264. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11265. const matricesTexture = this.batchMesh._matricesTexture;
  11266. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  11267. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  11268. const x = j.mod( size );
  11269. const y = j.div( size );
  11270. const batchingMatrix = mat4(
  11271. textureLoad( matricesTexture, ivec2( x, y ) ),
  11272. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11273. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11274. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11275. );
  11276. const colorsTexture = this.batchMesh._colorsTexture;
  11277. if ( colorsTexture !== null ) {
  11278. const getBatchingColor = Fn( ( [ id ] ) => {
  11279. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  11280. const j = id;
  11281. const x = j.mod( size );
  11282. const y = j.div( size );
  11283. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11284. } ).setLayout( {
  11285. name: 'getBatchingColor',
  11286. type: 'vec3',
  11287. inputs: [
  11288. { name: 'id', type: 'int' }
  11289. ]
  11290. } );
  11291. const color = getBatchingColor( indirectId );
  11292. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11293. }
  11294. const bm = mat3( batchingMatrix );
  11295. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11296. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11297. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11298. normalLocal.assign( batchingNormal );
  11299. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11300. tangentLocal.mulAssign( bm );
  11301. }
  11302. }
  11303. }
  11304. /**
  11305. * TSL function for creating a batch node.
  11306. *
  11307. * @tsl
  11308. * @function
  11309. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11310. * @returns {BatchNode}
  11311. */
  11312. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11313. /**
  11314. * This class enables element access on instances of {@link StorageBufferNode}.
  11315. * In most cases, it is indirectly used when accessing elements with the
  11316. * {@link StorageBufferNode#element} method.
  11317. *
  11318. * ```js
  11319. * const position = positionStorage.element( instanceIndex );
  11320. * ```
  11321. *
  11322. * @augments ArrayElementNode
  11323. */
  11324. class StorageArrayElementNode extends ArrayElementNode {
  11325. static get type() {
  11326. return 'StorageArrayElementNode';
  11327. }
  11328. /**
  11329. * Constructs storage buffer element node.
  11330. *
  11331. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11332. * @param {Node} indexNode - The index node that defines the element access.
  11333. */
  11334. constructor( storageBufferNode, indexNode ) {
  11335. super( storageBufferNode, indexNode );
  11336. /**
  11337. * This flag can be used for type testing.
  11338. *
  11339. * @type {boolean}
  11340. * @readonly
  11341. * @default true
  11342. */
  11343. this.isStorageArrayElementNode = true;
  11344. }
  11345. /**
  11346. * The storage buffer node.
  11347. *
  11348. * @param {Node} value
  11349. * @type {StorageBufferNode}
  11350. */
  11351. set storageBufferNode( value ) {
  11352. this.node = value;
  11353. }
  11354. get storageBufferNode() {
  11355. return this.node;
  11356. }
  11357. getMemberType( builder, name ) {
  11358. const structTypeNode = this.storageBufferNode.structTypeNode;
  11359. if ( structTypeNode ) {
  11360. return structTypeNode.getMemberType( builder, name );
  11361. }
  11362. return 'void';
  11363. }
  11364. setup( builder ) {
  11365. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11366. if ( this.node.isPBO === true ) {
  11367. builder.setupPBO( this.node );
  11368. }
  11369. }
  11370. return super.setup( builder );
  11371. }
  11372. generate( builder, output ) {
  11373. let snippet;
  11374. const isAssignContext = builder.context.assign;
  11375. //
  11376. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11377. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11378. snippet = builder.generatePBO( this );
  11379. } else {
  11380. snippet = this.node.build( builder );
  11381. }
  11382. } else {
  11383. snippet = super.generate( builder );
  11384. }
  11385. if ( isAssignContext !== true ) {
  11386. const type = this.getNodeType( builder );
  11387. snippet = builder.format( snippet, type, output );
  11388. }
  11389. return snippet;
  11390. }
  11391. }
  11392. /**
  11393. * TSL function for creating a storage element node.
  11394. *
  11395. * @tsl
  11396. * @function
  11397. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11398. * @param {Node} indexNode - The index node that defines the element access.
  11399. * @returns {StorageArrayElementNode}
  11400. */
  11401. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11402. /**
  11403. * This node is used in context of compute shaders and allows to define a
  11404. * storage buffer for data. A typical workflow is to create instances of
  11405. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11406. * setup up a compute shader that writes into the buffers and then convert
  11407. * the storage buffers to attribute nodes for rendering.
  11408. *
  11409. * ```js
  11410. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11411. *
  11412. * const computeInit = Fn( () => { // the compute shader
  11413. *
  11414. * const position = positionBuffer.element( instanceIndex );
  11415. *
  11416. * // compute position data
  11417. *
  11418. * position.x = 1;
  11419. * position.y = 1;
  11420. * position.z = 1;
  11421. *
  11422. * } )().compute( particleCount );
  11423. *
  11424. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11425. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11426. *
  11427. * renderer.computeAsync( computeInit );
  11428. *
  11429. * ```
  11430. *
  11431. * @augments BufferNode
  11432. */
  11433. class StorageBufferNode extends BufferNode {
  11434. static get type() {
  11435. return 'StorageBufferNode';
  11436. }
  11437. /**
  11438. * Constructs a new storage buffer node.
  11439. *
  11440. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11441. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11442. * @param {number} [bufferCount=0] - The buffer count.
  11443. */
  11444. constructor( value, bufferType = null, bufferCount = 0 ) {
  11445. let nodeType, structTypeNode = null;
  11446. if ( bufferType && bufferType.isStruct ) {
  11447. nodeType = 'struct';
  11448. structTypeNode = bufferType.layout;
  11449. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11450. bufferCount = value.count;
  11451. }
  11452. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11453. nodeType = getTypeFromLength( value.itemSize );
  11454. bufferCount = value.count;
  11455. } else {
  11456. nodeType = bufferType;
  11457. }
  11458. super( value, nodeType, bufferCount );
  11459. /**
  11460. * This flag can be used for type testing.
  11461. *
  11462. * @type {boolean}
  11463. * @readonly
  11464. * @default true
  11465. */
  11466. this.isStorageBufferNode = true;
  11467. /**
  11468. * The buffer struct type.
  11469. *
  11470. * @type {?StructTypeNode}
  11471. * @default null
  11472. */
  11473. this.structTypeNode = structTypeNode;
  11474. /**
  11475. * The access type of the texture node.
  11476. *
  11477. * @type {string}
  11478. * @default 'readWrite'
  11479. */
  11480. this.access = NodeAccess.READ_WRITE;
  11481. /**
  11482. * Whether the node is atomic or not.
  11483. *
  11484. * @type {boolean}
  11485. * @default false
  11486. */
  11487. this.isAtomic = false;
  11488. /**
  11489. * Whether the node represents a PBO or not.
  11490. * Only relevant for WebGL.
  11491. *
  11492. * @type {boolean}
  11493. * @default false
  11494. */
  11495. this.isPBO = false;
  11496. /**
  11497. * A reference to the internal buffer attribute node.
  11498. *
  11499. * @type {?BufferAttributeNode}
  11500. * @default null
  11501. */
  11502. this._attribute = null;
  11503. /**
  11504. * A reference to the internal varying node.
  11505. *
  11506. * @type {?VaryingNode}
  11507. * @default null
  11508. */
  11509. this._varying = null;
  11510. /**
  11511. * `StorageBufferNode` sets this property to `true` by default.
  11512. *
  11513. * @type {boolean}
  11514. * @default true
  11515. */
  11516. this.global = true;
  11517. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11518. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11519. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11520. else value.isStorageBufferAttribute = true;
  11521. }
  11522. }
  11523. /**
  11524. * This method is overwritten since the buffer data might be shared
  11525. * and thus the hash should be shared as well.
  11526. *
  11527. * @param {NodeBuilder} builder - The current node builder.
  11528. * @return {string} The hash.
  11529. */
  11530. getHash( builder ) {
  11531. if ( this.bufferCount === 0 ) {
  11532. let bufferData = builder.globalCache.getData( this.value );
  11533. if ( bufferData === undefined ) {
  11534. bufferData = {
  11535. node: this
  11536. };
  11537. builder.globalCache.setData( this.value, bufferData );
  11538. }
  11539. return bufferData.node.uuid;
  11540. }
  11541. return this.uuid;
  11542. }
  11543. /**
  11544. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11545. *
  11546. * @param {NodeBuilder} builder - The current node builder.
  11547. * @return {string} The input type.
  11548. */
  11549. getInputType( /*builder*/ ) {
  11550. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11551. }
  11552. /**
  11553. * Enables element access with the given index node.
  11554. *
  11555. * @param {IndexNode} indexNode - The index node.
  11556. * @return {StorageArrayElementNode} A node representing the element access.
  11557. */
  11558. element( indexNode ) {
  11559. return storageElement( this, indexNode );
  11560. }
  11561. /**
  11562. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11563. *
  11564. * @param {boolean} value - The value so set.
  11565. * @return {StorageBufferNode} A reference to this node.
  11566. */
  11567. setPBO( value ) {
  11568. this.isPBO = value;
  11569. return this;
  11570. }
  11571. /**
  11572. * Returns the `isPBO` value.
  11573. *
  11574. * @return {boolean} Whether the node represents a PBO or not.
  11575. */
  11576. getPBO() {
  11577. return this.isPBO;
  11578. }
  11579. /**
  11580. * Defines the node access.
  11581. *
  11582. * @param {string} value - The node access.
  11583. * @return {StorageBufferNode} A reference to this node.
  11584. */
  11585. setAccess( value ) {
  11586. this.access = value;
  11587. return this;
  11588. }
  11589. /**
  11590. * Convenience method for configuring a read-only node access.
  11591. *
  11592. * @return {StorageBufferNode} A reference to this node.
  11593. */
  11594. toReadOnly() {
  11595. return this.setAccess( NodeAccess.READ_ONLY );
  11596. }
  11597. /**
  11598. * Defines whether the node is atomic or not.
  11599. *
  11600. * @param {boolean} value - The atomic flag.
  11601. * @return {StorageBufferNode} A reference to this node.
  11602. */
  11603. setAtomic( value ) {
  11604. this.isAtomic = value;
  11605. return this;
  11606. }
  11607. /**
  11608. * Convenience method for making this node atomic.
  11609. *
  11610. * @return {StorageBufferNode} A reference to this node.
  11611. */
  11612. toAtomic() {
  11613. return this.setAtomic( true );
  11614. }
  11615. /**
  11616. * Returns attribute data for this storage buffer node.
  11617. *
  11618. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11619. */
  11620. getAttributeData() {
  11621. if ( this._attribute === null ) {
  11622. this._attribute = bufferAttribute( this.value );
  11623. this._varying = varying( this._attribute );
  11624. }
  11625. return {
  11626. attribute: this._attribute,
  11627. varying: this._varying
  11628. };
  11629. }
  11630. /**
  11631. * This method is overwritten since the node type from the availability of storage buffers
  11632. * and the attribute data.
  11633. *
  11634. * @param {NodeBuilder} builder - The current node builder.
  11635. * @return {string} The node type.
  11636. */
  11637. getNodeType( builder ) {
  11638. if ( this.structTypeNode !== null ) {
  11639. return this.structTypeNode.getNodeType( builder );
  11640. }
  11641. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11642. return super.getNodeType( builder );
  11643. }
  11644. const { attribute } = this.getAttributeData();
  11645. return attribute.getNodeType( builder );
  11646. }
  11647. /**
  11648. * Returns the type of a member of the struct.
  11649. *
  11650. * @param {NodeBuilder} builder - The current node builder.
  11651. * @param {string} name - The name of the member.
  11652. * @return {string} The type of the member.
  11653. */
  11654. getMemberType( builder, name ) {
  11655. if ( this.structTypeNode !== null ) {
  11656. return this.structTypeNode.getMemberType( builder, name );
  11657. }
  11658. return 'void';
  11659. }
  11660. /**
  11661. * Generates the code snippet of the storage buffer node.
  11662. *
  11663. * @param {NodeBuilder} builder - The current node builder.
  11664. * @return {string} The generated code snippet.
  11665. */
  11666. generate( builder ) {
  11667. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11668. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11669. return super.generate( builder );
  11670. }
  11671. const { attribute, varying } = this.getAttributeData();
  11672. const output = varying.build( builder );
  11673. builder.registerTransform( output, attribute );
  11674. return output;
  11675. }
  11676. }
  11677. /**
  11678. * TSL function for creating a storage buffer node.
  11679. *
  11680. * @tsl
  11681. * @function
  11682. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11683. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11684. * @param {number} [count=0] - The buffer count.
  11685. * @returns {StorageBufferNode}
  11686. */
  11687. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11688. /**
  11689. * @tsl
  11690. * @function
  11691. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11692. *
  11693. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11694. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  11695. * @param {number} count - The buffer count.
  11696. * @returns {StorageBufferNode}
  11697. */
  11698. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11699. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11700. return storage( value, type, count ).setPBO( true );
  11701. };
  11702. const _frameId = new WeakMap();
  11703. /**
  11704. * This node implements the vertex transformation shader logic which is required
  11705. * for skinning/skeletal animation.
  11706. *
  11707. * @augments Node
  11708. */
  11709. class SkinningNode extends Node {
  11710. static get type() {
  11711. return 'SkinningNode';
  11712. }
  11713. /**
  11714. * Constructs a new skinning node.
  11715. *
  11716. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11717. */
  11718. constructor( skinnedMesh ) {
  11719. super( 'void' );
  11720. /**
  11721. * The skinned mesh.
  11722. *
  11723. * @type {SkinnedMesh}
  11724. */
  11725. this.skinnedMesh = skinnedMesh;
  11726. /**
  11727. * The update type overwritten since skinning nodes are updated per object.
  11728. *
  11729. * @type {string}
  11730. */
  11731. this.updateType = NodeUpdateType.OBJECT;
  11732. //
  11733. /**
  11734. * The skin index attribute.
  11735. *
  11736. * @type {AttributeNode}
  11737. */
  11738. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  11739. /**
  11740. * The skin weight attribute.
  11741. *
  11742. * @type {AttributeNode}
  11743. */
  11744. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  11745. /**
  11746. * The bind matrix node.
  11747. *
  11748. * @type {Node<mat4>}
  11749. */
  11750. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  11751. /**
  11752. * The bind matrix inverse node.
  11753. *
  11754. * @type {Node<mat4>}
  11755. */
  11756. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  11757. /**
  11758. * The bind matrices as a uniform buffer node.
  11759. *
  11760. * @type {Node}
  11761. */
  11762. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11763. /**
  11764. * The current vertex position in local space.
  11765. *
  11766. * @type {Node<vec3>}
  11767. */
  11768. this.positionNode = positionLocal;
  11769. /**
  11770. * The result of vertex position in local space.
  11771. *
  11772. * @type {Node<vec3>}
  11773. */
  11774. this.toPositionNode = positionLocal;
  11775. /**
  11776. * The previous bind matrices as a uniform buffer node.
  11777. * Required for computing motion vectors.
  11778. *
  11779. * @type {?Node}
  11780. * @default null
  11781. */
  11782. this.previousBoneMatricesNode = null;
  11783. }
  11784. /**
  11785. * Transforms the given vertex position via skinning.
  11786. *
  11787. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11788. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  11789. * @return {Node<vec3>} The transformed vertex position.
  11790. */
  11791. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  11792. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11793. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11794. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11795. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11796. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11797. // POSITION
  11798. const skinVertex = bindMatrixNode.mul( position );
  11799. const skinned = add(
  11800. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  11801. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11802. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11803. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11804. );
  11805. return bindMatrixInverseNode.mul( skinned ).xyz;
  11806. }
  11807. /**
  11808. * Transforms the given vertex normal via skinning.
  11809. *
  11810. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11811. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11812. * @return {Node<vec3>} The transformed vertex normal.
  11813. */
  11814. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11815. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11816. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11817. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11818. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11819. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11820. // NORMAL
  11821. let skinMatrix = add(
  11822. skinWeightNode.x.mul( boneMatX ),
  11823. skinWeightNode.y.mul( boneMatY ),
  11824. skinWeightNode.z.mul( boneMatZ ),
  11825. skinWeightNode.w.mul( boneMatW )
  11826. );
  11827. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11828. return skinMatrix.transformDirection( normal ).xyz;
  11829. }
  11830. /**
  11831. * Computes the transformed/skinned vertex position of the previous frame.
  11832. *
  11833. * @param {NodeBuilder} builder - The current node builder.
  11834. * @return {Node<vec3>} The skinned position from the previous frame.
  11835. */
  11836. getPreviousSkinnedPosition( builder ) {
  11837. const skinnedMesh = builder.object;
  11838. if ( this.previousBoneMatricesNode === null ) {
  11839. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11840. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11841. }
  11842. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  11843. }
  11844. /**
  11845. * Returns `true` if bone matrices from the previous frame are required. Relevant
  11846. * when computing motion vectors with {@link VelocityNode}.
  11847. *
  11848. * @param {NodeBuilder} builder - The current node builder.
  11849. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  11850. */
  11851. needsPreviousBoneMatrices( builder ) {
  11852. const mrt = builder.renderer.getMRT();
  11853. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  11854. }
  11855. /**
  11856. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  11857. *
  11858. * @param {NodeBuilder} builder - The current node builder.
  11859. * @return {Node<vec3>} The transformed vertex position.
  11860. */
  11861. setup( builder ) {
  11862. if ( this.needsPreviousBoneMatrices( builder ) ) {
  11863. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  11864. }
  11865. const skinPosition = this.getSkinnedPosition();
  11866. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  11867. //
  11868. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11869. const skinNormal = this.getSkinnedNormal();
  11870. normalLocal.assign( skinNormal );
  11871. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11872. tangentLocal.assign( skinNormal );
  11873. }
  11874. }
  11875. return skinPosition;
  11876. }
  11877. /**
  11878. * Generates the code snippet of the skinning node.
  11879. *
  11880. * @param {NodeBuilder} builder - The current node builder.
  11881. * @param {string} output - The current output.
  11882. * @return {string} The generated code snippet.
  11883. */
  11884. generate( builder, output ) {
  11885. if ( output !== 'void' ) {
  11886. return super.generate( builder, output );
  11887. }
  11888. }
  11889. /**
  11890. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  11891. *
  11892. * @param {NodeFrame} frame - The current node frame.
  11893. */
  11894. update( frame ) {
  11895. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  11896. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  11897. _frameId.set( skeleton, frame.frameId );
  11898. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  11899. skeleton.update();
  11900. }
  11901. }
  11902. /**
  11903. * TSL function for creating a skinning node.
  11904. *
  11905. * @tsl
  11906. * @function
  11907. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11908. * @returns {SkinningNode}
  11909. */
  11910. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  11911. /**
  11912. * TSL function for computing skinning.
  11913. *
  11914. * @tsl
  11915. * @function
  11916. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11917. * @param {Node<vec3>} [toPosition=null] - The target position.
  11918. * @returns {SkinningNode}
  11919. */
  11920. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11921. const node = new SkinningNode( skinnedMesh );
  11922. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11923. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11924. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11925. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11926. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11927. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11928. node.toPositionNode = toPosition;
  11929. return nodeObject( node );
  11930. };
  11931. /**
  11932. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11933. * ```js
  11934. * Loop( count, ( { i } ) => {
  11935. *
  11936. * } );
  11937. * ```
  11938. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11939. * ```js
  11940. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11941. *
  11942. * } );
  11943. *```
  11944. * Nested loops can be defined in a compacted form:
  11945. * ```js
  11946. * Loop( 10, 5, ( { i, j } ) => {
  11947. *
  11948. * } );
  11949. * ```
  11950. * Loops that should run backwards can be defined like so:
  11951. * ```js
  11952. * Loop( { start: 10 }, () => {} );
  11953. * ```
  11954. * It is possible to execute with boolean values, similar to the `while` syntax.
  11955. * ```js
  11956. * const value = float( 0 ).toVar();
  11957. *
  11958. * Loop( value.lessThan( 10 ), () => {
  11959. *
  11960. * value.addAssign( 1 );
  11961. *
  11962. * } );
  11963. * ```
  11964. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11965. * @augments Node
  11966. */
  11967. class LoopNode extends Node {
  11968. static get type() {
  11969. return 'LoopNode';
  11970. }
  11971. /**
  11972. * Constructs a new loop node.
  11973. *
  11974. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11975. */
  11976. constructor( params = [] ) {
  11977. super();
  11978. this.params = params;
  11979. }
  11980. /**
  11981. * Returns a loop variable name based on an index. The pattern is
  11982. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11983. *
  11984. * @param {number} index - The index.
  11985. * @return {string} The loop variable name.
  11986. */
  11987. getVarName( index ) {
  11988. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11989. }
  11990. /**
  11991. * Returns properties about this node.
  11992. *
  11993. * @param {NodeBuilder} builder - The current node builder.
  11994. * @return {Object} The node properties.
  11995. */
  11996. getProperties( builder ) {
  11997. const properties = builder.getNodeProperties( this );
  11998. if ( properties.stackNode !== undefined ) return properties;
  11999. //
  12000. const inputs = {};
  12001. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12002. const param = this.params[ i ];
  12003. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12004. const type = ( param.isNode !== true && param.type ) || 'int';
  12005. inputs[ name ] = expression( name, type );
  12006. }
  12007. const stack = builder.addStack(); // TODO: cache() it
  12008. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  12009. properties.stackNode = stack;
  12010. const baseParam = this.params[ 0 ];
  12011. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12012. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  12013. }
  12014. builder.removeStack();
  12015. return properties;
  12016. }
  12017. /**
  12018. * This method is overwritten since the node type is inferred based on the loop configuration.
  12019. *
  12020. * @param {NodeBuilder} builder - The current node builder.
  12021. * @return {string} The node type.
  12022. */
  12023. getNodeType( builder ) {
  12024. const { returnsNode } = this.getProperties( builder );
  12025. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  12026. }
  12027. setup( builder ) {
  12028. // setup properties
  12029. this.getProperties( builder );
  12030. }
  12031. generate( builder ) {
  12032. const properties = this.getProperties( builder );
  12033. const params = this.params;
  12034. const stackNode = properties.stackNode;
  12035. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12036. const param = params[ i ];
  12037. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12038. if ( param.isNode ) {
  12039. if ( param.getNodeType( builder ) === 'bool' ) {
  12040. isWhile = true;
  12041. type = 'bool';
  12042. end = param.build( builder, type );
  12043. } else {
  12044. type = 'int';
  12045. name = this.getVarName( i );
  12046. start = '0';
  12047. end = param.build( builder, type );
  12048. condition = '<';
  12049. }
  12050. } else {
  12051. type = param.type || 'int';
  12052. name = param.name || this.getVarName( i );
  12053. start = param.start;
  12054. end = param.end;
  12055. condition = param.condition;
  12056. update = param.update;
  12057. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12058. else if ( start && start.isNode ) start = start.build( builder, type );
  12059. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12060. else if ( end && end.isNode ) end = end.build( builder, type );
  12061. if ( start !== undefined && end === undefined ) {
  12062. start = start + ' - 1';
  12063. end = '0';
  12064. condition = '>=';
  12065. } else if ( end !== undefined && start === undefined ) {
  12066. start = '0';
  12067. condition = '<';
  12068. }
  12069. if ( condition === undefined ) {
  12070. if ( Number( start ) > Number( end ) ) {
  12071. condition = '>=';
  12072. } else {
  12073. condition = '<';
  12074. }
  12075. }
  12076. }
  12077. let loopSnippet;
  12078. if ( isWhile ) {
  12079. loopSnippet = `while ( ${ end } )`;
  12080. } else {
  12081. const internalParam = { start, end};
  12082. //
  12083. const startSnippet = internalParam.start;
  12084. const endSnippet = internalParam.end;
  12085. let updateSnippet;
  12086. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12087. if ( update !== undefined && update !== null ) {
  12088. switch ( typeof update ) {
  12089. case 'function':
  12090. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12091. const snippet = flow.code.replace( /\t|;/g, '' );
  12092. updateSnippet = snippet;
  12093. break;
  12094. case 'number':
  12095. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12096. break;
  12097. case 'string':
  12098. updateSnippet = name + ' ' + update;
  12099. break;
  12100. default:
  12101. if ( update.isNode ) {
  12102. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12103. } else {
  12104. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12105. updateSnippet = 'break /* invalid update */';
  12106. }
  12107. }
  12108. } else {
  12109. if ( type === 'int' || type === 'uint' ) {
  12110. update = condition.includes( '<' ) ? '++' : '--';
  12111. } else {
  12112. update = deltaOperator() + ' 1.';
  12113. }
  12114. updateSnippet = name + ' ' + update;
  12115. }
  12116. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12117. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12118. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12119. }
  12120. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12121. }
  12122. const stackSnippet = stackNode.build( builder, 'void' );
  12123. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  12124. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12125. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12126. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12127. }
  12128. builder.addFlowTab();
  12129. return returnsSnippet;
  12130. }
  12131. }
  12132. /**
  12133. * TSL function for creating a loop node.
  12134. *
  12135. * @tsl
  12136. * @function
  12137. * @param {...any} params - A list of parameters.
  12138. * @returns {LoopNode}
  12139. */
  12140. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  12141. /**
  12142. * TSL function for creating a `Continue()` expression.
  12143. *
  12144. * @tsl
  12145. * @function
  12146. * @returns {ExpressionNode}
  12147. */
  12148. const Continue = () => expression( 'continue' ).toStack();
  12149. /**
  12150. * TSL function for creating a `Break()` expression.
  12151. *
  12152. * @tsl
  12153. * @function
  12154. * @returns {ExpressionNode}
  12155. */
  12156. const Break = () => expression( 'break' ).toStack();
  12157. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12158. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12159. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12160. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12161. const y = texelIndex.div( width );
  12162. const x = texelIndex.sub( y.mul( width ) );
  12163. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12164. return bufferAttrib.mul( influence );
  12165. } );
  12166. function getEntry( geometry ) {
  12167. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12168. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12169. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12170. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12171. // into an array of data textures. Each layer represents a single morph target.
  12172. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12173. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12174. let entry = _morphTextures.get( geometry );
  12175. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12176. if ( entry !== undefined ) entry.texture.dispose();
  12177. const morphTargets = geometry.morphAttributes.position || [];
  12178. const morphNormals = geometry.morphAttributes.normal || [];
  12179. const morphColors = geometry.morphAttributes.color || [];
  12180. let vertexDataCount = 0;
  12181. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12182. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12183. if ( hasMorphColors === true ) vertexDataCount = 3;
  12184. let width = geometry.attributes.position.count * vertexDataCount;
  12185. let height = 1;
  12186. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12187. if ( width > maxTextureSize ) {
  12188. height = Math.ceil( width / maxTextureSize );
  12189. width = maxTextureSize;
  12190. }
  12191. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12192. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12193. bufferTexture.type = FloatType;
  12194. bufferTexture.needsUpdate = true;
  12195. // fill buffer
  12196. const vertexDataStride = vertexDataCount * 4;
  12197. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12198. const morphTarget = morphTargets[ i ];
  12199. const morphNormal = morphNormals[ i ];
  12200. const morphColor = morphColors[ i ];
  12201. const offset = width * height * 4 * i;
  12202. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12203. const stride = j * vertexDataStride;
  12204. if ( hasMorphPosition === true ) {
  12205. _morphVec4.fromBufferAttribute( morphTarget, j );
  12206. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12207. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12208. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12209. buffer[ offset + stride + 3 ] = 0;
  12210. }
  12211. if ( hasMorphNormals === true ) {
  12212. _morphVec4.fromBufferAttribute( morphNormal, j );
  12213. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12214. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12215. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12216. buffer[ offset + stride + 7 ] = 0;
  12217. }
  12218. if ( hasMorphColors === true ) {
  12219. _morphVec4.fromBufferAttribute( morphColor, j );
  12220. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12221. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12222. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12223. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12224. }
  12225. }
  12226. }
  12227. entry = {
  12228. count: morphTargetsCount,
  12229. texture: bufferTexture,
  12230. stride: vertexDataCount,
  12231. size: new Vector2( width, height )
  12232. };
  12233. _morphTextures.set( geometry, entry );
  12234. function disposeTexture() {
  12235. bufferTexture.dispose();
  12236. _morphTextures.delete( geometry );
  12237. geometry.removeEventListener( 'dispose', disposeTexture );
  12238. }
  12239. geometry.addEventListener( 'dispose', disposeTexture );
  12240. }
  12241. return entry;
  12242. }
  12243. /**
  12244. * This node implements the vertex transformation shader logic which is required
  12245. * for morph target animation.
  12246. *
  12247. * @augments Node
  12248. */
  12249. class MorphNode extends Node {
  12250. static get type() {
  12251. return 'MorphNode';
  12252. }
  12253. /**
  12254. * Constructs a new morph node.
  12255. *
  12256. * @param {Mesh} mesh - The mesh holding the morph targets.
  12257. */
  12258. constructor( mesh ) {
  12259. super( 'void' );
  12260. /**
  12261. * The mesh holding the morph targets.
  12262. *
  12263. * @type {Mesh}
  12264. */
  12265. this.mesh = mesh;
  12266. /**
  12267. * A uniform node which represents the morph base influence value.
  12268. *
  12269. * @type {UniformNode<float>}
  12270. */
  12271. this.morphBaseInfluence = uniform( 1 );
  12272. /**
  12273. * The update type overwritten since morph nodes are updated per object.
  12274. *
  12275. * @type {string}
  12276. */
  12277. this.updateType = NodeUpdateType.OBJECT;
  12278. }
  12279. /**
  12280. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12281. *
  12282. * @param {NodeBuilder} builder - The current node builder.
  12283. */
  12284. setup( builder ) {
  12285. const { geometry } = builder;
  12286. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12287. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12288. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12289. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12290. // nodes
  12291. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12292. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12293. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12294. const width = int( size.width );
  12295. Loop( morphTargetsCount, ( { i } ) => {
  12296. const influence = float( 0 ).toVar();
  12297. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12298. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12299. } else {
  12300. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12301. }
  12302. If( influence.notEqual( 0 ), () => {
  12303. if ( hasMorphPosition === true ) {
  12304. positionLocal.addAssign( getMorph( {
  12305. bufferMap,
  12306. influence,
  12307. stride,
  12308. width,
  12309. depth: i,
  12310. offset: int( 0 )
  12311. } ) );
  12312. }
  12313. if ( hasMorphNormals === true ) {
  12314. normalLocal.addAssign( getMorph( {
  12315. bufferMap,
  12316. influence,
  12317. stride,
  12318. width,
  12319. depth: i,
  12320. offset: int( 1 )
  12321. } ) );
  12322. }
  12323. } );
  12324. } );
  12325. }
  12326. /**
  12327. * Updates the state of the morphed mesh by updating the base influence.
  12328. *
  12329. * @param {NodeFrame} frame - The current node frame.
  12330. */
  12331. update( /*frame*/ ) {
  12332. const morphBaseInfluence = this.morphBaseInfluence;
  12333. if ( this.mesh.geometry.morphTargetsRelative ) {
  12334. morphBaseInfluence.value = 1;
  12335. } else {
  12336. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12337. }
  12338. }
  12339. }
  12340. /**
  12341. * TSL function for creating a morph node.
  12342. *
  12343. * @tsl
  12344. * @function
  12345. * @param {Mesh} mesh - The mesh holding the morph targets.
  12346. * @returns {MorphNode}
  12347. */
  12348. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12349. /**
  12350. * Base class for lighting nodes.
  12351. *
  12352. * @augments Node
  12353. */
  12354. class LightingNode extends Node {
  12355. static get type() {
  12356. return 'LightingNode';
  12357. }
  12358. /**
  12359. * Constructs a new lighting node.
  12360. */
  12361. constructor() {
  12362. super( 'vec3' );
  12363. /**
  12364. * This flag can be used for type testing.
  12365. *
  12366. * @type {boolean}
  12367. * @readonly
  12368. * @default true
  12369. */
  12370. this.isLightingNode = true;
  12371. }
  12372. }
  12373. /**
  12374. * A generic class that can be used by nodes which contribute
  12375. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12376. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12377. *
  12378. * @augments LightingNode
  12379. */
  12380. class AONode extends LightingNode {
  12381. static get type() {
  12382. return 'AONode';
  12383. }
  12384. /**
  12385. * Constructs a new AO node.
  12386. *
  12387. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12388. */
  12389. constructor( aoNode = null ) {
  12390. super();
  12391. /**
  12392. * The ambient occlusion node.
  12393. *
  12394. * @type {?Node<float>}
  12395. * @default null
  12396. */
  12397. this.aoNode = aoNode;
  12398. }
  12399. setup( builder ) {
  12400. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12401. }
  12402. }
  12403. /**
  12404. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12405. * by adding lighting specific context data. It represents the runtime context of
  12406. * {@link LightsNode}.
  12407. *
  12408. * @augments ContextNode
  12409. */
  12410. class LightingContextNode extends ContextNode {
  12411. static get type() {
  12412. return 'LightingContextNode';
  12413. }
  12414. /**
  12415. * Constructs a new lighting context node.
  12416. *
  12417. * @param {LightsNode} lightsNode - The lights node.
  12418. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12419. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12420. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12421. */
  12422. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12423. super( lightsNode );
  12424. /**
  12425. * The current lighting model.
  12426. *
  12427. * @type {?LightingModel}
  12428. * @default null
  12429. */
  12430. this.lightingModel = lightingModel;
  12431. /**
  12432. * A backdrop node.
  12433. *
  12434. * @type {?Node<vec3>}
  12435. * @default null
  12436. */
  12437. this.backdropNode = backdropNode;
  12438. /**
  12439. * A backdrop alpha node.
  12440. *
  12441. * @type {?Node<float>}
  12442. * @default null
  12443. */
  12444. this.backdropAlphaNode = backdropAlphaNode;
  12445. this._value = null;
  12446. }
  12447. /**
  12448. * Returns a lighting context object.
  12449. *
  12450. * @return {{
  12451. * radiance: Node<vec3>,
  12452. * irradiance: Node<vec3>,
  12453. * iblIrradiance: Node<vec3>,
  12454. * ambientOcclusion: Node<float>,
  12455. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12456. * backdrop: Node<vec3>,
  12457. * backdropAlpha: Node<float>
  12458. * }} The lighting context object.
  12459. */
  12460. getContext() {
  12461. const { backdropNode, backdropAlphaNode } = this;
  12462. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12463. directSpecular = vec3().toVar( 'directSpecular' ),
  12464. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12465. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12466. const reflectedLight = {
  12467. directDiffuse,
  12468. directSpecular,
  12469. indirectDiffuse,
  12470. indirectSpecular
  12471. };
  12472. const context = {
  12473. radiance: vec3().toVar( 'radiance' ),
  12474. irradiance: vec3().toVar( 'irradiance' ),
  12475. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12476. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12477. reflectedLight,
  12478. backdrop: backdropNode,
  12479. backdropAlpha: backdropAlphaNode
  12480. };
  12481. return context;
  12482. }
  12483. setup( builder ) {
  12484. this.value = this._value || ( this._value = this.getContext() );
  12485. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  12486. return super.setup( builder );
  12487. }
  12488. }
  12489. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  12490. /**
  12491. * A generic class that can be used by nodes which contribute
  12492. * irradiance to the scene. E.g. a light map node can be used
  12493. * as input for this module. Used in {@link NodeMaterial}.
  12494. *
  12495. * @augments LightingNode
  12496. */
  12497. class IrradianceNode extends LightingNode {
  12498. static get type() {
  12499. return 'IrradianceNode';
  12500. }
  12501. /**
  12502. * Constructs a new irradiance node.
  12503. *
  12504. * @param {Node<vec3>} node - A node contributing irradiance.
  12505. */
  12506. constructor( node ) {
  12507. super();
  12508. /**
  12509. * A node contributing irradiance.
  12510. *
  12511. * @type {Node<vec3>}
  12512. */
  12513. this.node = node;
  12514. }
  12515. setup( builder ) {
  12516. builder.context.irradiance.addAssign( this.node );
  12517. }
  12518. }
  12519. const _size$4 = /*@__PURE__*/ new Vector2();
  12520. /**
  12521. * A special type of texture node which represents the data of the current viewport
  12522. * as a texture. The module extracts data from the current bound framebuffer with
  12523. * a copy operation so no extra render pass is required to produce the texture data
  12524. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  12525. * variety of effects like refractive or transmissive materials.
  12526. *
  12527. * @augments TextureNode
  12528. */
  12529. class ViewportTextureNode extends TextureNode {
  12530. static get type() {
  12531. return 'ViewportTextureNode';
  12532. }
  12533. /**
  12534. * Constructs a new viewport texture node.
  12535. *
  12536. * @param {Node} [uvNode=screenUV] - The uv node.
  12537. * @param {?Node} [levelNode=null] - The level node.
  12538. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12539. */
  12540. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12541. let defaultFramebuffer = null;
  12542. if ( framebufferTexture === null ) {
  12543. defaultFramebuffer = new FramebufferTexture();
  12544. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  12545. framebufferTexture = defaultFramebuffer;
  12546. } else {
  12547. defaultFramebuffer = framebufferTexture;
  12548. }
  12549. super( framebufferTexture, uvNode, levelNode );
  12550. /**
  12551. * Whether to generate mipmaps or not.
  12552. *
  12553. * @type {boolean}
  12554. * @default false
  12555. */
  12556. this.generateMipmaps = false;
  12557. /**
  12558. * The reference framebuffer texture. This is used to store the framebuffer texture
  12559. * for the current render target. If the render target changes, a new framebuffer texture
  12560. * is created automatically.
  12561. *
  12562. * @type {FramebufferTexture}
  12563. * @default null
  12564. */
  12565. this.defaultFramebuffer = defaultFramebuffer;
  12566. /**
  12567. * This flag can be used for type testing.
  12568. *
  12569. * @type {boolean}
  12570. * @readonly
  12571. * @default true
  12572. */
  12573. this.isOutputTextureNode = true;
  12574. /**
  12575. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  12576. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  12577. *
  12578. * @type {string}
  12579. * @default 'frame'
  12580. */
  12581. this.updateBeforeType = NodeUpdateType.FRAME;
  12582. /**
  12583. * The framebuffer texture for the current renderer context.
  12584. *
  12585. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  12586. * @private
  12587. */
  12588. this._cacheTextures = new WeakMap();
  12589. }
  12590. /**
  12591. * This methods returns a texture for the given render target reference.
  12592. *
  12593. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  12594. * for different render contexts.
  12595. *
  12596. * @param {?RenderTarget} [reference=null] - The render target reference.
  12597. * @return {Texture} The framebuffer texture.
  12598. */
  12599. getTextureForReference( reference = null ) {
  12600. let defaultFramebuffer;
  12601. let cacheTextures;
  12602. if ( this.referenceNode ) {
  12603. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  12604. cacheTextures = this.referenceNode._cacheTextures;
  12605. } else {
  12606. defaultFramebuffer = this.defaultFramebuffer;
  12607. cacheTextures = this._cacheTextures;
  12608. }
  12609. if ( reference === null ) {
  12610. return defaultFramebuffer;
  12611. }
  12612. if ( cacheTextures.has( reference ) === false ) {
  12613. const framebufferTexture = defaultFramebuffer.clone();
  12614. cacheTextures.set( reference, framebufferTexture );
  12615. }
  12616. return cacheTextures.get( reference );
  12617. }
  12618. updateReference( frame ) {
  12619. const renderTarget = frame.renderer.getRenderTarget();
  12620. this.value = this.getTextureForReference( renderTarget );
  12621. return this.value;
  12622. }
  12623. updateBefore( frame ) {
  12624. const renderer = frame.renderer;
  12625. const renderTarget = renderer.getRenderTarget();
  12626. if ( renderTarget === null ) {
  12627. renderer.getDrawingBufferSize( _size$4 );
  12628. } else {
  12629. _size$4.set( renderTarget.width, renderTarget.height );
  12630. }
  12631. //
  12632. const framebufferTexture = this.getTextureForReference( renderTarget );
  12633. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  12634. framebufferTexture.image.width = _size$4.width;
  12635. framebufferTexture.image.height = _size$4.height;
  12636. framebufferTexture.needsUpdate = true;
  12637. }
  12638. //
  12639. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12640. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12641. renderer.copyFramebufferToTexture( framebufferTexture );
  12642. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12643. }
  12644. clone() {
  12645. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12646. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12647. return viewportTextureNode;
  12648. }
  12649. }
  12650. /**
  12651. * TSL function for creating a viewport texture node.
  12652. *
  12653. * @tsl
  12654. * @function
  12655. * @param {?Node} [uvNode=screenUV] - The uv node.
  12656. * @param {?Node} [levelNode=null] - The level node.
  12657. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12658. * @returns {ViewportTextureNode}
  12659. */
  12660. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12661. /**
  12662. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12663. *
  12664. * @tsl
  12665. * @function
  12666. * @param {?Node} [uvNode=screenUV] - The uv node.
  12667. * @param {?Node} [levelNode=null] - The level node.
  12668. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12669. * @returns {ViewportTextureNode}
  12670. */
  12671. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12672. let _sharedDepthbuffer = null;
  12673. /**
  12674. * Represents the depth of the current viewport as a texture. This module
  12675. * can be used in combination with viewport texture to achieve effects
  12676. * that require depth evaluation.
  12677. *
  12678. * @augments ViewportTextureNode
  12679. */
  12680. class ViewportDepthTextureNode extends ViewportTextureNode {
  12681. static get type() {
  12682. return 'ViewportDepthTextureNode';
  12683. }
  12684. /**
  12685. * Constructs a new viewport depth texture node.
  12686. *
  12687. * @param {Node} [uvNode=screenUV] - The uv node.
  12688. * @param {?Node} [levelNode=null] - The level node.
  12689. */
  12690. constructor( uvNode = screenUV, levelNode = null ) {
  12691. if ( _sharedDepthbuffer === null ) {
  12692. _sharedDepthbuffer = new DepthTexture();
  12693. }
  12694. super( uvNode, levelNode, _sharedDepthbuffer );
  12695. }
  12696. /**
  12697. * Overwritten so the method always returns the unique shared
  12698. * depth texture.
  12699. *
  12700. * @return {DepthTexture} The shared depth texture.
  12701. */
  12702. getTextureForReference() {
  12703. return _sharedDepthbuffer;
  12704. }
  12705. }
  12706. /**
  12707. * TSL function for a viewport depth texture node.
  12708. *
  12709. * @tsl
  12710. * @function
  12711. * @param {?Node} [uvNode=screenUV] - The uv node.
  12712. * @param {?Node} [levelNode=null] - The level node.
  12713. * @returns {ViewportDepthTextureNode}
  12714. */
  12715. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12716. /**
  12717. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12718. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12719. * fragment or for depth evaluation purposes.
  12720. *
  12721. * @augments Node
  12722. */
  12723. class ViewportDepthNode extends Node {
  12724. static get type() {
  12725. return 'ViewportDepthNode';
  12726. }
  12727. /**
  12728. * Constructs a new viewport depth node.
  12729. *
  12730. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12731. * @param {?Node} [valueNode=null] - The value node.
  12732. */
  12733. constructor( scope, valueNode = null ) {
  12734. super( 'float' );
  12735. /**
  12736. * The node behaves differently depending on which scope is selected.
  12737. *
  12738. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12739. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12740. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12741. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12742. *
  12743. * @type {('depth'|'depthBase'|'linearDepth')}
  12744. */
  12745. this.scope = scope;
  12746. /**
  12747. * Can be used to define a custom depth value.
  12748. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12749. *
  12750. * @type {?Node}
  12751. * @default null
  12752. */
  12753. this.valueNode = valueNode;
  12754. /**
  12755. * This flag can be used for type testing.
  12756. *
  12757. * @type {boolean}
  12758. * @readonly
  12759. * @default true
  12760. */
  12761. this.isViewportDepthNode = true;
  12762. }
  12763. generate( builder ) {
  12764. const { scope } = this;
  12765. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12766. return builder.getFragDepth();
  12767. }
  12768. return super.generate( builder );
  12769. }
  12770. setup( { camera } ) {
  12771. const { scope } = this;
  12772. const value = this.valueNode;
  12773. let node = null;
  12774. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12775. if ( value !== null ) {
  12776. node = depthBase().assign( value );
  12777. }
  12778. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12779. if ( camera.isPerspectiveCamera ) {
  12780. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12781. } else {
  12782. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12783. }
  12784. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12785. if ( value !== null ) {
  12786. if ( camera.isPerspectiveCamera ) {
  12787. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12788. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12789. } else {
  12790. node = value;
  12791. }
  12792. } else {
  12793. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12794. }
  12795. }
  12796. return node;
  12797. }
  12798. }
  12799. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12800. ViewportDepthNode.DEPTH = 'depth';
  12801. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12802. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12803. /**
  12804. * TSL function for converting a viewZ value to an orthographic depth value.
  12805. *
  12806. * @tsl
  12807. * @function
  12808. * @param {Node<float>} viewZ - The viewZ node.
  12809. * @param {Node<float>} near - The camera's near value.
  12810. * @param {Node<float>} far - The camera's far value.
  12811. * @returns {Node<float>}
  12812. */
  12813. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12814. /**
  12815. * TSL function for converting an orthographic depth value to a viewZ value.
  12816. *
  12817. * @tsl
  12818. * @function
  12819. * @param {Node<float>} depth - The orthographic depth.
  12820. * @param {Node<float>} near - The camera's near value.
  12821. * @param {Node<float>} far - The camera's far value.
  12822. * @returns {Node<float>}
  12823. */
  12824. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12825. /**
  12826. * TSL function for converting a viewZ value to a perspective depth value.
  12827. *
  12828. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12829. *
  12830. * @tsl
  12831. * @function
  12832. * @param {Node<float>} viewZ - The viewZ node.
  12833. * @param {Node<float>} near - The camera's near value.
  12834. * @param {Node<float>} far - The camera's far value.
  12835. * @returns {Node<float>}
  12836. */
  12837. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12838. /**
  12839. * TSL function for converting a perspective depth value to a viewZ value.
  12840. *
  12841. * @tsl
  12842. * @function
  12843. * @param {Node<float>} depth - The perspective depth.
  12844. * @param {Node<float>} near - The camera's near value.
  12845. * @param {Node<float>} far - The camera's far value.
  12846. * @returns {Node<float>}
  12847. */
  12848. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12849. /**
  12850. * TSL function for converting a viewZ value to a logarithmic depth value.
  12851. *
  12852. * @tsl
  12853. * @function
  12854. * @param {Node<float>} viewZ - The viewZ node.
  12855. * @param {Node<float>} near - The camera's near value.
  12856. * @param {Node<float>} far - The camera's far value.
  12857. * @returns {Node<float>}
  12858. */
  12859. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12860. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12861. // The final logarithmic depth formula used here is adapted from one described in an
  12862. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12863. // which was an improvement upon an earlier formula one described in an
  12864. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12865. // Ulrich's formula is the following:
  12866. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12867. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12868. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12869. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12870. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12871. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12872. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12873. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12874. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12875. // Outerra eventually made another improvement to their original "C-constant" variant,
  12876. // but it still does not incorporate the camera near plane (for this version,
  12877. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12878. // Here we make 4 changes to Ulrich's formula:
  12879. // 1. Clamp the camera near plane so we don't divide by 0.
  12880. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12881. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12882. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12883. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12884. // so we do the same here, hence the 'viewZ.negate()' call.
  12885. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12886. near = near.max( 1e-6 ).toVar();
  12887. const numerator = log2( viewZ.negate().div( near ) );
  12888. const denominator = log2( far.div( near ) );
  12889. return numerator.div( denominator );
  12890. };
  12891. /**
  12892. * TSL function for converting a logarithmic depth value to a viewZ value.
  12893. *
  12894. * @tsl
  12895. * @function
  12896. * @param {Node<float>} depth - The logarithmic depth.
  12897. * @param {Node<float>} near - The camera's near value.
  12898. * @param {Node<float>} far - The camera's far value.
  12899. * @returns {Node<float>}
  12900. */
  12901. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12902. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12903. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12904. // a negative viewZ).
  12905. const exponent = depth.mul( log( far.div( near ) ) );
  12906. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12907. };
  12908. /**
  12909. * TSL function for defining a value for the current fragment's depth.
  12910. *
  12911. * @tsl
  12912. * @function
  12913. * @param {Node<float>} value - The depth value to set.
  12914. * @returns {ViewportDepthNode<float>}
  12915. */
  12916. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12917. /**
  12918. * TSL object that represents the depth value for the current fragment.
  12919. *
  12920. * @tsl
  12921. * @type {ViewportDepthNode}
  12922. */
  12923. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12924. /**
  12925. * TSL function for converting a perspective depth value to linear depth.
  12926. *
  12927. * @tsl
  12928. * @function
  12929. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12930. * @returns {ViewportDepthNode<float>}
  12931. */
  12932. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12933. /**
  12934. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12935. *
  12936. * @tsl
  12937. * @type {ViewportDepthNode}
  12938. */
  12939. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12940. depth.assign = ( value ) => depthBase( value );
  12941. /**
  12942. * This node is used in {@link NodeMaterial} to setup the clipping
  12943. * which can happen hardware-accelerated (if supported) and optionally
  12944. * use alpha-to-coverage for anti-aliasing clipped edges.
  12945. *
  12946. * @augments Node
  12947. */
  12948. class ClippingNode extends Node {
  12949. static get type() {
  12950. return 'ClippingNode';
  12951. }
  12952. /**
  12953. * Constructs a new clipping node.
  12954. *
  12955. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12956. * the selected scope influences the behavior of the node and what type of code is generated.
  12957. */
  12958. constructor( scope = ClippingNode.DEFAULT ) {
  12959. super();
  12960. /**
  12961. * The node's scope. Similar to other nodes, the selected scope influences
  12962. * the behavior of the node and what type of code is generated.
  12963. *
  12964. * @type {('default'|'hardware'|'alphaToCoverage')}
  12965. */
  12966. this.scope = scope;
  12967. }
  12968. /**
  12969. * Setups the node depending on the selected scope.
  12970. *
  12971. * @param {NodeBuilder} builder - The current node builder.
  12972. * @return {Node} The result node.
  12973. */
  12974. setup( builder ) {
  12975. super.setup( builder );
  12976. const clippingContext = builder.clippingContext;
  12977. const { intersectionPlanes, unionPlanes } = clippingContext;
  12978. this.hardwareClipping = builder.material.hardwareClipping;
  12979. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12980. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12981. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12982. return this.setupHardwareClipping( unionPlanes, builder );
  12983. } else {
  12984. return this.setupDefault( intersectionPlanes, unionPlanes );
  12985. }
  12986. }
  12987. /**
  12988. * Setups alpha to coverage.
  12989. *
  12990. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12991. * @param {Array<Vector4>} unionPlanes - The union planes.
  12992. * @return {Node} The result node.
  12993. */
  12994. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  12995. return Fn( () => {
  12996. const distanceToPlane = float().toVar( 'distanceToPlane' );
  12997. const distanceGradient = float().toVar( 'distanceToGradient' );
  12998. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  12999. const numUnionPlanes = unionPlanes.length;
  13000. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13001. const clippingPlanes = uniformArray( unionPlanes );
  13002. Loop( numUnionPlanes, ( { i } ) => {
  13003. const plane = clippingPlanes.element( i );
  13004. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13005. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13006. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13007. } );
  13008. }
  13009. const numIntersectionPlanes = intersectionPlanes.length;
  13010. if ( numIntersectionPlanes > 0 ) {
  13011. const clippingPlanes = uniformArray( intersectionPlanes );
  13012. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13013. Loop( numIntersectionPlanes, ( { i } ) => {
  13014. const plane = clippingPlanes.element( i );
  13015. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13016. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13017. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13018. } );
  13019. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13020. }
  13021. diffuseColor.a.mulAssign( clipOpacity );
  13022. diffuseColor.a.equal( 0.0 ).discard();
  13023. } )();
  13024. }
  13025. /**
  13026. * Setups the default clipping.
  13027. *
  13028. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13029. * @param {Array<Vector4>} unionPlanes - The union planes.
  13030. * @return {Node} The result node.
  13031. */
  13032. setupDefault( intersectionPlanes, unionPlanes ) {
  13033. return Fn( () => {
  13034. const numUnionPlanes = unionPlanes.length;
  13035. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13036. const clippingPlanes = uniformArray( unionPlanes );
  13037. Loop( numUnionPlanes, ( { i } ) => {
  13038. const plane = clippingPlanes.element( i );
  13039. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13040. } );
  13041. }
  13042. const numIntersectionPlanes = intersectionPlanes.length;
  13043. if ( numIntersectionPlanes > 0 ) {
  13044. const clippingPlanes = uniformArray( intersectionPlanes );
  13045. const clipped = bool( true ).toVar( 'clipped' );
  13046. Loop( numIntersectionPlanes, ( { i } ) => {
  13047. const plane = clippingPlanes.element( i );
  13048. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13049. } );
  13050. clipped.discard();
  13051. }
  13052. } )();
  13053. }
  13054. /**
  13055. * Setups hardware clipping.
  13056. *
  13057. * @param {Array<Vector4>} unionPlanes - The union planes.
  13058. * @param {NodeBuilder} builder - The current node builder.
  13059. * @return {Node} The result node.
  13060. */
  13061. setupHardwareClipping( unionPlanes, builder ) {
  13062. const numUnionPlanes = unionPlanes.length;
  13063. builder.enableHardwareClipping( numUnionPlanes );
  13064. return Fn( () => {
  13065. const clippingPlanes = uniformArray( unionPlanes );
  13066. const hw_clip_distances = builtin( builder.getClipDistance() );
  13067. Loop( numUnionPlanes, ( { i } ) => {
  13068. const plane = clippingPlanes.element( i );
  13069. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13070. hw_clip_distances.element( i ).assign( distance );
  13071. } );
  13072. } )();
  13073. }
  13074. }
  13075. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13076. ClippingNode.DEFAULT = 'default';
  13077. ClippingNode.HARDWARE = 'hardware';
  13078. /**
  13079. * TSL function for setting up the default clipping logic.
  13080. *
  13081. * @tsl
  13082. * @function
  13083. * @returns {ClippingNode}
  13084. */
  13085. const clipping = () => nodeObject( new ClippingNode() );
  13086. /**
  13087. * TSL function for setting up alpha to coverage.
  13088. *
  13089. * @tsl
  13090. * @function
  13091. * @returns {ClippingNode}
  13092. */
  13093. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13094. /**
  13095. * TSL function for setting up hardware-based clipping.
  13096. *
  13097. * @tsl
  13098. * @function
  13099. * @returns {ClippingNode}
  13100. */
  13101. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13102. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13103. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13104. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13105. 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 ) ) ) ) ) );
  13106. } );
  13107. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13108. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13109. } );
  13110. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13111. // Find the discretized derivatives of our coordinates
  13112. const maxDeriv = max$1(
  13113. length( dFdx( position.xyz ) ),
  13114. length( dFdy( position.xyz ) )
  13115. );
  13116. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13117. // Find two nearest log-discretized noise scales
  13118. const pixScales = vec2(
  13119. exp2( floor( log2( pixScale ) ) ),
  13120. exp2( ceil( log2( pixScale ) ) )
  13121. );
  13122. // Compute alpha thresholds at our two noise scales
  13123. const alpha = vec2(
  13124. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13125. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13126. );
  13127. // Factor to interpolate lerp with
  13128. const lerpFactor = fract( log2( pixScale ) );
  13129. // Interpolate alpha threshold from noise at two scales
  13130. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13131. // Pass into CDF to compute uniformly distrib threshold
  13132. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13133. const cases = vec3(
  13134. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13135. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13136. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13137. // Find our final, uniformly distributed alpha threshold (ατ)
  13138. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13139. // Avoids ατ == 0. Could also do ατ =1-ατ
  13140. return clamp( threshold, 1.0e-6, 1.0 );
  13141. } ).setLayout( {
  13142. name: 'getAlphaHashThreshold',
  13143. type: 'float',
  13144. inputs: [
  13145. { name: 'position', type: 'vec3' }
  13146. ]
  13147. } );
  13148. /**
  13149. * An attribute node for representing vertex colors.
  13150. *
  13151. * @augments AttributeNode
  13152. */
  13153. class VertexColorNode extends AttributeNode {
  13154. static get type() {
  13155. return 'VertexColorNode';
  13156. }
  13157. /**
  13158. * Constructs a new vertex color node.
  13159. *
  13160. * @param {number} index - The attribute index.
  13161. */
  13162. constructor( index ) {
  13163. super( null, 'vec4' );
  13164. /**
  13165. * This flag can be used for type testing.
  13166. *
  13167. * @type {boolean}
  13168. * @readonly
  13169. * @default true
  13170. */
  13171. this.isVertexColorNode = true;
  13172. /**
  13173. * The attribute index to enable more than one sets of vertex colors.
  13174. *
  13175. * @type {number}
  13176. * @default 0
  13177. */
  13178. this.index = index;
  13179. }
  13180. /**
  13181. * Overwrites the default implementation by honoring the attribute index.
  13182. *
  13183. * @param {NodeBuilder} builder - The current node builder.
  13184. * @return {string} The attribute name.
  13185. */
  13186. getAttributeName( /*builder*/ ) {
  13187. const index = this.index;
  13188. return 'color' + ( index > 0 ? index : '' );
  13189. }
  13190. generate( builder ) {
  13191. const attributeName = this.getAttributeName( builder );
  13192. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13193. let result;
  13194. if ( geometryAttribute === true ) {
  13195. result = super.generate( builder );
  13196. } else {
  13197. // Vertex color fallback should be white
  13198. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13199. }
  13200. return result;
  13201. }
  13202. serialize( data ) {
  13203. super.serialize( data );
  13204. data.index = this.index;
  13205. }
  13206. deserialize( data ) {
  13207. super.deserialize( data );
  13208. this.index = data.index;
  13209. }
  13210. }
  13211. /**
  13212. * TSL function for creating a reference node.
  13213. *
  13214. * @tsl
  13215. * @function
  13216. * @param {number} [index=0] - The attribute index.
  13217. * @returns {VertexColorNode}
  13218. */
  13219. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13220. /**
  13221. * Represents a "Color Burn" blend mode.
  13222. *
  13223. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13224. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13225. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13226. *
  13227. * @tsl
  13228. * @function
  13229. * @param {Node<vec3>} base - The base color.
  13230. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13231. * @return {Node<vec3>} The result.
  13232. */
  13233. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13234. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13235. } ).setLayout( {
  13236. name: 'blendBurn',
  13237. type: 'vec3',
  13238. inputs: [
  13239. { name: 'base', type: 'vec3' },
  13240. { name: 'blend', type: 'vec3' }
  13241. ]
  13242. } );
  13243. /**
  13244. * Represents a "Color Dodge" blend mode.
  13245. *
  13246. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13247. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13248. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13249. *
  13250. * @tsl
  13251. * @function
  13252. * @param {Node<vec3>} base - The base color.
  13253. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13254. * @return {Node<vec3>} The result.
  13255. */
  13256. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13257. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13258. } ).setLayout( {
  13259. name: 'blendDodge',
  13260. type: 'vec3',
  13261. inputs: [
  13262. { name: 'base', type: 'vec3' },
  13263. { name: 'blend', type: 'vec3' }
  13264. ]
  13265. } );
  13266. /**
  13267. * Represents a "Screen" blend mode.
  13268. *
  13269. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13270. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13271. * effects.
  13272. *
  13273. * @tsl
  13274. * @function
  13275. * @param {Node<vec3>} base - The base color.
  13276. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13277. * @return {Node<vec3>} The result.
  13278. */
  13279. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13280. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13281. } ).setLayout( {
  13282. name: 'blendScreen',
  13283. type: 'vec3',
  13284. inputs: [
  13285. { name: 'base', type: 'vec3' },
  13286. { name: 'blend', type: 'vec3' }
  13287. ]
  13288. } );
  13289. /**
  13290. * Represents a "Overlay" blend mode.
  13291. *
  13292. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13293. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13294. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13295. *
  13296. * @tsl
  13297. * @function
  13298. * @param {Node<vec3>} base - The base color.
  13299. * @param {Node<vec3>} blend - The blend color
  13300. * @return {Node<vec3>} The result.
  13301. */
  13302. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13303. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13304. } ).setLayout( {
  13305. name: 'blendOverlay',
  13306. type: 'vec3',
  13307. inputs: [
  13308. { name: 'base', type: 'vec3' },
  13309. { name: 'blend', type: 'vec3' }
  13310. ]
  13311. } );
  13312. /**
  13313. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13314. * It assumes both input colors have non-premultiplied alpha.
  13315. *
  13316. * @tsl
  13317. * @function
  13318. * @param {Node<vec4>} base - The base color.
  13319. * @param {Node<vec4>} blend - The blend color
  13320. * @return {Node<vec4>} The result.
  13321. */
  13322. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13323. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13324. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13325. } ).setLayout( {
  13326. name: 'blendColor',
  13327. type: 'vec4',
  13328. inputs: [
  13329. { name: 'base', type: 'vec4' },
  13330. { name: 'blend', type: 'vec4' }
  13331. ]
  13332. } );
  13333. /**
  13334. * Premultiplies the RGB channels of a color by its alpha channel.
  13335. *
  13336. * This function is useful for converting a non-premultiplied alpha color
  13337. * into a premultiplied alpha format, where the RGB values are scaled
  13338. * by the alpha value. Premultiplied alpha is often used in graphics
  13339. * rendering for certain operations, such as compositing and image processing.
  13340. *
  13341. * @tsl
  13342. * @function
  13343. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13344. * @return {Node<vec4>} The color with premultiplied alpha.
  13345. */
  13346. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13347. return vec4( color.rgb.mul( color.a ), color.a );
  13348. }, { color: 'vec4', return: 'vec4' } );
  13349. /**
  13350. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13351. *
  13352. * This function is useful for converting a premultiplied alpha color
  13353. * back into a non-premultiplied alpha format, where the RGB values are
  13354. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13355. * rendering for certain operations, such as compositing and image processing.
  13356. *
  13357. * @tsl
  13358. * @function
  13359. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13360. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13361. */
  13362. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13363. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13364. return vec4( color.rgb.div( color.a ), color.a );
  13365. }, { color: 'vec4', return: 'vec4' } );
  13366. // Deprecated
  13367. /**
  13368. * @tsl
  13369. * @function
  13370. * @deprecated since r171. Use {@link blendBurn} instead.
  13371. *
  13372. * @param {...any} params
  13373. * @returns {Function}
  13374. */
  13375. const burn = ( ...params ) => { // @deprecated, r171
  13376. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13377. return blendBurn( params );
  13378. };
  13379. /**
  13380. * @tsl
  13381. * @function
  13382. * @deprecated since r171. Use {@link blendDodge} instead.
  13383. *
  13384. * @param {...any} params
  13385. * @returns {Function}
  13386. */
  13387. const dodge = ( ...params ) => { // @deprecated, r171
  13388. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13389. return blendDodge( params );
  13390. };
  13391. /**
  13392. * @tsl
  13393. * @function
  13394. * @deprecated since r171. Use {@link blendScreen} instead.
  13395. *
  13396. * @param {...any} params
  13397. * @returns {Function}
  13398. */
  13399. const screen = ( ...params ) => { // @deprecated, r171
  13400. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13401. return blendScreen( params );
  13402. };
  13403. /**
  13404. * @tsl
  13405. * @function
  13406. * @deprecated since r171. Use {@link blendOverlay} instead.
  13407. *
  13408. * @param {...any} params
  13409. * @returns {Function}
  13410. */
  13411. const overlay = ( ...params ) => { // @deprecated, r171
  13412. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13413. return blendOverlay( params );
  13414. };
  13415. /**
  13416. * Base class for all node materials.
  13417. *
  13418. * @augments Material
  13419. */
  13420. class NodeMaterial extends Material {
  13421. static get type() {
  13422. return 'NodeMaterial';
  13423. }
  13424. /**
  13425. * Represents the type of the node material.
  13426. *
  13427. * @type {string}
  13428. */
  13429. get type() {
  13430. return this.constructor.type;
  13431. }
  13432. set type( _value ) { /* */ }
  13433. /**
  13434. * Constructs a new node material.
  13435. */
  13436. constructor() {
  13437. super();
  13438. /**
  13439. * This flag can be used for type testing.
  13440. *
  13441. * @type {boolean}
  13442. * @readonly
  13443. * @default true
  13444. */
  13445. this.isNodeMaterial = true;
  13446. /**
  13447. * Whether this material is affected by fog or not.
  13448. *
  13449. * @type {boolean}
  13450. * @default true
  13451. */
  13452. this.fog = true;
  13453. /**
  13454. * Whether this material is affected by lights or not.
  13455. *
  13456. * @type {boolean}
  13457. * @default false
  13458. */
  13459. this.lights = false;
  13460. /**
  13461. * Whether this material uses hardware clipping or not.
  13462. * This property is managed by the engine and should not be
  13463. * modified by apps.
  13464. *
  13465. * @type {boolean}
  13466. * @default false
  13467. */
  13468. this.hardwareClipping = false;
  13469. /**
  13470. * Node materials which set their `lights` property to `true`
  13471. * are affected by all lights of the scene. Sometimes selective
  13472. * lighting is wanted which means only _some_ lights in the scene
  13473. * affect a material. This can be achieved by creating an instance
  13474. * of {@link LightsNode} with a list of selective
  13475. * lights and assign the node to this property.
  13476. *
  13477. * ```js
  13478. * const customLightsNode = lights( [ light1, light2 ] );
  13479. * material.lightsNode = customLightsNode;
  13480. * ```
  13481. *
  13482. * @type {?LightsNode}
  13483. * @default null
  13484. */
  13485. this.lightsNode = null;
  13486. /**
  13487. * The environment of node materials can be defined by an environment
  13488. * map assigned to the `envMap` property or by `Scene.environment`
  13489. * if the node material is a PBR material. This node property allows to overwrite
  13490. * the default behavior and define the environment with a custom node.
  13491. *
  13492. * ```js
  13493. * material.envNode = pmremTexture( renderTarget.texture );
  13494. * ```
  13495. *
  13496. * @type {?Node<vec3>}
  13497. * @default null
  13498. */
  13499. this.envNode = null;
  13500. /**
  13501. * The lighting of node materials might be influenced by ambient occlusion.
  13502. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13503. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13504. * the default and define the ambient occlusion with a custom node instead.
  13505. *
  13506. * If you don't want to overwrite the diffuse color but modify the existing
  13507. * values instead, use {@link materialAO}.
  13508. *
  13509. * @type {?Node<float>}
  13510. * @default null
  13511. */
  13512. this.aoNode = null;
  13513. /**
  13514. * The diffuse color of node materials is by default inferred from the
  13515. * `color` and `map` properties. This node property allows to overwrite the default
  13516. * and define the diffuse color with a node instead.
  13517. *
  13518. * ```js
  13519. * material.colorNode = color( 0xff0000 ); // define red color
  13520. * ```
  13521. *
  13522. * If you don't want to overwrite the diffuse color but modify the existing
  13523. * values instead, use {@link materialColor}.
  13524. *
  13525. * ```js
  13526. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  13527. * ```
  13528. *
  13529. * @type {?Node<vec3>}
  13530. * @default null
  13531. */
  13532. this.colorNode = null;
  13533. /**
  13534. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  13535. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  13536. * and define the normals with a node instead.
  13537. *
  13538. * If you don't want to overwrite the normals but modify the existing values instead,
  13539. * use {@link materialNormal}.
  13540. *
  13541. * @type {?Node<vec3>}
  13542. * @default null
  13543. */
  13544. this.normalNode = null;
  13545. /**
  13546. * The opacity of node materials is by default inferred from the `opacity`
  13547. * and `alphaMap` properties. This node property allows to overwrite the default
  13548. * and define the opacity with a node instead.
  13549. *
  13550. * If you don't want to overwrite the normals but modify the existing
  13551. * value instead, use {@link materialOpacity}.
  13552. *
  13553. * @type {?Node<float>}
  13554. * @default null
  13555. */
  13556. this.opacityNode = null;
  13557. /**
  13558. * This node can be used to implement a variety of filter-like effects. The idea is
  13559. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  13560. * to create an arbitrary effect and then assign the node composition to this property.
  13561. * Everything behind the object using this material will now be affected by a filter.
  13562. *
  13563. * ```js
  13564. * const material = new NodeMaterial()
  13565. * material.transparent = true;
  13566. *
  13567. * // everything behind the object will be monochromatic
  13568. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  13569. * ```
  13570. *
  13571. * Backdrop computations are part of the lighting so only lit materials can use this property.
  13572. *
  13573. * @type {?Node<vec3>}
  13574. * @default null
  13575. */
  13576. this.backdropNode = null;
  13577. /**
  13578. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  13579. *
  13580. * @type {?Node<float>}
  13581. * @default null
  13582. */
  13583. this.backdropAlphaNode = null;
  13584. /**
  13585. * The alpha test of node materials is by default inferred from the `alphaTest`
  13586. * property. This node property allows to overwrite the default and define the
  13587. * alpha test with a node instead.
  13588. *
  13589. * If you don't want to overwrite the alpha test but modify the existing
  13590. * value instead, use {@link materialAlphaTest}.
  13591. *
  13592. * @type {?Node<float>}
  13593. * @default null
  13594. */
  13595. this.alphaTestNode = null;
  13596. /**
  13597. * Discards the fragment if the mask value is `false`.
  13598. *
  13599. * @type {?Node<bool>}
  13600. * @default null
  13601. */
  13602. this.maskNode = null;
  13603. /**
  13604. * The local vertex positions are computed based on multiple factors like the
  13605. * attribute data, morphing or skinning. This node property allows to overwrite
  13606. * the default and define local vertex positions with nodes instead.
  13607. *
  13608. * If you don't want to overwrite the vertex positions but modify the existing
  13609. * values instead, use {@link positionLocal}.
  13610. *
  13611. *```js
  13612. * material.positionNode = positionLocal.add( displace );
  13613. * ```
  13614. *
  13615. * @type {?Node<vec3>}
  13616. * @default null
  13617. */
  13618. this.positionNode = null;
  13619. /**
  13620. * This node property is intended for logic which modifies geometry data once or per animation step.
  13621. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  13622. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  13623. * can be implemented.
  13624. *
  13625. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  13626. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  13627. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  13628. * eventually assigned to `geometryNode`.
  13629. *
  13630. * @type {?Function}
  13631. * @default null
  13632. */
  13633. this.geometryNode = null;
  13634. /**
  13635. * Allows to overwrite depth values in the fragment shader.
  13636. *
  13637. * @type {?Node<float>}
  13638. * @default null
  13639. */
  13640. this.depthNode = null;
  13641. /**
  13642. * Allows to overwrite the position used for shadow map rendering which
  13643. * is by default {@link positionWorld}, the vertex position
  13644. * in world space.
  13645. *
  13646. * @type {?Node<float>}
  13647. * @default null
  13648. */
  13649. this.receivedShadowPositionNode = null;
  13650. /**
  13651. * Allows to overwrite the geometry position used for shadow map projection which
  13652. * is by default {@link positionLocal}, the vertex position in local space.
  13653. *
  13654. * @type {?Node<float>}
  13655. * @default null
  13656. */
  13657. this.castShadowPositionNode = null;
  13658. /**
  13659. * This node can be used to influence how an object using this node material
  13660. * receive shadows.
  13661. *
  13662. * ```js
  13663. * const totalShadows = float( 1 ).toVar();
  13664. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  13665. * totalShadows.mulAssign( shadow );
  13666. * //return float( 1 ); // bypass received shadows
  13667. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  13668. * } );
  13669. *
  13670. * @type {?(Function|FunctionNode<vec4>)}
  13671. * @default null
  13672. */
  13673. this.receivedShadowNode = null;
  13674. /**
  13675. * This node can be used to influence how an object using this node material
  13676. * casts shadows. To apply a color to shadows, you can simply do:
  13677. *
  13678. * ```js
  13679. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  13680. * ```
  13681. *
  13682. * Which can be nice to fake colored shadows of semi-transparent objects. It
  13683. * is also common to use the property with `Fn` function so checks are performed
  13684. * per fragment.
  13685. *
  13686. * ```js
  13687. * materialCustomShadow.castShadowNode = Fn( () => {
  13688. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  13689. * return materialColor;
  13690. * } )();
  13691. * ```
  13692. *
  13693. * @type {?Node<vec4>}
  13694. * @default null
  13695. */
  13696. this.castShadowNode = null;
  13697. /**
  13698. * This node can be used to define the final output of the material.
  13699. *
  13700. * TODO: Explain the differences to `fragmentNode`.
  13701. *
  13702. * @type {?Node<vec4>}
  13703. * @default null
  13704. */
  13705. this.outputNode = null;
  13706. /**
  13707. * MRT configuration is done on renderer or pass level. This node allows to
  13708. * overwrite what values are written into MRT targets on material level. This
  13709. * can be useful for implementing selective FX features that should only affect
  13710. * specific objects.
  13711. *
  13712. * @type {?MRTNode}
  13713. * @default null
  13714. */
  13715. this.mrtNode = null;
  13716. /**
  13717. * This node property can be used if you need complete freedom in implementing
  13718. * the fragment shader. Assigning a node will replace the built-in material
  13719. * logic used in the fragment stage.
  13720. *
  13721. * @type {?Node<vec4>}
  13722. * @default null
  13723. */
  13724. this.fragmentNode = null;
  13725. /**
  13726. * This node property can be used if you need complete freedom in implementing
  13727. * the vertex shader. Assigning a node will replace the built-in material logic
  13728. * used in the vertex stage.
  13729. *
  13730. * @type {?Node<vec4>}
  13731. * @default null
  13732. */
  13733. this.vertexNode = null;
  13734. // Deprecated properties
  13735. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  13736. get: () => {
  13737. return this.receivedShadowPositionNode;
  13738. },
  13739. set: ( value ) => {
  13740. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  13741. this.receivedShadowPositionNode = value;
  13742. }
  13743. } );
  13744. }
  13745. /**
  13746. * Allows to define a custom cache key that influence the material key computation
  13747. * for render objects.
  13748. *
  13749. * @return {string} The custom cache key.
  13750. */
  13751. customProgramCacheKey() {
  13752. return this.type + getCacheKey$1( this );
  13753. }
  13754. /**
  13755. * Builds this material with the given node builder.
  13756. *
  13757. * @param {NodeBuilder} builder - The current node builder.
  13758. */
  13759. build( builder ) {
  13760. this.setup( builder );
  13761. }
  13762. /**
  13763. * Setups a node material observer with the given builder.
  13764. *
  13765. * @param {NodeBuilder} builder - The current node builder.
  13766. * @return {NodeMaterialObserver} The node material observer.
  13767. */
  13768. setupObserver( builder ) {
  13769. return new NodeMaterialObserver( builder );
  13770. }
  13771. /**
  13772. * Setups the vertex and fragment stage of this node material.
  13773. *
  13774. * @param {NodeBuilder} builder - The current node builder.
  13775. */
  13776. setup( builder ) {
  13777. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  13778. builder.context.setupPositionView = () => this.setupPositionView( builder );
  13779. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  13780. const renderer = builder.renderer;
  13781. const renderTarget = renderer.getRenderTarget();
  13782. // < VERTEX STAGE >
  13783. builder.addStack();
  13784. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  13785. const vertexNode = this.vertexNode || mvp;
  13786. builder.stack.outputNode = vertexNode;
  13787. this.setupHardwareClipping( builder );
  13788. if ( this.geometryNode !== null ) {
  13789. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  13790. }
  13791. builder.addFlow( 'vertex', builder.removeStack() );
  13792. // < FRAGMENT STAGE >
  13793. builder.addStack();
  13794. let resultNode;
  13795. const clippingNode = this.setupClipping( builder );
  13796. if ( this.depthWrite === true || this.depthTest === true ) {
  13797. // only write depth if depth buffer is configured
  13798. if ( renderTarget !== null ) {
  13799. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  13800. } else {
  13801. if ( renderer.depth === true ) this.setupDepth( builder );
  13802. }
  13803. }
  13804. if ( this.fragmentNode === null ) {
  13805. this.setupDiffuseColor( builder );
  13806. this.setupVariants( builder );
  13807. const outgoingLightNode = this.setupLighting( builder );
  13808. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  13809. // force unsigned floats - useful for RenderTargets
  13810. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  13811. resultNode = this.setupOutput( builder, basicOutput );
  13812. // OUTPUT NODE
  13813. output.assign( resultNode );
  13814. //
  13815. const isCustomOutput = this.outputNode !== null;
  13816. if ( isCustomOutput ) resultNode = this.outputNode;
  13817. // MRT
  13818. if ( renderTarget !== null ) {
  13819. const mrt = renderer.getMRT();
  13820. const materialMRT = this.mrtNode;
  13821. if ( mrt !== null ) {
  13822. if ( isCustomOutput ) output.assign( resultNode );
  13823. resultNode = mrt;
  13824. if ( materialMRT !== null ) {
  13825. resultNode = mrt.merge( materialMRT );
  13826. }
  13827. } else if ( materialMRT !== null ) {
  13828. resultNode = materialMRT;
  13829. }
  13830. }
  13831. } else {
  13832. let fragmentNode = this.fragmentNode;
  13833. if ( fragmentNode.isOutputStructNode !== true ) {
  13834. fragmentNode = vec4( fragmentNode );
  13835. }
  13836. resultNode = this.setupOutput( builder, fragmentNode );
  13837. }
  13838. builder.stack.outputNode = resultNode;
  13839. builder.addFlow( 'fragment', builder.removeStack() );
  13840. // < OBSERVER >
  13841. builder.observer = this.setupObserver( builder );
  13842. }
  13843. /**
  13844. * Setups the clipping node.
  13845. *
  13846. * @param {NodeBuilder} builder - The current node builder.
  13847. * @return {ClippingNode} The clipping node.
  13848. */
  13849. setupClipping( builder ) {
  13850. if ( builder.clippingContext === null ) return null;
  13851. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  13852. let result = null;
  13853. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  13854. const samples = builder.renderer.samples;
  13855. if ( this.alphaToCoverage && samples > 1 ) {
  13856. // to be added to flow when the color/alpha value has been determined
  13857. result = clippingAlpha();
  13858. } else {
  13859. builder.stack.add( clipping() );
  13860. }
  13861. }
  13862. return result;
  13863. }
  13864. /**
  13865. * Setups the hardware clipping if available on the current device.
  13866. *
  13867. * @param {NodeBuilder} builder - The current node builder.
  13868. */
  13869. setupHardwareClipping( builder ) {
  13870. this.hardwareClipping = false;
  13871. if ( builder.clippingContext === null ) return;
  13872. const candidateCount = builder.clippingContext.unionPlanes.length;
  13873. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  13874. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  13875. builder.stack.add( hardwareClipping() );
  13876. this.hardwareClipping = true;
  13877. }
  13878. return;
  13879. }
  13880. /**
  13881. * Setups the depth of this material.
  13882. *
  13883. * @param {NodeBuilder} builder - The current node builder.
  13884. */
  13885. setupDepth( builder ) {
  13886. const { renderer, camera } = builder;
  13887. // Depth
  13888. let depthNode = this.depthNode;
  13889. if ( depthNode === null ) {
  13890. const mrt = renderer.getMRT();
  13891. if ( mrt && mrt.has( 'depth' ) ) {
  13892. depthNode = mrt.get( 'depth' );
  13893. } else if ( renderer.logarithmicDepthBuffer === true ) {
  13894. if ( camera.isPerspectiveCamera ) {
  13895. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  13896. } else {
  13897. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13898. }
  13899. }
  13900. }
  13901. if ( depthNode !== null ) {
  13902. depth.assign( depthNode ).toStack();
  13903. }
  13904. }
  13905. /**
  13906. * Setups the position node in view space. This method exists
  13907. * so derived node materials can modify the implementation e.g. sprite materials.
  13908. *
  13909. * @param {NodeBuilder} builder - The current node builder.
  13910. * @return {Node<vec3>} The position in view space.
  13911. */
  13912. setupPositionView( /*builder*/ ) {
  13913. return modelViewMatrix.mul( positionLocal ).xyz;
  13914. }
  13915. /**
  13916. * Setups the position in clip space.
  13917. *
  13918. * @param {NodeBuilder} builder - The current node builder.
  13919. * @return {Node<vec4>} The position in view space.
  13920. */
  13921. setupModelViewProjection( /*builder*/ ) {
  13922. return cameraProjectionMatrix.mul( positionView );
  13923. }
  13924. /**
  13925. * Setups the logic for the vertex stage.
  13926. *
  13927. * @param {NodeBuilder} builder - The current node builder.
  13928. * @return {Node<vec4>} The position in clip space.
  13929. */
  13930. setupVertex( builder ) {
  13931. builder.addStack();
  13932. this.setupPosition( builder );
  13933. builder.context.vertex = builder.removeStack();
  13934. return modelViewProjection;
  13935. }
  13936. /**
  13937. * Setups the computation of the position in local space.
  13938. *
  13939. * @param {NodeBuilder} builder - The current node builder.
  13940. * @return {Node<vec3>} The position in local space.
  13941. */
  13942. setupPosition( builder ) {
  13943. const { object, geometry } = builder;
  13944. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  13945. morphReference( object ).toStack();
  13946. }
  13947. if ( object.isSkinnedMesh === true ) {
  13948. skinning( object ).toStack();
  13949. }
  13950. if ( this.displacementMap ) {
  13951. const displacementMap = materialReference( 'displacementMap', 'texture' );
  13952. const displacementScale = materialReference( 'displacementScale', 'float' );
  13953. const displacementBias = materialReference( 'displacementBias', 'float' );
  13954. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  13955. }
  13956. if ( object.isBatchedMesh ) {
  13957. batch( object ).toStack();
  13958. }
  13959. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  13960. instancedMesh( object ).toStack();
  13961. }
  13962. if ( this.positionNode !== null ) {
  13963. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  13964. }
  13965. return positionLocal;
  13966. }
  13967. /**
  13968. * Setups the computation of the material's diffuse color.
  13969. *
  13970. * @param {NodeBuilder} builder - The current node builder.
  13971. * @param {BufferGeometry} geometry - The geometry.
  13972. */
  13973. setupDiffuseColor( { object, geometry } ) {
  13974. // MASK
  13975. if ( this.maskNode !== null ) {
  13976. // Discard if the mask is `false`
  13977. bool( this.maskNode ).not().discard();
  13978. }
  13979. // COLOR
  13980. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  13981. // VERTEX COLORS
  13982. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  13983. colorNode = colorNode.mul( vertexColor() );
  13984. }
  13985. // INSTANCED COLORS
  13986. if ( object.instanceColor ) {
  13987. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  13988. colorNode = instanceColor.mul( colorNode );
  13989. }
  13990. if ( object.isBatchedMesh && object._colorsTexture ) {
  13991. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  13992. colorNode = batchColor.mul( colorNode );
  13993. }
  13994. // DIFFUSE COLOR
  13995. diffuseColor.assign( colorNode );
  13996. // OPACITY
  13997. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13998. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  13999. // ALPHA TEST
  14000. let alphaTestNode = null;
  14001. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14002. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14003. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14004. }
  14005. // ALPHA HASH
  14006. if ( this.alphaHash === true ) {
  14007. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14008. }
  14009. // OPAQUE
  14010. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  14011. if ( isOpaque ) {
  14012. diffuseColor.a.assign( 1.0 );
  14013. } else if ( alphaTestNode === null ) {
  14014. diffuseColor.a.lessThanEqual( 0 ).discard();
  14015. }
  14016. }
  14017. /**
  14018. * Abstract interface method that can be implemented by derived materials
  14019. * to setup material-specific node variables.
  14020. *
  14021. * @abstract
  14022. * @param {NodeBuilder} builder - The current node builder.
  14023. */
  14024. setupVariants( /*builder*/ ) {
  14025. // Interface function.
  14026. }
  14027. /**
  14028. * Setups the outgoing light node variable
  14029. *
  14030. * @return {Node<vec3>} The outgoing light node.
  14031. */
  14032. setupOutgoingLight() {
  14033. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14034. }
  14035. /**
  14036. * Setups the normal node from the material.
  14037. *
  14038. * @return {Node<vec3>} The normal node.
  14039. */
  14040. setupNormal() {
  14041. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14042. }
  14043. /**
  14044. * Setups the environment node from the material.
  14045. *
  14046. * @param {NodeBuilder} builder - The current node builder.
  14047. * @return {Node<vec4>} The environment node.
  14048. */
  14049. setupEnvironment( /*builder*/ ) {
  14050. let node = null;
  14051. if ( this.envNode ) {
  14052. node = this.envNode;
  14053. } else if ( this.envMap ) {
  14054. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14055. }
  14056. return node;
  14057. }
  14058. /**
  14059. * Setups the light map node from the material.
  14060. *
  14061. * @param {NodeBuilder} builder - The current node builder.
  14062. * @return {Node<vec3>} The light map node.
  14063. */
  14064. setupLightMap( builder ) {
  14065. let node = null;
  14066. if ( builder.material.lightMap ) {
  14067. node = new IrradianceNode( materialLightMap );
  14068. }
  14069. return node;
  14070. }
  14071. /**
  14072. * Setups the lights node based on the scene, environment and material.
  14073. *
  14074. * @param {NodeBuilder} builder - The current node builder.
  14075. * @return {LightsNode} The lights node.
  14076. */
  14077. setupLights( builder ) {
  14078. const materialLightsNode = [];
  14079. //
  14080. const envNode = this.setupEnvironment( builder );
  14081. if ( envNode && envNode.isLightingNode ) {
  14082. materialLightsNode.push( envNode );
  14083. }
  14084. const lightMapNode = this.setupLightMap( builder );
  14085. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14086. materialLightsNode.push( lightMapNode );
  14087. }
  14088. if ( this.aoNode !== null || builder.material.aoMap ) {
  14089. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14090. materialLightsNode.push( new AONode( aoNode ) );
  14091. }
  14092. let lightsN = this.lightsNode || builder.lightsNode;
  14093. if ( materialLightsNode.length > 0 ) {
  14094. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14095. }
  14096. return lightsN;
  14097. }
  14098. /**
  14099. * This method should be implemented by most derived materials
  14100. * since it defines the material's lighting model.
  14101. *
  14102. * @abstract
  14103. * @param {NodeBuilder} builder - The current node builder.
  14104. * @return {LightingModel} The lighting model.
  14105. */
  14106. setupLightingModel( /*builder*/ ) {
  14107. // Interface function.
  14108. }
  14109. /**
  14110. * Setups the outgoing light node.
  14111. *
  14112. * @param {NodeBuilder} builder - The current node builder.
  14113. * @return {Node<vec3>} The outgoing light node.
  14114. */
  14115. setupLighting( builder ) {
  14116. const { material } = builder;
  14117. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14118. // OUTGOING LIGHT
  14119. const lights = this.lights === true || this.lightsNode !== null;
  14120. const lightsNode = lights ? this.setupLights( builder ) : null;
  14121. let outgoingLightNode = this.setupOutgoingLight( builder );
  14122. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14123. const lightingModel = this.setupLightingModel( builder ) || null;
  14124. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14125. } else if ( backdropNode !== null ) {
  14126. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14127. }
  14128. // EMISSIVE
  14129. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14130. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14131. outgoingLightNode = outgoingLightNode.add( emissive );
  14132. }
  14133. return outgoingLightNode;
  14134. }
  14135. /**
  14136. * Setup the fog.
  14137. *
  14138. * @param {NodeBuilder} builder - The current node builder.
  14139. * @param {Node<vec4>} outputNode - The existing output node.
  14140. * @return {Node<vec4>} The output node.
  14141. */
  14142. setupFog( builder, outputNode ) {
  14143. const fogNode = builder.fogNode;
  14144. if ( fogNode ) {
  14145. output.assign( outputNode );
  14146. outputNode = vec4( fogNode.toVar() );
  14147. }
  14148. return outputNode;
  14149. }
  14150. /**
  14151. * Setups premultiplied alpha.
  14152. *
  14153. * @param {NodeBuilder} builder - The current node builder.
  14154. * @param {Node<vec4>} outputNode - The existing output node.
  14155. * @return {Node<vec4>} The output node.
  14156. */
  14157. setupPremultipliedAlpha( builder, outputNode ) {
  14158. return premultiplyAlpha( outputNode );
  14159. }
  14160. /**
  14161. * Setups the output node.
  14162. *
  14163. * @param {NodeBuilder} builder - The current node builder.
  14164. * @param {Node<vec4>} outputNode - The existing output node.
  14165. * @return {Node<vec4>} The output node.
  14166. */
  14167. setupOutput( builder, outputNode ) {
  14168. // FOG
  14169. if ( this.fog === true ) {
  14170. outputNode = this.setupFog( builder, outputNode );
  14171. }
  14172. // PREMULTIPLIED ALPHA
  14173. if ( this.premultipliedAlpha === true ) {
  14174. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14175. }
  14176. return outputNode;
  14177. }
  14178. /**
  14179. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14180. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14181. * defining all material properties of the classic type in the node type.
  14182. *
  14183. * @param {Material} material - The material to copy properties with their values to this node material.
  14184. */
  14185. setDefaultValues( material ) {
  14186. // This approach is to reuse the native refreshUniforms*
  14187. // and turn available the use of features like transmission and environment in core
  14188. for ( const property in material ) {
  14189. const value = material[ property ];
  14190. if ( this[ property ] === undefined ) {
  14191. this[ property ] = value;
  14192. if ( value && value.clone ) this[ property ] = value.clone();
  14193. }
  14194. }
  14195. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14196. for ( const key in descriptors ) {
  14197. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14198. descriptors[ key ].get !== undefined ) {
  14199. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14200. }
  14201. }
  14202. }
  14203. /**
  14204. * Serializes this material to JSON.
  14205. *
  14206. * @param {?(Object|string)} meta - The meta information for serialization.
  14207. * @return {Object} The serialized node.
  14208. */
  14209. toJSON( meta ) {
  14210. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14211. if ( isRoot ) {
  14212. meta = {
  14213. textures: {},
  14214. images: {},
  14215. nodes: {}
  14216. };
  14217. }
  14218. const data = Material.prototype.toJSON.call( this, meta );
  14219. const nodeChildren = getNodeChildren( this );
  14220. data.inputNodes = {};
  14221. for ( const { property, childNode } of nodeChildren ) {
  14222. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14223. }
  14224. // TODO: Copied from Object3D.toJSON
  14225. function extractFromCache( cache ) {
  14226. const values = [];
  14227. for ( const key in cache ) {
  14228. const data = cache[ key ];
  14229. delete data.metadata;
  14230. values.push( data );
  14231. }
  14232. return values;
  14233. }
  14234. if ( isRoot ) {
  14235. const textures = extractFromCache( meta.textures );
  14236. const images = extractFromCache( meta.images );
  14237. const nodes = extractFromCache( meta.nodes );
  14238. if ( textures.length > 0 ) data.textures = textures;
  14239. if ( images.length > 0 ) data.images = images;
  14240. if ( nodes.length > 0 ) data.nodes = nodes;
  14241. }
  14242. return data;
  14243. }
  14244. /**
  14245. * Copies the properties of the given node material to this instance.
  14246. *
  14247. * @param {NodeMaterial} source - The material to copy.
  14248. * @return {NodeMaterial} A reference to this node material.
  14249. */
  14250. copy( source ) {
  14251. this.lightsNode = source.lightsNode;
  14252. this.envNode = source.envNode;
  14253. this.colorNode = source.colorNode;
  14254. this.normalNode = source.normalNode;
  14255. this.opacityNode = source.opacityNode;
  14256. this.backdropNode = source.backdropNode;
  14257. this.backdropAlphaNode = source.backdropAlphaNode;
  14258. this.alphaTestNode = source.alphaTestNode;
  14259. this.maskNode = source.maskNode;
  14260. this.positionNode = source.positionNode;
  14261. this.geometryNode = source.geometryNode;
  14262. this.depthNode = source.depthNode;
  14263. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14264. this.castShadowPositionNode = source.castShadowPositionNode;
  14265. this.receivedShadowNode = source.receivedShadowNode;
  14266. this.castShadowNode = source.castShadowNode;
  14267. this.outputNode = source.outputNode;
  14268. this.mrtNode = source.mrtNode;
  14269. this.fragmentNode = source.fragmentNode;
  14270. this.vertexNode = source.vertexNode;
  14271. return super.copy( source );
  14272. }
  14273. }
  14274. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14275. /**
  14276. * Node material version of {@link LineBasicMaterial}.
  14277. *
  14278. * @augments NodeMaterial
  14279. */
  14280. class LineBasicNodeMaterial extends NodeMaterial {
  14281. static get type() {
  14282. return 'LineBasicNodeMaterial';
  14283. }
  14284. /**
  14285. * Constructs a new line basic node material.
  14286. *
  14287. * @param {Object} [parameters] - The configuration parameter.
  14288. */
  14289. constructor( parameters ) {
  14290. super();
  14291. /**
  14292. * This flag can be used for type testing.
  14293. *
  14294. * @type {boolean}
  14295. * @readonly
  14296. * @default true
  14297. */
  14298. this.isLineBasicNodeMaterial = true;
  14299. this.setDefaultValues( _defaultValues$d );
  14300. this.setValues( parameters );
  14301. }
  14302. }
  14303. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14304. /**
  14305. * Node material version of {@link LineDashedMaterial}.
  14306. *
  14307. * @augments NodeMaterial
  14308. */
  14309. class LineDashedNodeMaterial extends NodeMaterial {
  14310. static get type() {
  14311. return 'LineDashedNodeMaterial';
  14312. }
  14313. /**
  14314. * Constructs a new line dashed node material.
  14315. *
  14316. * @param {Object} [parameters] - The configuration parameter.
  14317. */
  14318. constructor( parameters ) {
  14319. super();
  14320. /**
  14321. * This flag can be used for type testing.
  14322. *
  14323. * @type {boolean}
  14324. * @readonly
  14325. * @default true
  14326. */
  14327. this.isLineDashedNodeMaterial = true;
  14328. this.setDefaultValues( _defaultValues$c );
  14329. /**
  14330. * The dash offset.
  14331. *
  14332. * @type {number}
  14333. * @default 0
  14334. */
  14335. this.dashOffset = 0;
  14336. /**
  14337. * The offset of dash materials is by default inferred from the `dashOffset`
  14338. * property. This node property allows to overwrite the default
  14339. * and define the offset with a node instead.
  14340. *
  14341. * If you don't want to overwrite the offset but modify the existing
  14342. * value instead, use {@link materialLineDashOffset}.
  14343. *
  14344. * @type {?Node<float>}
  14345. * @default null
  14346. */
  14347. this.offsetNode = null;
  14348. /**
  14349. * The scale of dash materials is by default inferred from the `scale`
  14350. * property. This node property allows to overwrite the default
  14351. * and define the scale with a node instead.
  14352. *
  14353. * If you don't want to overwrite the scale but modify the existing
  14354. * value instead, use {@link materialLineScale}.
  14355. *
  14356. * @type {?Node<float>}
  14357. * @default null
  14358. */
  14359. this.dashScaleNode = null;
  14360. /**
  14361. * The dash size of dash materials is by default inferred from the `dashSize`
  14362. * property. This node property allows to overwrite the default
  14363. * and define the dash size with a node instead.
  14364. *
  14365. * If you don't want to overwrite the dash size but modify the existing
  14366. * value instead, use {@link materialLineDashSize}.
  14367. *
  14368. * @type {?Node<float>}
  14369. * @default null
  14370. */
  14371. this.dashSizeNode = null;
  14372. /**
  14373. * The gap size of dash materials is by default inferred from the `gapSize`
  14374. * property. This node property allows to overwrite the default
  14375. * and define the gap size with a node instead.
  14376. *
  14377. * If you don't want to overwrite the gap size but modify the existing
  14378. * value instead, use {@link materialLineGapSize}.
  14379. *
  14380. * @type {?Node<float>}
  14381. * @default null
  14382. */
  14383. this.gapSizeNode = null;
  14384. this.setValues( parameters );
  14385. }
  14386. /**
  14387. * Setups the dash specific node variables.
  14388. *
  14389. * @param {NodeBuilder} builder - The current node builder.
  14390. */
  14391. setupVariants( /* builder */ ) {
  14392. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14393. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14394. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14395. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14396. dashSize.assign( dashSizeNode );
  14397. gapSize.assign( gapSizeNode );
  14398. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14399. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14400. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14401. }
  14402. }
  14403. let _sharedFramebuffer = null;
  14404. /**
  14405. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14406. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14407. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14408. *
  14409. * @augments ViewportTextureNode
  14410. */
  14411. class ViewportSharedTextureNode extends ViewportTextureNode {
  14412. static get type() {
  14413. return 'ViewportSharedTextureNode';
  14414. }
  14415. /**
  14416. * Constructs a new viewport shared texture node.
  14417. *
  14418. * @param {Node} [uvNode=screenUV] - The uv node.
  14419. * @param {?Node} [levelNode=null] - The level node.
  14420. */
  14421. constructor( uvNode = screenUV, levelNode = null ) {
  14422. if ( _sharedFramebuffer === null ) {
  14423. _sharedFramebuffer = new FramebufferTexture();
  14424. }
  14425. super( uvNode, levelNode, _sharedFramebuffer );
  14426. }
  14427. /**
  14428. * Overwritten so the method always returns the unique shared
  14429. * framebuffer texture.
  14430. *
  14431. * @return {FramebufferTexture} The shared framebuffer texture.
  14432. */
  14433. getTextureForReference() {
  14434. return _sharedFramebuffer;
  14435. }
  14436. updateReference() {
  14437. return this;
  14438. }
  14439. }
  14440. /**
  14441. * TSL function for creating a shared viewport texture node.
  14442. *
  14443. * @tsl
  14444. * @function
  14445. * @param {?Node} [uvNode=screenUV] - The uv node.
  14446. * @param {?Node} [levelNode=null] - The level node.
  14447. * @returns {ViewportSharedTextureNode}
  14448. */
  14449. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14450. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14451. /**
  14452. * This node material can be used to render lines with a size larger than one
  14453. * by representing them as instanced meshes.
  14454. *
  14455. * @augments NodeMaterial
  14456. */
  14457. class Line2NodeMaterial extends NodeMaterial {
  14458. static get type() {
  14459. return 'Line2NodeMaterial';
  14460. }
  14461. /**
  14462. * Constructs a new node material for wide line rendering.
  14463. *
  14464. * @param {Object} [parameters={}] - The configuration parameter.
  14465. */
  14466. constructor( parameters = {} ) {
  14467. super();
  14468. /**
  14469. * This flag can be used for type testing.
  14470. *
  14471. * @type {boolean}
  14472. * @readonly
  14473. * @default true
  14474. */
  14475. this.isLine2NodeMaterial = true;
  14476. this.setDefaultValues( _defaultValues$b );
  14477. /**
  14478. * Whether vertex colors should be used or not.
  14479. *
  14480. * @type {boolean}
  14481. * @default false
  14482. */
  14483. this.useColor = parameters.vertexColors;
  14484. /**
  14485. * The dash offset.
  14486. *
  14487. * @type {number}
  14488. * @default 0
  14489. */
  14490. this.dashOffset = 0;
  14491. /**
  14492. * Defines the lines color.
  14493. *
  14494. * @type {?Node<vec3>}
  14495. * @default null
  14496. */
  14497. this.lineColorNode = null;
  14498. /**
  14499. * Defines the offset.
  14500. *
  14501. * @type {?Node<float>}
  14502. * @default null
  14503. */
  14504. this.offsetNode = null;
  14505. /**
  14506. * Defines the dash scale.
  14507. *
  14508. * @type {?Node<float>}
  14509. * @default null
  14510. */
  14511. this.dashScaleNode = null;
  14512. /**
  14513. * Defines the dash size.
  14514. *
  14515. * @type {?Node<float>}
  14516. * @default null
  14517. */
  14518. this.dashSizeNode = null;
  14519. /**
  14520. * Defines the gap size.
  14521. *
  14522. * @type {?Node<float>}
  14523. * @default null
  14524. */
  14525. this.gapSizeNode = null;
  14526. /**
  14527. * Blending is set to `NoBlending` since transparency
  14528. * is not supported, yet.
  14529. *
  14530. * @type {number}
  14531. * @default 0
  14532. */
  14533. this.blending = NoBlending;
  14534. this._useDash = parameters.dashed;
  14535. this._useAlphaToCoverage = true;
  14536. this._useWorldUnits = false;
  14537. this.setValues( parameters );
  14538. }
  14539. /**
  14540. * Setups the vertex and fragment stage of this node material.
  14541. *
  14542. * @param {NodeBuilder} builder - The current node builder.
  14543. */
  14544. setup( builder ) {
  14545. const { renderer } = builder;
  14546. const useAlphaToCoverage = this._useAlphaToCoverage;
  14547. const useColor = this.useColor;
  14548. const useDash = this._useDash;
  14549. const useWorldUnits = this._useWorldUnits;
  14550. const trimSegment = Fn( ( { start, end } ) => {
  14551. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  14552. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  14553. const nearEstimate = b.mul( -0.5 ).div( a );
  14554. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  14555. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  14556. } ).setLayout( {
  14557. name: 'trimSegment',
  14558. type: 'vec4',
  14559. inputs: [
  14560. { name: 'start', type: 'vec4' },
  14561. { name: 'end', type: 'vec4' }
  14562. ]
  14563. } );
  14564. this.vertexNode = Fn( () => {
  14565. const instanceStart = attribute( 'instanceStart' );
  14566. const instanceEnd = attribute( 'instanceEnd' );
  14567. // camera space
  14568. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  14569. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  14570. if ( useDash ) {
  14571. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14572. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14573. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  14574. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  14575. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  14576. lineDistance = lineDistance.add( offsetNode );
  14577. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  14578. }
  14579. if ( useWorldUnits ) {
  14580. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  14581. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  14582. }
  14583. const aspect = viewport.z.div( viewport.w );
  14584. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  14585. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  14586. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  14587. // perhaps there is a more elegant solution -- WestLangley
  14588. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  14589. If( perspective, () => {
  14590. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  14591. end.assign( trimSegment( { start: start, end: end } ) );
  14592. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  14593. start.assign( trimSegment( { start: end, end: start } ) );
  14594. } );
  14595. } );
  14596. // clip space
  14597. const clipStart = cameraProjectionMatrix.mul( start );
  14598. const clipEnd = cameraProjectionMatrix.mul( end );
  14599. // ndc space
  14600. const ndcStart = clipStart.xyz.div( clipStart.w );
  14601. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  14602. // direction
  14603. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  14604. // account for clip-space aspect ratio
  14605. dir.x.assign( dir.x.mul( aspect ) );
  14606. dir.assign( dir.normalize() );
  14607. const clip = vec4().toVar();
  14608. if ( useWorldUnits ) {
  14609. // get the offset direction as perpendicular to the view vector
  14610. const worldDir = end.xyz.sub( start.xyz ).normalize();
  14611. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  14612. const worldUp = worldDir.cross( tmpFwd ).normalize();
  14613. const worldFwd = worldDir.cross( worldUp );
  14614. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  14615. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  14616. // height offset
  14617. const hw = materialLineWidth.mul( 0.5 );
  14618. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  14619. // don't extend the line if we're rendering dashes because we
  14620. // won't be rendering the endcaps
  14621. if ( ! useDash ) {
  14622. // cap extension
  14623. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  14624. // add width to the box
  14625. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  14626. // endcaps
  14627. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  14628. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  14629. } );
  14630. }
  14631. // project the worldpos
  14632. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  14633. // shift the depth of the projected points so the line
  14634. // segments overlap neatly
  14635. const clipPose = vec3().toVar();
  14636. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  14637. clip.z.assign( clipPose.z.mul( clip.w ) );
  14638. } else {
  14639. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  14640. // undo aspect ratio adjustment
  14641. dir.x.assign( dir.x.div( aspect ) );
  14642. offset.x.assign( offset.x.div( aspect ) );
  14643. // sign flip
  14644. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  14645. // endcaps
  14646. If( positionGeometry.y.lessThan( 0.0 ), () => {
  14647. offset.assign( offset.sub( dir ) );
  14648. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  14649. offset.assign( offset.add( dir ) );
  14650. } );
  14651. // adjust for linewidth
  14652. offset.assign( offset.mul( materialLineWidth ) );
  14653. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  14654. offset.assign( offset.div( viewport.w ) );
  14655. // select end
  14656. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  14657. // back to clip space
  14658. offset.assign( offset.mul( clip.w ) );
  14659. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  14660. }
  14661. return clip;
  14662. } )();
  14663. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  14664. const p13 = p1.sub( p3 );
  14665. const p43 = p4.sub( p3 );
  14666. const p21 = p2.sub( p1 );
  14667. const d1343 = p13.dot( p43 );
  14668. const d4321 = p43.dot( p21 );
  14669. const d1321 = p13.dot( p21 );
  14670. const d4343 = p43.dot( p43 );
  14671. const d2121 = p21.dot( p21 );
  14672. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  14673. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  14674. const mua = numer.div( denom ).clamp();
  14675. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  14676. return vec2( mua, mub );
  14677. } );
  14678. this.colorNode = Fn( () => {
  14679. const vUv = uv$1();
  14680. if ( useDash ) {
  14681. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14682. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14683. dashSize.assign( dashSizeNode );
  14684. gapSize.assign( gapSizeNode );
  14685. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  14686. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  14687. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  14688. }
  14689. const alpha = float( 1 ).toVar( 'alpha' );
  14690. if ( useWorldUnits ) {
  14691. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  14692. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  14693. // Find the closest points on the view ray and the line segment
  14694. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  14695. const lineDir = worldEnd.sub( worldStart );
  14696. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  14697. const p1 = worldStart.add( lineDir.mul( params.x ) );
  14698. const p2 = rayEnd.mul( params.y );
  14699. const delta = p1.sub( p2 );
  14700. const len = delta.length();
  14701. const norm = len.div( materialLineWidth );
  14702. if ( ! useDash ) {
  14703. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14704. const dnorm = norm.fwidth();
  14705. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  14706. } else {
  14707. norm.greaterThan( 0.5 ).discard();
  14708. }
  14709. }
  14710. } else {
  14711. // round endcaps
  14712. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14713. const a = vUv.x;
  14714. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14715. const len2 = a.mul( a ).add( b.mul( b ) );
  14716. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  14717. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14718. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  14719. } );
  14720. } else {
  14721. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14722. const a = vUv.x;
  14723. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14724. const len2 = a.mul( a ).add( b.mul( b ) );
  14725. len2.greaterThan( 1.0 ).discard();
  14726. } );
  14727. }
  14728. }
  14729. let lineColorNode;
  14730. if ( this.lineColorNode ) {
  14731. lineColorNode = this.lineColorNode;
  14732. } else {
  14733. if ( useColor ) {
  14734. const instanceColorStart = attribute( 'instanceColorStart' );
  14735. const instanceColorEnd = attribute( 'instanceColorEnd' );
  14736. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  14737. lineColorNode = instanceColor.mul( materialColor );
  14738. } else {
  14739. lineColorNode = materialColor;
  14740. }
  14741. }
  14742. return vec4( lineColorNode, alpha );
  14743. } )();
  14744. if ( this.transparent ) {
  14745. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14746. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  14747. }
  14748. super.setup( builder );
  14749. }
  14750. /**
  14751. * Whether the lines should sized in world units or not.
  14752. * When set to `false` the unit is pixel.
  14753. *
  14754. * @type {boolean}
  14755. * @default false
  14756. */
  14757. get worldUnits() {
  14758. return this._useWorldUnits;
  14759. }
  14760. set worldUnits( value ) {
  14761. if ( this._useWorldUnits !== value ) {
  14762. this._useWorldUnits = value;
  14763. this.needsUpdate = true;
  14764. }
  14765. }
  14766. /**
  14767. * Whether the lines should be dashed or not.
  14768. *
  14769. * @type {boolean}
  14770. * @default false
  14771. */
  14772. get dashed() {
  14773. return this._useDash;
  14774. }
  14775. set dashed( value ) {
  14776. if ( this._useDash !== value ) {
  14777. this._useDash = value;
  14778. this.needsUpdate = true;
  14779. }
  14780. }
  14781. /**
  14782. * Whether alpha to coverage should be used or not.
  14783. *
  14784. * @type {boolean}
  14785. * @default true
  14786. */
  14787. get alphaToCoverage() {
  14788. return this._useAlphaToCoverage;
  14789. }
  14790. set alphaToCoverage( value ) {
  14791. if ( this._useAlphaToCoverage !== value ) {
  14792. this._useAlphaToCoverage = value;
  14793. this.needsUpdate = true;
  14794. }
  14795. }
  14796. }
  14797. /**
  14798. * Packs a direction vector into a color value.
  14799. *
  14800. * @tsl
  14801. * @function
  14802. * @param {Node<vec3>} node - The direction to pack.
  14803. * @return {Node<vec3>} The color.
  14804. */
  14805. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  14806. /**
  14807. * Unpacks a color value into a direction vector.
  14808. *
  14809. * @tsl
  14810. * @function
  14811. * @param {Node<vec3>} node - The color to unpack.
  14812. * @return {Node<vec3>} The direction.
  14813. */
  14814. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  14815. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  14816. /**
  14817. * Node material version of {@link MeshNormalMaterial}.
  14818. *
  14819. * @augments NodeMaterial
  14820. */
  14821. class MeshNormalNodeMaterial extends NodeMaterial {
  14822. static get type() {
  14823. return 'MeshNormalNodeMaterial';
  14824. }
  14825. /**
  14826. * Constructs a new mesh normal node material.
  14827. *
  14828. * @param {Object} [parameters] - The configuration parameter.
  14829. */
  14830. constructor( parameters ) {
  14831. super();
  14832. /**
  14833. * This flag can be used for type testing.
  14834. *
  14835. * @type {boolean}
  14836. * @readonly
  14837. * @default true
  14838. */
  14839. this.isMeshNormalNodeMaterial = true;
  14840. this.setDefaultValues( _defaultValues$a );
  14841. this.setValues( parameters );
  14842. }
  14843. /**
  14844. * Overwrites the default implementation by computing the diffuse color
  14845. * based on the normal data.
  14846. */
  14847. setupDiffuseColor() {
  14848. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14849. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  14850. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  14851. }
  14852. }
  14853. /**
  14854. * TSL function for creating an equirect uv node.
  14855. *
  14856. * Can be used to compute texture coordinates for projecting an
  14857. * equirectangular texture onto a mesh for using it as the scene's
  14858. * background.
  14859. *
  14860. * ```js
  14861. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  14862. * ```
  14863. *
  14864. * @tsl
  14865. * @function
  14866. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14867. * @returns {Node<vec2>}
  14868. */
  14869. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  14870. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  14871. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  14872. return vec2( u, v );
  14873. } );
  14874. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  14875. /**
  14876. * This class represents a cube render target. It is a special version
  14877. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  14878. *
  14879. * @augments WebGLCubeRenderTarget
  14880. */
  14881. class CubeRenderTarget extends WebGLCubeRenderTarget {
  14882. /**
  14883. * Constructs a new cube render target.
  14884. *
  14885. * @param {number} [size=1] - The size of the render target.
  14886. * @param {RenderTarget~Options} [options] - The configuration object.
  14887. */
  14888. constructor( size = 1, options = {} ) {
  14889. super( size, options );
  14890. /**
  14891. * This flag can be used for type testing.
  14892. *
  14893. * @type {boolean}
  14894. * @readonly
  14895. * @default true
  14896. */
  14897. this.isCubeRenderTarget = true;
  14898. }
  14899. /**
  14900. * Converts the given equirectangular texture to a cube map.
  14901. *
  14902. * @param {Renderer} renderer - The renderer.
  14903. * @param {Texture} texture - The equirectangular texture.
  14904. * @return {CubeRenderTarget} A reference to this cube render target.
  14905. */
  14906. fromEquirectangularTexture( renderer, texture$1 ) {
  14907. const currentMinFilter = texture$1.minFilter;
  14908. const currentGenerateMipmaps = texture$1.generateMipmaps;
  14909. texture$1.generateMipmaps = true;
  14910. this.texture.type = texture$1.type;
  14911. this.texture.colorSpace = texture$1.colorSpace;
  14912. this.texture.generateMipmaps = texture$1.generateMipmaps;
  14913. this.texture.minFilter = texture$1.minFilter;
  14914. this.texture.magFilter = texture$1.magFilter;
  14915. const geometry = new BoxGeometry( 5, 5, 5 );
  14916. const uvNode = equirectUV( positionWorldDirection );
  14917. const material = new NodeMaterial();
  14918. material.colorNode = texture( texture$1, uvNode, 0 );
  14919. material.side = BackSide;
  14920. material.blending = NoBlending;
  14921. const mesh = new Mesh( geometry, material );
  14922. const scene = new Scene();
  14923. scene.add( mesh );
  14924. // Avoid blurred poles
  14925. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  14926. const camera = new CubeCamera( 1, 10, this );
  14927. const currentMRT = renderer.getMRT();
  14928. renderer.setMRT( null );
  14929. camera.update( renderer, scene );
  14930. renderer.setMRT( currentMRT );
  14931. texture$1.minFilter = currentMinFilter;
  14932. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  14933. mesh.geometry.dispose();
  14934. mesh.material.dispose();
  14935. return this;
  14936. }
  14937. }
  14938. const _cache$1 = new WeakMap();
  14939. /**
  14940. * This node can be used to automatically convert environment maps in the
  14941. * equirectangular format into the cube map format.
  14942. *
  14943. * @augments TempNode
  14944. */
  14945. class CubeMapNode extends TempNode {
  14946. static get type() {
  14947. return 'CubeMapNode';
  14948. }
  14949. /**
  14950. * Constructs a new cube map node.
  14951. *
  14952. * @param {Node} envNode - The node representing the environment map.
  14953. */
  14954. constructor( envNode ) {
  14955. super( 'vec3' );
  14956. /**
  14957. * The node representing the environment map.
  14958. *
  14959. * @type {Node}
  14960. */
  14961. this.envNode = envNode;
  14962. /**
  14963. * A reference to the internal cube texture.
  14964. *
  14965. * @private
  14966. * @type {?CubeTexture}
  14967. * @default null
  14968. */
  14969. this._cubeTexture = null;
  14970. /**
  14971. * A reference to the internal cube texture node.
  14972. *
  14973. * @private
  14974. * @type {CubeTextureNode}
  14975. */
  14976. this._cubeTextureNode = cubeTexture( null );
  14977. const defaultTexture = new CubeTexture();
  14978. defaultTexture.isRenderTargetTexture = true;
  14979. /**
  14980. * A default cube texture that acts as a placeholder.
  14981. * It is used when the conversion from equirectangular to cube
  14982. * map has not finished yet for a given texture.
  14983. *
  14984. * @private
  14985. * @type {CubeTexture}
  14986. */
  14987. this._defaultTexture = defaultTexture;
  14988. /**
  14989. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14990. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  14991. *
  14992. * @type {string}
  14993. * @default 'render'
  14994. */
  14995. this.updateBeforeType = NodeUpdateType.RENDER;
  14996. }
  14997. updateBefore( frame ) {
  14998. const { renderer, material } = frame;
  14999. const envNode = this.envNode;
  15000. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15001. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15002. if ( texture && texture.isTexture ) {
  15003. const mapping = texture.mapping;
  15004. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15005. // check for converted cubemap map
  15006. if ( _cache$1.has( texture ) ) {
  15007. const cubeMap = _cache$1.get( texture );
  15008. mapTextureMapping( cubeMap, texture.mapping );
  15009. this._cubeTexture = cubeMap;
  15010. } else {
  15011. // create cube map from equirectangular map
  15012. const image = texture.image;
  15013. if ( isEquirectangularMapReady$1( image ) ) {
  15014. const renderTarget = new CubeRenderTarget( image.height );
  15015. renderTarget.fromEquirectangularTexture( renderer, texture );
  15016. mapTextureMapping( renderTarget.texture, texture.mapping );
  15017. this._cubeTexture = renderTarget.texture;
  15018. _cache$1.set( texture, renderTarget.texture );
  15019. texture.addEventListener( 'dispose', onTextureDispose );
  15020. } else {
  15021. // default cube texture as fallback when equirectangular texture is not yet loaded
  15022. this._cubeTexture = this._defaultTexture;
  15023. }
  15024. }
  15025. //
  15026. this._cubeTextureNode.value = this._cubeTexture;
  15027. } else {
  15028. // envNode already refers to a cube map
  15029. this._cubeTextureNode = this.envNode;
  15030. }
  15031. }
  15032. }
  15033. }
  15034. setup( builder ) {
  15035. this.updateBefore( builder );
  15036. return this._cubeTextureNode;
  15037. }
  15038. }
  15039. /**
  15040. * Returns true if the given equirectangular image has been fully loaded
  15041. * and is ready for further processing.
  15042. *
  15043. * @private
  15044. * @param {Image} image - The equirectangular image to check.
  15045. * @return {boolean} Whether the image is ready or not.
  15046. */
  15047. function isEquirectangularMapReady$1( image ) {
  15048. if ( image === null || image === undefined ) return false;
  15049. return image.height > 0;
  15050. }
  15051. /**
  15052. * This function is executed when `dispose()` is called on the equirectangular
  15053. * texture. In this case, the generated cube map with its render target
  15054. * is deleted as well.
  15055. *
  15056. * @private
  15057. * @param {Object} event - The event object.
  15058. */
  15059. function onTextureDispose( event ) {
  15060. const texture = event.target;
  15061. texture.removeEventListener( 'dispose', onTextureDispose );
  15062. const renderTarget = _cache$1.get( texture );
  15063. if ( renderTarget !== undefined ) {
  15064. _cache$1.delete( texture );
  15065. renderTarget.dispose();
  15066. }
  15067. }
  15068. /**
  15069. * This function makes sure the generated cube map uses the correct
  15070. * texture mapping that corresponds to the equirectangular original.
  15071. *
  15072. * @private
  15073. * @param {Texture} texture - The cube texture.
  15074. * @param {number} mapping - The original texture mapping.
  15075. */
  15076. function mapTextureMapping( texture, mapping ) {
  15077. if ( mapping === EquirectangularReflectionMapping ) {
  15078. texture.mapping = CubeReflectionMapping;
  15079. } else if ( mapping === EquirectangularRefractionMapping ) {
  15080. texture.mapping = CubeRefractionMapping;
  15081. }
  15082. }
  15083. /**
  15084. * TSL function for creating a cube map node.
  15085. *
  15086. * @tsl
  15087. * @function
  15088. * @param {Node} envNode - The node representing the environment map.
  15089. * @returns {CubeMapNode}
  15090. */
  15091. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15092. /**
  15093. * Represents a basic model for Image-based lighting (IBL). The environment
  15094. * is defined via environment maps in the equirectangular or cube map format.
  15095. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15096. * or {@link MeshPhongNodeMaterial}.
  15097. *
  15098. * @augments LightingNode
  15099. */
  15100. class BasicEnvironmentNode extends LightingNode {
  15101. static get type() {
  15102. return 'BasicEnvironmentNode';
  15103. }
  15104. /**
  15105. * Constructs a new basic environment node.
  15106. *
  15107. * @param {Node} [envNode=null] - A node representing the environment.
  15108. */
  15109. constructor( envNode = null ) {
  15110. super();
  15111. /**
  15112. * A node representing the environment.
  15113. *
  15114. * @type {Node}
  15115. * @default null
  15116. */
  15117. this.envNode = envNode;
  15118. }
  15119. setup( builder ) {
  15120. // environment property is used in the finish() method of BasicLightingModel
  15121. builder.context.environment = cubeMapNode( this.envNode );
  15122. }
  15123. }
  15124. /**
  15125. * A specific version of {@link IrradianceNode} that is only relevant
  15126. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15127. * requires a special scaling factor for the light map.
  15128. *
  15129. * @augments LightingNode
  15130. */
  15131. class BasicLightMapNode extends LightingNode {
  15132. static get type() {
  15133. return 'BasicLightMapNode';
  15134. }
  15135. /**
  15136. * Constructs a new basic light map node.
  15137. *
  15138. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15139. */
  15140. constructor( lightMapNode = null ) {
  15141. super();
  15142. /**
  15143. * The light map node.
  15144. *
  15145. * @type {?Node<vec3>}
  15146. */
  15147. this.lightMapNode = lightMapNode;
  15148. }
  15149. setup( builder ) {
  15150. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15151. const RECIPROCAL_PI = float( 1 / Math.PI );
  15152. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15153. }
  15154. }
  15155. /**
  15156. * Abstract class for implementing lighting models. The module defines
  15157. * multiple methods that concrete lighting models can implement. These
  15158. * methods are executed at different points during the light evaluation
  15159. * process.
  15160. */
  15161. class LightingModel {
  15162. /**
  15163. * This method is intended for setting up lighting model and context data
  15164. * which are later used in the evaluation process.
  15165. *
  15166. * @abstract
  15167. * @param {NodeBuilder} builder - The current node builder.
  15168. */
  15169. start( builder ) {
  15170. // lights ( direct )
  15171. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15172. // indirect
  15173. this.indirect( builder );
  15174. }
  15175. /**
  15176. * This method is intended for executing final tasks like final updates
  15177. * to the outgoing light.
  15178. *
  15179. * @abstract
  15180. * @param {NodeBuilder} builder - The current node builder.
  15181. */
  15182. finish( /*builder*/ ) { }
  15183. /**
  15184. * This method is intended for implementing the direct light term and
  15185. * executed during the build process of directional, point and spot light nodes.
  15186. *
  15187. * @abstract
  15188. * @param {Object} lightData - The light data.
  15189. * @param {NodeBuilder} builder - The current node builder.
  15190. */
  15191. direct( /*lightData, builder*/ ) { }
  15192. /**
  15193. * This method is intended for implementing the direct light term for
  15194. * rect area light nodes.
  15195. *
  15196. * @abstract
  15197. * @param {Object} lightData - The light data.
  15198. * @param {NodeBuilder} builder - The current node builder.
  15199. */
  15200. directRectArea( /*lightData, builder*/ ) {}
  15201. /**
  15202. * This method is intended for implementing the indirect light term.
  15203. *
  15204. * @abstract
  15205. * @param {NodeBuilder} builder - The current node builder.
  15206. */
  15207. indirect( /*builder*/ ) { }
  15208. /**
  15209. * This method is intended for implementing the ambient occlusion term.
  15210. * Unlike other methods, this method must be called manually by the lighting
  15211. * model in its indirect term.
  15212. *
  15213. * @abstract
  15214. * @param {NodeBuilder} builder - The current node builder.
  15215. */
  15216. ambientOcclusion( /*input, stack, builder*/ ) { }
  15217. }
  15218. /**
  15219. * Represents the lighting model for unlit materials. The only light contribution
  15220. * is baked indirect lighting modulated with ambient occlusion and the material's
  15221. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15222. *
  15223. * @augments LightingModel
  15224. */
  15225. class BasicLightingModel extends LightingModel {
  15226. /**
  15227. * Constructs a new basic lighting model.
  15228. */
  15229. constructor() {
  15230. super();
  15231. }
  15232. /**
  15233. * Implements the baked indirect lighting with its modulation.
  15234. *
  15235. * @param {NodeBuilder} builder - The current node builder.
  15236. */
  15237. indirect( { context } ) {
  15238. const ambientOcclusion = context.ambientOcclusion;
  15239. const reflectedLight = context.reflectedLight;
  15240. const irradianceLightMap = context.irradianceLightMap;
  15241. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15242. // accumulation (baked indirect lighting only)
  15243. if ( irradianceLightMap ) {
  15244. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15245. } else {
  15246. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15247. }
  15248. // modulation
  15249. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15250. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15251. }
  15252. /**
  15253. * Implements the environment mapping.
  15254. *
  15255. * @param {NodeBuilder} builder - The current node builder.
  15256. */
  15257. finish( builder ) {
  15258. const { material, context } = builder;
  15259. const outgoingLight = context.outgoingLight;
  15260. const envNode = builder.context.environment;
  15261. if ( envNode ) {
  15262. switch ( material.combine ) {
  15263. case MultiplyOperation:
  15264. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15265. break;
  15266. case MixOperation:
  15267. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15268. break;
  15269. case AddOperation:
  15270. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15271. break;
  15272. default:
  15273. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  15274. break;
  15275. }
  15276. }
  15277. }
  15278. }
  15279. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15280. /**
  15281. * Node material version of {@link MeshBasicMaterial}.
  15282. *
  15283. * @augments NodeMaterial
  15284. */
  15285. class MeshBasicNodeMaterial extends NodeMaterial {
  15286. static get type() {
  15287. return 'MeshBasicNodeMaterial';
  15288. }
  15289. /**
  15290. * Constructs a new mesh basic node material.
  15291. *
  15292. * @param {Object} [parameters] - The configuration parameter.
  15293. */
  15294. constructor( parameters ) {
  15295. super();
  15296. /**
  15297. * This flag can be used for type testing.
  15298. *
  15299. * @type {boolean}
  15300. * @readonly
  15301. * @default true
  15302. */
  15303. this.isMeshBasicNodeMaterial = true;
  15304. /**
  15305. * Although the basic material is by definition unlit, we set
  15306. * this property to `true` since we use a lighting model to compute
  15307. * the outgoing light of the fragment shader.
  15308. *
  15309. * @type {boolean}
  15310. * @default true
  15311. */
  15312. this.lights = true;
  15313. this.setDefaultValues( _defaultValues$9 );
  15314. this.setValues( parameters );
  15315. }
  15316. /**
  15317. * Basic materials are not affected by normal and bump maps so we
  15318. * return by default {@link normalViewGeometry}.
  15319. *
  15320. * @return {Node<vec3>} The normal node.
  15321. */
  15322. setupNormal() {
  15323. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15324. }
  15325. /**
  15326. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15327. * to implement the default environment mapping.
  15328. *
  15329. * @param {NodeBuilder} builder - The current node builder.
  15330. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15331. */
  15332. setupEnvironment( builder ) {
  15333. const envNode = super.setupEnvironment( builder );
  15334. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15335. }
  15336. /**
  15337. * This method must be overwritten since light maps are evaluated
  15338. * with a special scaling factor for basic materials.
  15339. *
  15340. * @param {NodeBuilder} builder - The current node builder.
  15341. * @return {?BasicLightMapNode<vec3>} The light map node.
  15342. */
  15343. setupLightMap( builder ) {
  15344. let node = null;
  15345. if ( builder.material.lightMap ) {
  15346. node = new BasicLightMapNode( materialLightMap );
  15347. }
  15348. return node;
  15349. }
  15350. /**
  15351. * The material overwrites this method because `lights` is set to `true` but
  15352. * we still want to return the diffuse color as the outgoing light.
  15353. *
  15354. * @return {Node<vec3>} The outgoing light node.
  15355. */
  15356. setupOutgoingLight() {
  15357. return diffuseColor.rgb;
  15358. }
  15359. /**
  15360. * Setups the lighting model.
  15361. *
  15362. * @return {BasicLightingModel} The lighting model.
  15363. */
  15364. setupLightingModel() {
  15365. return new BasicLightingModel();
  15366. }
  15367. }
  15368. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15369. // Original approximation by Christophe Schlick '94
  15370. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15371. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15372. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15373. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15374. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15375. } ); // validated
  15376. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15377. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15378. } ); // validated
  15379. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15380. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15381. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15382. } );
  15383. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15384. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15385. const dotNH = normalView.dot( halfDir ).clamp();
  15386. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15387. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15388. const G = G_BlinnPhong_Implicit();
  15389. const D = D_BlinnPhong( { dotNH } );
  15390. return F.mul( G ).mul( D );
  15391. } );
  15392. /**
  15393. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15394. *
  15395. * @augments BasicLightingModel
  15396. */
  15397. class PhongLightingModel extends BasicLightingModel {
  15398. /**
  15399. * Constructs a new phong lighting model.
  15400. *
  15401. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15402. */
  15403. constructor( specular = true ) {
  15404. super();
  15405. /**
  15406. * Whether specular is supported or not. Set this to `false` if you are
  15407. * looking for a Lambert-like material meaning a material for non-shiny
  15408. * surfaces, without specular highlights.
  15409. *
  15410. * @type {boolean}
  15411. * @default true
  15412. */
  15413. this.specular = specular;
  15414. }
  15415. /**
  15416. * Implements the direct lighting. The specular portion is optional an can be controlled
  15417. * with the {@link PhongLightingModel#specular} flag.
  15418. *
  15419. * @param {Object} lightData - The light data.
  15420. */
  15421. direct( { lightDirection, lightColor, reflectedLight } ) {
  15422. const dotNL = normalView.dot( lightDirection ).clamp();
  15423. const irradiance = dotNL.mul( lightColor );
  15424. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15425. if ( this.specular === true ) {
  15426. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15427. }
  15428. }
  15429. /**
  15430. * Implements the indirect lighting.
  15431. *
  15432. * @param {NodeBuilder} builder - The current node builder.
  15433. */
  15434. indirect( builder ) {
  15435. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15436. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15437. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15438. }
  15439. }
  15440. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15441. /**
  15442. * Node material version of {@link MeshLambertMaterial}.
  15443. *
  15444. * @augments NodeMaterial
  15445. */
  15446. class MeshLambertNodeMaterial extends NodeMaterial {
  15447. static get type() {
  15448. return 'MeshLambertNodeMaterial';
  15449. }
  15450. /**
  15451. * Constructs a new mesh lambert node material.
  15452. *
  15453. * @param {Object} [parameters] - The configuration parameter.
  15454. */
  15455. constructor( parameters ) {
  15456. super();
  15457. /**
  15458. * This flag can be used for type testing.
  15459. *
  15460. * @type {boolean}
  15461. * @readonly
  15462. * @default true
  15463. */
  15464. this.isMeshLambertNodeMaterial = true;
  15465. /**
  15466. * Set to `true` because lambert materials react on lights.
  15467. *
  15468. * @type {boolean}
  15469. * @default true
  15470. */
  15471. this.lights = true;
  15472. this.setDefaultValues( _defaultValues$8 );
  15473. this.setValues( parameters );
  15474. }
  15475. /**
  15476. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15477. * to implement the default environment mapping.
  15478. *
  15479. * @param {NodeBuilder} builder - The current node builder.
  15480. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15481. */
  15482. setupEnvironment( builder ) {
  15483. const envNode = super.setupEnvironment( builder );
  15484. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15485. }
  15486. /**
  15487. * Setups the lighting model.
  15488. *
  15489. * @return {PhongLightingModel} The lighting model.
  15490. */
  15491. setupLightingModel( /*builder*/ ) {
  15492. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15493. }
  15494. }
  15495. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15496. /**
  15497. * Node material version of {@link MeshPhongMaterial}.
  15498. *
  15499. * @augments NodeMaterial
  15500. */
  15501. class MeshPhongNodeMaterial extends NodeMaterial {
  15502. static get type() {
  15503. return 'MeshPhongNodeMaterial';
  15504. }
  15505. /**
  15506. * Constructs a new mesh lambert node material.
  15507. *
  15508. * @param {Object} [parameters] - The configuration parameter.
  15509. */
  15510. constructor( parameters ) {
  15511. super();
  15512. /**
  15513. * This flag can be used for type testing.
  15514. *
  15515. * @type {boolean}
  15516. * @readonly
  15517. * @default true
  15518. */
  15519. this.isMeshPhongNodeMaterial = true;
  15520. /**
  15521. * Set to `true` because phong materials react on lights.
  15522. *
  15523. * @type {boolean}
  15524. * @default true
  15525. */
  15526. this.lights = true;
  15527. /**
  15528. * The shininess of phong materials is by default inferred from the `shininess`
  15529. * property. This node property allows to overwrite the default
  15530. * and define the shininess with a node instead.
  15531. *
  15532. * If you don't want to overwrite the shininess but modify the existing
  15533. * value instead, use {@link materialShininess}.
  15534. *
  15535. * @type {?Node<float>}
  15536. * @default null
  15537. */
  15538. this.shininessNode = null;
  15539. /**
  15540. * The specular color of phong materials is by default inferred from the
  15541. * `specular` property. This node property allows to overwrite the default
  15542. * and define the specular color with a node instead.
  15543. *
  15544. * If you don't want to overwrite the specular color but modify the existing
  15545. * value instead, use {@link materialSpecular}.
  15546. *
  15547. * @type {?Node<vec3>}
  15548. * @default null
  15549. */
  15550. this.specularNode = null;
  15551. this.setDefaultValues( _defaultValues$7 );
  15552. this.setValues( parameters );
  15553. }
  15554. /**
  15555. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15556. * to implement the default environment mapping.
  15557. *
  15558. * @param {NodeBuilder} builder - The current node builder.
  15559. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15560. */
  15561. setupEnvironment( builder ) {
  15562. const envNode = super.setupEnvironment( builder );
  15563. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15564. }
  15565. /**
  15566. * Setups the lighting model.
  15567. *
  15568. * @return {PhongLightingModel} The lighting model.
  15569. */
  15570. setupLightingModel( /*builder*/ ) {
  15571. return new PhongLightingModel();
  15572. }
  15573. /**
  15574. * Setups the phong specific node variables.
  15575. *
  15576. * @param {NodeBuilder} builder - The current node builder.
  15577. */
  15578. setupVariants( /*builder*/ ) {
  15579. // SHININESS
  15580. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15581. shininess.assign( shininessNode );
  15582. // SPECULAR COLOR
  15583. const specularNode = this.specularNode || materialSpecular;
  15584. specularColor.assign( specularNode );
  15585. }
  15586. copy( source ) {
  15587. this.shininessNode = source.shininessNode;
  15588. this.specularNode = source.specularNode;
  15589. return super.copy( source );
  15590. }
  15591. }
  15592. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  15593. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  15594. return float( 0 );
  15595. }
  15596. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  15597. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  15598. return geometryRoughness;
  15599. } );
  15600. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  15601. const { roughness } = inputs;
  15602. const geometryRoughness = getGeometryRoughness();
  15603. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  15604. roughnessFactor = roughnessFactor.add( geometryRoughness );
  15605. roughnessFactor = roughnessFactor.min( 1.0 );
  15606. return roughnessFactor;
  15607. } );
  15608. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  15609. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15610. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  15611. const a2 = alpha.pow2();
  15612. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  15613. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  15614. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  15615. } ).setLayout( {
  15616. name: 'V_GGX_SmithCorrelated',
  15617. type: 'float',
  15618. inputs: [
  15619. { name: 'alpha', type: 'float' },
  15620. { name: 'dotNL', type: 'float' },
  15621. { name: 'dotNV', type: 'float' }
  15622. ]
  15623. } ); // validated
  15624. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15625. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  15626. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  15627. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  15628. const v = div( 0.5, gv.add( gl ) );
  15629. return v.saturate();
  15630. } ).setLayout( {
  15631. name: 'V_GGX_SmithCorrelated_Anisotropic',
  15632. type: 'float',
  15633. inputs: [
  15634. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15635. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15636. { name: 'dotTV', type: 'float', qualifier: 'in' },
  15637. { name: 'dotBV', type: 'float', qualifier: 'in' },
  15638. { name: 'dotTL', type: 'float', qualifier: 'in' },
  15639. { name: 'dotBL', type: 'float', qualifier: 'in' },
  15640. { name: 'dotNV', type: 'float', qualifier: 'in' },
  15641. { name: 'dotNL', type: 'float', qualifier: 'in' }
  15642. ]
  15643. } );
  15644. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  15645. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  15646. // alpha is "roughness squared" in Disney’s reparameterization
  15647. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  15648. const a2 = alpha.pow2();
  15649. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  15650. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  15651. } ).setLayout( {
  15652. name: 'D_GGX',
  15653. type: 'float',
  15654. inputs: [
  15655. { name: 'alpha', type: 'float' },
  15656. { name: 'dotNH', type: 'float' }
  15657. ]
  15658. } ); // validated
  15659. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  15660. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15661. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  15662. const a2 = alphaT.mul( alphaB );
  15663. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  15664. const v2 = v.dot( v );
  15665. const w2 = a2.div( v2 );
  15666. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  15667. } ).setLayout( {
  15668. name: 'D_GGX_Anisotropic',
  15669. type: 'float',
  15670. inputs: [
  15671. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15672. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15673. { name: 'dotNH', type: 'float', qualifier: 'in' },
  15674. { name: 'dotTH', type: 'float', qualifier: 'in' },
  15675. { name: 'dotBH', type: 'float', qualifier: 'in' }
  15676. ]
  15677. } );
  15678. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  15679. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  15680. const alpha = roughness.pow2(); // UE4's roughness
  15681. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15682. const dotNL = normalView$1.dot( lightDirection ).clamp();
  15683. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15684. const dotNH = normalView$1.dot( halfDir ).clamp();
  15685. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15686. let F = F_Schlick( { f0, f90, dotVH } );
  15687. let V, D;
  15688. if ( defined( USE_IRIDESCENCE ) ) {
  15689. F = iridescence.mix( F, f );
  15690. }
  15691. if ( defined( USE_ANISOTROPY ) ) {
  15692. const dotTL = anisotropyT.dot( lightDirection );
  15693. const dotTV = anisotropyT.dot( positionViewDirection );
  15694. const dotTH = anisotropyT.dot( halfDir );
  15695. const dotBL = anisotropyB.dot( lightDirection );
  15696. const dotBV = anisotropyB.dot( positionViewDirection );
  15697. const dotBH = anisotropyB.dot( halfDir );
  15698. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  15699. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  15700. } else {
  15701. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  15702. D = D_GGX( { alpha, dotNH } );
  15703. }
  15704. return F.mul( V ).mul( D );
  15705. } ); // validated
  15706. // Analytical approximation of the DFG LUT, one half of the
  15707. // split-sum approximation used in indirect specular lighting.
  15708. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  15709. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  15710. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  15711. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  15712. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  15713. const r = roughness.mul( c0 ).add( c1 );
  15714. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  15715. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  15716. return fab;
  15717. } ).setLayout( {
  15718. name: 'DFGApprox',
  15719. type: 'vec2',
  15720. inputs: [
  15721. { name: 'roughness', type: 'float' },
  15722. { name: 'dotNV', type: 'vec3' }
  15723. ]
  15724. } );
  15725. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  15726. const { dotNV, specularColor, specularF90, roughness } = inputs;
  15727. const fab = DFGApprox( { dotNV, roughness } );
  15728. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15729. } );
  15730. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  15731. const x = dotVH.oneMinus().saturate();
  15732. const x2 = x.mul( x );
  15733. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  15734. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  15735. } ).setLayout( {
  15736. name: 'Schlick_to_F0',
  15737. type: 'vec3',
  15738. inputs: [
  15739. { name: 'f', type: 'vec3' },
  15740. { name: 'f90', type: 'float' },
  15741. { name: 'dotVH', type: 'float' }
  15742. ]
  15743. } );
  15744. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15745. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  15746. const alpha = roughness.pow2();
  15747. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  15748. const invAlpha = float( 1.0 ).div( alpha );
  15749. const cos2h = dotNH.pow2();
  15750. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  15751. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  15752. } ).setLayout( {
  15753. name: 'D_Charlie',
  15754. type: 'float',
  15755. inputs: [
  15756. { name: 'roughness', type: 'float' },
  15757. { name: 'dotNH', type: 'float' }
  15758. ]
  15759. } );
  15760. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15761. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  15762. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  15763. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  15764. } ).setLayout( {
  15765. name: 'V_Neubelt',
  15766. type: 'float',
  15767. inputs: [
  15768. { name: 'dotNV', type: 'float' },
  15769. { name: 'dotNL', type: 'float' }
  15770. ]
  15771. } );
  15772. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15773. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15774. const dotNL = normalView.dot( lightDirection ).clamp();
  15775. const dotNV = normalView.dot( positionViewDirection ).clamp();
  15776. const dotNH = normalView.dot( halfDir ).clamp();
  15777. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  15778. const V = V_Neubelt( { dotNV, dotNL } );
  15779. return sheen.mul( D ).mul( V );
  15780. } );
  15781. // Rect Area Light
  15782. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  15783. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  15784. // code: https://github.com/selfshadow/ltc_code/
  15785. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  15786. const LUT_SIZE = 64.0;
  15787. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  15788. const LUT_BIAS = 0.5 / LUT_SIZE;
  15789. const dotNV = N.dot( V ).saturate();
  15790. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  15791. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  15792. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  15793. return uv;
  15794. } ).setLayout( {
  15795. name: 'LTC_Uv',
  15796. type: 'vec2',
  15797. inputs: [
  15798. { name: 'N', type: 'vec3' },
  15799. { name: 'V', type: 'vec3' },
  15800. { name: 'roughness', type: 'float' }
  15801. ]
  15802. } );
  15803. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  15804. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  15805. // An approximation of the form factor of a horizon-clipped rectangle.
  15806. const l = f.length();
  15807. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  15808. } ).setLayout( {
  15809. name: 'LTC_ClippedSphereFormFactor',
  15810. type: 'float',
  15811. inputs: [
  15812. { name: 'f', type: 'vec3' }
  15813. ]
  15814. } );
  15815. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  15816. const x = v1.dot( v2 );
  15817. const y = x.abs().toVar();
  15818. // rational polynomial approximation to theta / sin( theta ) / 2PI
  15819. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  15820. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  15821. const v = a.div( b );
  15822. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  15823. return v1.cross( v2 ).mul( theta_sintheta );
  15824. } ).setLayout( {
  15825. name: 'LTC_EdgeVectorFormFactor',
  15826. type: 'vec3',
  15827. inputs: [
  15828. { name: 'v1', type: 'vec3' },
  15829. { name: 'v2', type: 'vec3' }
  15830. ]
  15831. } );
  15832. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  15833. // bail if point is on back side of plane of light
  15834. // assumes ccw winding order of light vertices
  15835. const v1 = p1.sub( p0 ).toVar();
  15836. const v2 = p3.sub( p0 ).toVar();
  15837. const lightNormal = v1.cross( v2 );
  15838. const result = vec3().toVar();
  15839. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15840. // construct orthonormal basis around N
  15841. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  15842. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  15843. // compute transform
  15844. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  15845. // transform rect
  15846. // & project rect onto sphere
  15847. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  15848. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  15849. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  15850. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  15851. // calculate vector form factor
  15852. const vectorFormFactor = vec3( 0 ).toVar();
  15853. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15854. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15855. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15856. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15857. // adjust for horizon clipping
  15858. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  15859. } );
  15860. return result;
  15861. } ).setLayout( {
  15862. name: 'LTC_Evaluate',
  15863. type: 'vec3',
  15864. inputs: [
  15865. { name: 'N', type: 'vec3' },
  15866. { name: 'V', type: 'vec3' },
  15867. { name: 'P', type: 'vec3' },
  15868. { name: 'mInv', type: 'mat3' },
  15869. { name: 'p0', type: 'vec3' },
  15870. { name: 'p1', type: 'vec3' },
  15871. { name: 'p2', type: 'vec3' },
  15872. { name: 'p3', type: 'vec3' }
  15873. ]
  15874. } );
  15875. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  15876. // bail if point is on back side of plane of light
  15877. // assumes ccw winding order of light vertices
  15878. const v1 = p1.sub( p0 ).toVar();
  15879. const v2 = p3.sub( p0 ).toVar();
  15880. const lightNormal = v1.cross( v2 );
  15881. const result = vec3().toVar();
  15882. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15883. // transform rect
  15884. // & project rect onto sphere
  15885. const coords0 = p0.sub( P ).normalize().toVar();
  15886. const coords1 = p1.sub( P ).normalize().toVar();
  15887. const coords2 = p2.sub( P ).normalize().toVar();
  15888. const coords3 = p3.sub( P ).normalize().toVar();
  15889. // calculate vector form factor
  15890. const vectorFormFactor = vec3( 0 ).toVar();
  15891. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15892. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15893. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15894. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15895. // adjust for horizon clipping
  15896. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  15897. } );
  15898. return result;
  15899. } ).setLayout( {
  15900. name: 'LTC_Evaluate',
  15901. type: 'vec3',
  15902. inputs: [
  15903. { name: 'P', type: 'vec3' },
  15904. { name: 'p0', type: 'vec3' },
  15905. { name: 'p1', type: 'vec3' },
  15906. { name: 'p2', type: 'vec3' },
  15907. { name: 'p3', type: 'vec3' }
  15908. ]
  15909. } );
  15910. // Mipped Bicubic Texture Filtering by N8
  15911. // https://www.shadertoy.com/view/Dl2SDW
  15912. const bC = 1.0 / 6.0;
  15913. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  15914. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  15915. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  15916. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  15917. const g0 = ( a ) => w0( a ).add( w1( a ) );
  15918. const g1 = ( a ) => w2( a ).add( w3( a ) );
  15919. // h0 and h1 are the two offset functions
  15920. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  15921. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  15922. const bicubic = ( textureNode, texelSize, lod ) => {
  15923. const uv = textureNode.uvNode;
  15924. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  15925. const iuv = floor( uvScaled );
  15926. const fuv = fract( uvScaled );
  15927. const g0x = g0( fuv.x );
  15928. const g1x = g1( fuv.x );
  15929. const h0x = h0( fuv.x );
  15930. const h1x = h1( fuv.x );
  15931. const h0y = h0( fuv.y );
  15932. const h1y = h1( fuv.y );
  15933. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15934. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15935. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15936. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15937. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  15938. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  15939. return a.add( b );
  15940. };
  15941. /**
  15942. * Applies mipped bicubic texture filtering to the given texture node.
  15943. *
  15944. * @tsl
  15945. * @function
  15946. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15947. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  15948. * @return {Node} The filtered texture sample.
  15949. */
  15950. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  15951. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  15952. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  15953. const fLodSizeInv = div( 1.0, fLodSize );
  15954. const cLodSizeInv = div( 1.0, cLodSize );
  15955. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  15956. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  15957. return fract( lodNode ).mix( fSample, cSample );
  15958. } );
  15959. /**
  15960. * Applies mipped bicubic texture filtering to the given texture node.
  15961. *
  15962. * @tsl
  15963. * @function
  15964. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15965. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  15966. * @return {Node} The filtered texture sample.
  15967. */
  15968. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  15969. const lod = strength.mul( maxMipLevel( textureNode ) );
  15970. return textureBicubicLevel( textureNode, lod );
  15971. } );
  15972. //
  15973. // Transmission
  15974. //
  15975. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  15976. // Direction of refracted light.
  15977. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  15978. // Compute rotation-independent scaling of the model matrix.
  15979. const modelScale = vec3(
  15980. length( modelMatrix[ 0 ].xyz ),
  15981. length( modelMatrix[ 1 ].xyz ),
  15982. length( modelMatrix[ 2 ].xyz )
  15983. );
  15984. // The thickness is specified in local space.
  15985. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  15986. } ).setLayout( {
  15987. name: 'getVolumeTransmissionRay',
  15988. type: 'vec3',
  15989. inputs: [
  15990. { name: 'n', type: 'vec3' },
  15991. { name: 'v', type: 'vec3' },
  15992. { name: 'thickness', type: 'float' },
  15993. { name: 'ior', type: 'float' },
  15994. { name: 'modelMatrix', type: 'mat4' }
  15995. ]
  15996. } );
  15997. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  15998. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  15999. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16000. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16001. } ).setLayout( {
  16002. name: 'applyIorToRoughness',
  16003. type: 'float',
  16004. inputs: [
  16005. { name: 'roughness', type: 'float' },
  16006. { name: 'ior', type: 'float' }
  16007. ]
  16008. } );
  16009. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16010. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16011. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16012. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16013. const transmissionSample = vTexture.sample( fragCoord );
  16014. //const transmissionSample = viewportMipTexture( fragCoord );
  16015. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16016. return textureBicubicLevel( transmissionSample, lod );
  16017. } );
  16018. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16019. If( attenuationDistance.notEqual( 0 ), () => {
  16020. // Compute light attenuation using Beer's law.
  16021. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16022. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16023. return transmittance;
  16024. } );
  16025. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16026. return vec3( 1.0 );
  16027. } ).setLayout( {
  16028. name: 'volumeAttenuation',
  16029. type: 'vec3',
  16030. inputs: [
  16031. { name: 'transmissionDistance', type: 'float' },
  16032. { name: 'attenuationColor', type: 'vec3' },
  16033. { name: 'attenuationDistance', type: 'float' }
  16034. ]
  16035. } );
  16036. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16037. let transmittedLight, transmittance;
  16038. if ( dispersion ) {
  16039. transmittedLight = vec4().toVar();
  16040. transmittance = vec3().toVar();
  16041. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16042. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16043. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16044. const ior = iors.element( i );
  16045. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16046. const refractedRayExit = position.add( transmissionRay );
  16047. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16048. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16049. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16050. refractionCoords.addAssign( 1.0 );
  16051. refractionCoords.divAssign( 2.0 );
  16052. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16053. // Sample framebuffer to get pixel the refracted ray hits.
  16054. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16055. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16056. transmittedLight.a.addAssign( transmissionSample.a );
  16057. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16058. } );
  16059. transmittedLight.a.divAssign( 3.0 );
  16060. } else {
  16061. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16062. const refractedRayExit = position.add( transmissionRay );
  16063. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16064. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16065. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16066. refractionCoords.addAssign( 1.0 );
  16067. refractionCoords.divAssign( 2.0 );
  16068. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16069. // Sample framebuffer to get pixel the refracted ray hits.
  16070. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16071. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16072. }
  16073. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16074. const dotNV = n.dot( v ).clamp();
  16075. // Get the specular component.
  16076. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16077. dotNV,
  16078. specularColor,
  16079. specularF90,
  16080. roughness
  16081. } ) );
  16082. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16083. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16084. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16085. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16086. } );
  16087. //
  16088. // Iridescence
  16089. //
  16090. // XYZ to linear-sRGB color space
  16091. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16092. 3.2404542, -0.969266, 0.0556434,
  16093. -1.5371385, 1.8760108, -0.2040259,
  16094. -0.4985314, 0.0415560, 1.0572252
  16095. );
  16096. // Assume air interface for top
  16097. // Note: We don't handle the case fresnel0 == 1
  16098. const Fresnel0ToIor = ( fresnel0 ) => {
  16099. const sqrtF0 = fresnel0.sqrt();
  16100. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16101. };
  16102. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16103. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16104. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16105. };
  16106. // Fresnel equations for dielectric/dielectric interfaces.
  16107. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16108. // Evaluation XYZ sensitivity curves in Fourier space
  16109. const evalSensitivity = ( OPD, shift ) => {
  16110. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16111. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16112. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16113. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16114. 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() );
  16115. 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() );
  16116. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16117. const rgb = XYZ_TO_REC709.mul( xyz );
  16118. return rgb;
  16119. };
  16120. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16121. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16122. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16123. // Evaluate the cosTheta on the base layer (Snell law)
  16124. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16125. // Handle TIR:
  16126. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16127. If( cosTheta2Sq.lessThan( 0 ), () => {
  16128. return vec3( 1.0 );
  16129. } );
  16130. const cosTheta2 = cosTheta2Sq.sqrt();
  16131. // First interface
  16132. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16133. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16134. //const R21 = R12;
  16135. const T121 = R12.oneMinus();
  16136. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16137. const phi21 = float( Math.PI ).sub( phi12 );
  16138. // Second interface
  16139. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16140. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16141. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16142. const phi23 = vec3(
  16143. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16144. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16145. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16146. );
  16147. // Phase shift
  16148. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16149. const phi = vec3( phi21 ).add( phi23 );
  16150. // Compound terms
  16151. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16152. const r123 = R123.sqrt();
  16153. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16154. // Reflectance term for m = 0 (DC term amplitude)
  16155. const C0 = R12.add( Rs );
  16156. const I = C0.toVar();
  16157. // Reflectance term for m > 0 (pairs of diracs)
  16158. const Cm = Rs.sub( T121 ).toVar();
  16159. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16160. Cm.mulAssign( r123 );
  16161. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16162. I.addAssign( Cm.mul( Sm ) );
  16163. } );
  16164. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16165. return I.max( vec3( 0.0 ) );
  16166. } ).setLayout( {
  16167. name: 'evalIridescence',
  16168. type: 'vec3',
  16169. inputs: [
  16170. { name: 'outsideIOR', type: 'float' },
  16171. { name: 'eta2', type: 'float' },
  16172. { name: 'cosTheta1', type: 'float' },
  16173. { name: 'thinFilmThickness', type: 'float' },
  16174. { name: 'baseF0', type: 'vec3' }
  16175. ]
  16176. } );
  16177. //
  16178. // Sheen
  16179. //
  16180. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16181. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16182. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16183. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16184. const dotNV = normal.dot( viewDir ).saturate();
  16185. const r2 = roughness.pow2();
  16186. const a = select(
  16187. roughness.lessThan( 0.25 ),
  16188. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16189. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16190. );
  16191. const b = select(
  16192. roughness.lessThan( 0.25 ),
  16193. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16194. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16195. );
  16196. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16197. return DG.mul( 1.0 / Math.PI ).saturate();
  16198. } );
  16199. const clearcoatF0 = vec3( 0.04 );
  16200. const clearcoatF90 = float( 1 );
  16201. /**
  16202. * Represents the lighting model for a PBR material.
  16203. *
  16204. * @augments LightingModel
  16205. */
  16206. class PhysicalLightingModel extends LightingModel {
  16207. /**
  16208. * Constructs a new physical lighting model.
  16209. *
  16210. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16211. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16212. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16213. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16214. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16215. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16216. */
  16217. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16218. super();
  16219. /**
  16220. * Whether clearcoat is supported or not.
  16221. *
  16222. * @type {boolean}
  16223. * @default false
  16224. */
  16225. this.clearcoat = clearcoat;
  16226. /**
  16227. * Whether sheen is supported or not.
  16228. *
  16229. * @type {boolean}
  16230. * @default false
  16231. */
  16232. this.sheen = sheen;
  16233. /**
  16234. * Whether iridescence is supported or not.
  16235. *
  16236. * @type {boolean}
  16237. * @default false
  16238. */
  16239. this.iridescence = iridescence;
  16240. /**
  16241. * Whether anisotropy is supported or not.
  16242. *
  16243. * @type {boolean}
  16244. * @default false
  16245. */
  16246. this.anisotropy = anisotropy;
  16247. /**
  16248. * Whether transmission is supported or not.
  16249. *
  16250. * @type {boolean}
  16251. * @default false
  16252. */
  16253. this.transmission = transmission;
  16254. /**
  16255. * Whether dispersion is supported or not.
  16256. *
  16257. * @type {boolean}
  16258. * @default false
  16259. */
  16260. this.dispersion = dispersion;
  16261. /**
  16262. * The clear coat radiance.
  16263. *
  16264. * @type {?Node}
  16265. * @default null
  16266. */
  16267. this.clearcoatRadiance = null;
  16268. /**
  16269. * The clear coat specular direct.
  16270. *
  16271. * @type {?Node}
  16272. * @default null
  16273. */
  16274. this.clearcoatSpecularDirect = null;
  16275. /**
  16276. * The clear coat specular indirect.
  16277. *
  16278. * @type {?Node}
  16279. * @default null
  16280. */
  16281. this.clearcoatSpecularIndirect = null;
  16282. /**
  16283. * The sheen specular direct.
  16284. *
  16285. * @type {?Node}
  16286. * @default null
  16287. */
  16288. this.sheenSpecularDirect = null;
  16289. /**
  16290. * The sheen specular indirect.
  16291. *
  16292. * @type {?Node}
  16293. * @default null
  16294. */
  16295. this.sheenSpecularIndirect = null;
  16296. /**
  16297. * The iridescence Fresnel.
  16298. *
  16299. * @type {?Node}
  16300. * @default null
  16301. */
  16302. this.iridescenceFresnel = null;
  16303. /**
  16304. * The iridescence F0.
  16305. *
  16306. * @type {?Node}
  16307. * @default null
  16308. */
  16309. this.iridescenceF0 = null;
  16310. }
  16311. /**
  16312. * Depending on what features are requested, the method prepares certain node variables
  16313. * which are later used for lighting computations.
  16314. *
  16315. * @param {NodeBuilder} builder - The current node builder.
  16316. */
  16317. start( builder ) {
  16318. if ( this.clearcoat === true ) {
  16319. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16320. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16321. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16322. }
  16323. if ( this.sheen === true ) {
  16324. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16325. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16326. }
  16327. if ( this.iridescence === true ) {
  16328. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16329. this.iridescenceFresnel = evalIridescence( {
  16330. outsideIOR: float( 1.0 ),
  16331. eta2: iridescenceIOR,
  16332. cosTheta1: dotNVi,
  16333. thinFilmThickness: iridescenceThickness,
  16334. baseF0: specularColor
  16335. } );
  16336. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16337. }
  16338. if ( this.transmission === true ) {
  16339. const position = positionWorld;
  16340. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16341. const n = normalWorld;
  16342. const context = builder.context;
  16343. context.backdrop = getIBLVolumeRefraction(
  16344. n,
  16345. v,
  16346. roughness,
  16347. diffuseColor,
  16348. specularColor,
  16349. specularF90, // specularF90
  16350. position, // positionWorld
  16351. modelWorldMatrix, // modelMatrix
  16352. cameraViewMatrix, // viewMatrix
  16353. cameraProjectionMatrix, // projMatrix
  16354. ior,
  16355. thickness,
  16356. attenuationColor,
  16357. attenuationDistance,
  16358. this.dispersion ? dispersion : null
  16359. );
  16360. context.backdropAlpha = transmission;
  16361. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16362. }
  16363. super.start( builder );
  16364. }
  16365. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16366. // Approximates multi-scattering in order to preserve energy.
  16367. // http://www.jcgt.org/published/0008/01/03/
  16368. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16369. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16370. const fab = DFGApprox( { roughness, dotNV } );
  16371. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16372. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16373. const Ess = fab.x.add( fab.y );
  16374. const Ems = Ess.oneMinus();
  16375. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16376. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16377. singleScatter.addAssign( FssEss );
  16378. multiScatter.addAssign( Fms.mul( Ems ) );
  16379. }
  16380. /**
  16381. * Implements the direct light.
  16382. *
  16383. * @param {Object} lightData - The light data.
  16384. * @param {NodeBuilder} builder - The current node builder.
  16385. */
  16386. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16387. const dotNL = normalView.dot( lightDirection ).clamp();
  16388. const irradiance = dotNL.mul( lightColor );
  16389. if ( this.sheen === true ) {
  16390. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16391. }
  16392. if ( this.clearcoat === true ) {
  16393. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16394. const ccIrradiance = dotNLcc.mul( lightColor );
  16395. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16396. }
  16397. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16398. 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 } ) ) );
  16399. }
  16400. /**
  16401. * This method is intended for implementing the direct light term for
  16402. * rect area light nodes.
  16403. *
  16404. * @param {Object} input - The input data.
  16405. * @param {NodeBuilder} builder - The current node builder.
  16406. */
  16407. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16408. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16409. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16410. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16411. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16412. const N = normalView;
  16413. const V = positionViewDirection;
  16414. const P = positionView.toVar();
  16415. const uv = LTC_Uv( { N, V, roughness } );
  16416. const t1 = ltc_1.sample( uv ).toVar();
  16417. const t2 = ltc_2.sample( uv ).toVar();
  16418. const mInv = mat3(
  16419. vec3( t1.x, 0, t1.y ),
  16420. vec3( 0, 1, 0 ),
  16421. vec3( t1.z, 0, t1.w )
  16422. ).toVar();
  16423. // LTC Fresnel Approximation by Stephen Hill
  16424. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16425. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16426. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16427. 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 } ) ) );
  16428. }
  16429. /**
  16430. * Implements the indirect lighting.
  16431. *
  16432. * @param {NodeBuilder} builder - The current node builder.
  16433. */
  16434. indirect( builder ) {
  16435. this.indirectDiffuse( builder );
  16436. this.indirectSpecular( builder );
  16437. this.ambientOcclusion( builder );
  16438. }
  16439. /**
  16440. * Implements the indirect diffuse term.
  16441. *
  16442. * @param {NodeBuilder} builder - The current node builder.
  16443. */
  16444. indirectDiffuse( builder ) {
  16445. const { irradiance, reflectedLight } = builder.context;
  16446. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16447. }
  16448. /**
  16449. * Implements the indirect specular term.
  16450. *
  16451. * @param {NodeBuilder} builder - The current node builder.
  16452. */
  16453. indirectSpecular( builder ) {
  16454. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16455. if ( this.sheen === true ) {
  16456. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16457. sheen,
  16458. IBLSheenBRDF( {
  16459. normal: normalView,
  16460. viewDir: positionViewDirection,
  16461. roughness: sheenRoughness
  16462. } )
  16463. ) );
  16464. }
  16465. if ( this.clearcoat === true ) {
  16466. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16467. const clearcoatEnv = EnvironmentBRDF( {
  16468. dotNV: dotNVcc,
  16469. specularColor: clearcoatF0,
  16470. specularF90: clearcoatF90,
  16471. roughness: clearcoatRoughness
  16472. } );
  16473. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16474. }
  16475. // Both indirect specular and indirect diffuse light accumulate here
  16476. const singleScattering = vec3().toVar( 'singleScattering' );
  16477. const multiScattering = vec3().toVar( 'multiScattering' );
  16478. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16479. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16480. const totalScattering = singleScattering.add( multiScattering );
  16481. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16482. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16483. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16484. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16485. }
  16486. /**
  16487. * Implements the ambient occlusion term.
  16488. *
  16489. * @param {NodeBuilder} builder - The current node builder.
  16490. */
  16491. ambientOcclusion( builder ) {
  16492. const { ambientOcclusion, reflectedLight } = builder.context;
  16493. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16494. const aoNV = dotNV.add( ambientOcclusion );
  16495. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16496. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16497. if ( this.clearcoat === true ) {
  16498. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16499. }
  16500. if ( this.sheen === true ) {
  16501. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16502. }
  16503. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16504. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16505. }
  16506. /**
  16507. * Used for final lighting accumulations depending on the requested features.
  16508. *
  16509. * @param {NodeBuilder} builder - The current node builder.
  16510. */
  16511. finish( { context } ) {
  16512. const { outgoingLight } = context;
  16513. if ( this.clearcoat === true ) {
  16514. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16515. const Fcc = F_Schlick( {
  16516. dotVH: dotNVcc,
  16517. f0: clearcoatF0,
  16518. f90: clearcoatF90
  16519. } );
  16520. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  16521. outgoingLight.assign( clearcoatLight );
  16522. }
  16523. if ( this.sheen === true ) {
  16524. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  16525. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  16526. outgoingLight.assign( sheenLight );
  16527. }
  16528. }
  16529. }
  16530. // These defines must match with PMREMGenerator
  16531. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  16532. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  16533. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  16534. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  16535. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  16536. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  16537. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  16538. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  16539. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  16540. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  16541. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  16542. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  16543. // These shader functions convert between the UV coordinates of a single face of
  16544. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  16545. // sampling a textureCube (not generally normalized ).
  16546. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  16547. const absDirection = vec3( abs( direction ) ).toVar();
  16548. const face = float( -1 ).toVar();
  16549. If( absDirection.x.greaterThan( absDirection.z ), () => {
  16550. If( absDirection.x.greaterThan( absDirection.y ), () => {
  16551. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  16552. } ).Else( () => {
  16553. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16554. } );
  16555. } ).Else( () => {
  16556. If( absDirection.z.greaterThan( absDirection.y ), () => {
  16557. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  16558. } ).Else( () => {
  16559. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16560. } );
  16561. } );
  16562. return face;
  16563. } ).setLayout( {
  16564. name: 'getFace',
  16565. type: 'float',
  16566. inputs: [
  16567. { name: 'direction', type: 'vec3' }
  16568. ]
  16569. } );
  16570. // RH coordinate system; PMREM face-indexing convention
  16571. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  16572. const uv = vec2().toVar();
  16573. If( face.equal( 0.0 ), () => {
  16574. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  16575. } ).ElseIf( face.equal( 1.0 ), () => {
  16576. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  16577. } ).ElseIf( face.equal( 2.0 ), () => {
  16578. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  16579. } ).ElseIf( face.equal( 3.0 ), () => {
  16580. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  16581. } ).ElseIf( face.equal( 4.0 ), () => {
  16582. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  16583. } ).Else( () => {
  16584. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  16585. } );
  16586. return mul( 0.5, uv.add( 1.0 ) );
  16587. } ).setLayout( {
  16588. name: 'getUV',
  16589. type: 'vec2',
  16590. inputs: [
  16591. { name: 'direction', type: 'vec3' },
  16592. { name: 'face', type: 'float' }
  16593. ]
  16594. } );
  16595. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  16596. const mip = float( 0.0 ).toVar();
  16597. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  16598. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  16599. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  16600. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  16601. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  16602. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  16603. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  16604. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  16605. } ).Else( () => {
  16606. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  16607. } );
  16608. return mip;
  16609. } ).setLayout( {
  16610. name: 'roughnessToMip',
  16611. type: 'float',
  16612. inputs: [
  16613. { name: 'roughness', type: 'float' }
  16614. ]
  16615. } );
  16616. // RH coordinate system; PMREM face-indexing convention
  16617. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  16618. const uv = uv_immutable.toVar();
  16619. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  16620. const direction = vec3( uv, 1.0 ).toVar();
  16621. If( face.equal( 0.0 ), () => {
  16622. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  16623. } ).ElseIf( face.equal( 1.0 ), () => {
  16624. direction.assign( direction.xzy );
  16625. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  16626. } ).ElseIf( face.equal( 2.0 ), () => {
  16627. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  16628. } ).ElseIf( face.equal( 3.0 ), () => {
  16629. direction.assign( direction.zyx );
  16630. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  16631. } ).ElseIf( face.equal( 4.0 ), () => {
  16632. direction.assign( direction.xzy );
  16633. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  16634. } ).ElseIf( face.equal( 5.0 ), () => {
  16635. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  16636. } );
  16637. return direction;
  16638. } ).setLayout( {
  16639. name: 'getDirection',
  16640. type: 'vec3',
  16641. inputs: [
  16642. { name: 'uv', type: 'vec2' },
  16643. { name: 'face', type: 'float' }
  16644. ]
  16645. } );
  16646. //
  16647. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16648. const roughness = float( roughness_immutable );
  16649. const sampleDir = vec3( sampleDir_immutable );
  16650. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  16651. const mipF = fract( mip );
  16652. const mipInt = floor( mip );
  16653. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16654. If( mipF.notEqual( 0.0 ), () => {
  16655. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16656. color0.assign( mix( color0, color1, mipF ) );
  16657. } );
  16658. return color0;
  16659. } );
  16660. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16661. const mipInt = float( mipInt_immutable ).toVar();
  16662. const direction = vec3( direction_immutable );
  16663. const face = float( getFace( direction ) ).toVar();
  16664. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  16665. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  16666. const faceSize = float( exp2( mipInt ) ).toVar();
  16667. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  16668. If( face.greaterThan( 2.0 ), () => {
  16669. uv.y.addAssign( faceSize );
  16670. face.subAssign( 3.0 );
  16671. } );
  16672. uv.x.addAssign( face.mul( faceSize ) );
  16673. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  16674. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  16675. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  16676. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  16677. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  16678. } );
  16679. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16680. const cosTheta = cos( theta );
  16681. // Rodrigues' axis-angle rotation
  16682. const sampleDirection = outputDirection.mul( cosTheta )
  16683. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  16684. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  16685. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  16686. } );
  16687. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16688. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  16689. If( axis.equal( vec3( 0.0 ) ), () => {
  16690. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  16691. } );
  16692. axis.assign( normalize( axis ) );
  16693. const gl_FragColor = vec3().toVar();
  16694. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16695. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  16696. If( i.greaterThanEqual( samples ), () => {
  16697. Break();
  16698. } );
  16699. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  16700. 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 } ) ) );
  16701. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16702. } );
  16703. return vec4( gl_FragColor, 1 );
  16704. } );
  16705. const LOD_MIN = 4;
  16706. // The standard deviations (radians) associated with the extra mips. These are
  16707. // chosen to approximate a Trowbridge-Reitz distribution function times the
  16708. // geometric shadowing function. These sigma values squared must match the
  16709. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  16710. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  16711. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  16712. // samples and exit early, but not recompile the shader.
  16713. const MAX_SAMPLES = 20;
  16714. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  16715. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  16716. const _clearColor$2 = /*@__PURE__*/ new Color();
  16717. let _oldTarget = null;
  16718. let _oldActiveCubeFace = 0;
  16719. let _oldActiveMipmapLevel = 0;
  16720. // Golden Ratio
  16721. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  16722. const INV_PHI = 1 / PHI;
  16723. // Vertices of a dodecahedron (except the opposites, which represent the
  16724. // same axis), used as axis directions evenly spread on a sphere.
  16725. const _axisDirections = [
  16726. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  16727. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  16728. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  16729. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  16730. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  16731. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  16732. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  16733. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  16734. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  16735. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  16736. ];
  16737. const _origin = /*@__PURE__*/ new Vector3();
  16738. // maps blur materials to their uniforms dictionary
  16739. const _uniformsMap = new WeakMap();
  16740. // WebGPU Face indices
  16741. const _faceLib = [
  16742. 3, 1, 5,
  16743. 0, 4, 2
  16744. ];
  16745. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  16746. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  16747. /**
  16748. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  16749. * (PMREM) from a cubeMap environment texture. This allows different levels of
  16750. * blur to be quickly accessed based on material roughness. It is packed into a
  16751. * special CubeUV format that allows us to perform custom interpolation so that
  16752. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  16753. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  16754. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  16755. * higher roughness levels. In this way we maintain resolution to smoothly
  16756. * interpolate diffuse lighting while limiting sampling computation.
  16757. *
  16758. * Paper: Fast, Accurate Image-Based Lighting:
  16759. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  16760. */
  16761. class PMREMGenerator {
  16762. /**
  16763. * Constructs a new PMREM generator.
  16764. *
  16765. * @param {Renderer} renderer - The renderer.
  16766. */
  16767. constructor( renderer ) {
  16768. this._renderer = renderer;
  16769. this._pingPongRenderTarget = null;
  16770. this._lodMax = 0;
  16771. this._cubeSize = 0;
  16772. this._lodPlanes = [];
  16773. this._sizeLods = [];
  16774. this._sigmas = [];
  16775. this._lodMeshes = [];
  16776. this._blurMaterial = null;
  16777. this._cubemapMaterial = null;
  16778. this._equirectMaterial = null;
  16779. this._backgroundBox = null;
  16780. }
  16781. get _hasInitialized() {
  16782. return this._renderer.hasInitialized();
  16783. }
  16784. /**
  16785. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16786. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16787. * in radians to be applied to the scene before PMREM generation. Optional near
  16788. * and far planes ensure the scene is rendered in its entirety.
  16789. *
  16790. * @param {Scene} scene - The scene to be captured.
  16791. * @param {number} [sigma=0] - The blur radius in radians.
  16792. * @param {number} [near=0.1] - The near plane distance.
  16793. * @param {number} [far=100] - The far plane distance.
  16794. * @param {Object} [options={}] - The configuration options.
  16795. * @param {number} [options.size=256] - The texture size of the PMREM.
  16796. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  16797. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16798. * @return {RenderTarget} The resulting PMREM.
  16799. * @see {@link PMREMGenerator#fromSceneAsync}
  16800. */
  16801. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16802. const {
  16803. size = 256,
  16804. position = _origin,
  16805. renderTarget = null,
  16806. } = options;
  16807. this._setSize( size );
  16808. if ( this._hasInitialized === false ) {
  16809. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  16810. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16811. options.renderTarget = cubeUVRenderTarget;
  16812. this.fromSceneAsync( scene, sigma, near, far, options );
  16813. return cubeUVRenderTarget;
  16814. }
  16815. _oldTarget = this._renderer.getRenderTarget();
  16816. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16817. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16818. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16819. cubeUVRenderTarget.depthBuffer = true;
  16820. this._init( cubeUVRenderTarget );
  16821. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  16822. if ( sigma > 0 ) {
  16823. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  16824. }
  16825. this._applyPMREM( cubeUVRenderTarget );
  16826. this._cleanup( cubeUVRenderTarget );
  16827. return cubeUVRenderTarget;
  16828. }
  16829. /**
  16830. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16831. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16832. * in radians to be applied to the scene before PMREM generation. Optional near
  16833. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  16834. * is placed at the origin).
  16835. *
  16836. * @param {Scene} scene - The scene to be captured.
  16837. * @param {number} [sigma=0] - The blur radius in radians.
  16838. * @param {number} [near=0.1] - The near plane distance.
  16839. * @param {number} [far=100] - The far plane distance.
  16840. * @param {Object} [options={}] - The configuration options.
  16841. * @param {number} [options.size=256] - The texture size of the PMREM.
  16842. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  16843. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16844. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  16845. * @see {@link PMREMGenerator#fromScene}
  16846. */
  16847. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16848. if ( this._hasInitialized === false ) await this._renderer.init();
  16849. return this.fromScene( scene, sigma, near, far, options );
  16850. }
  16851. /**
  16852. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16853. * or HDR. The ideal input image size is 1k (1024 x 512),
  16854. * as this matches best with the 256 x 256 cubemap output.
  16855. *
  16856. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16857. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16858. * @return {RenderTarget} The resulting PMREM.
  16859. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  16860. */
  16861. fromEquirectangular( equirectangular, renderTarget = null ) {
  16862. if ( this._hasInitialized === false ) {
  16863. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16864. this._setSizeFromTexture( equirectangular );
  16865. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16866. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16867. return cubeUVRenderTarget;
  16868. }
  16869. return this._fromTexture( equirectangular, renderTarget );
  16870. }
  16871. /**
  16872. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16873. * or HDR. The ideal input image size is 1k (1024 x 512),
  16874. * as this matches best with the 256 x 256 cubemap output.
  16875. *
  16876. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16877. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16878. * @return {Promise<RenderTarget>} The resulting PMREM.
  16879. * @see {@link PMREMGenerator#fromEquirectangular}
  16880. */
  16881. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16882. if ( this._hasInitialized === false ) await this._renderer.init();
  16883. return this._fromTexture( equirectangular, renderTarget );
  16884. }
  16885. /**
  16886. * Generates a PMREM from an cubemap texture, which can be either LDR
  16887. * or HDR. The ideal input cube size is 256 x 256,
  16888. * as this matches best with the 256 x 256 cubemap output.
  16889. *
  16890. * @param {Texture} cubemap - The cubemap texture to be converted.
  16891. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16892. * @return {RenderTarget} The resulting PMREM.
  16893. * @see {@link PMREMGenerator#fromCubemapAsync}
  16894. */
  16895. fromCubemap( cubemap, renderTarget = null ) {
  16896. if ( this._hasInitialized === false ) {
  16897. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16898. this._setSizeFromTexture( cubemap );
  16899. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16900. this.fromCubemapAsync( cubemap, renderTarget );
  16901. return cubeUVRenderTarget;
  16902. }
  16903. return this._fromTexture( cubemap, renderTarget );
  16904. }
  16905. /**
  16906. * Generates a PMREM from an cubemap texture, which can be either LDR
  16907. * or HDR. The ideal input cube size is 256 x 256,
  16908. * with the 256 x 256 cubemap output.
  16909. *
  16910. * @param {Texture} cubemap - The cubemap texture to be converted.
  16911. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16912. * @return {Promise<RenderTarget>} The resulting PMREM.
  16913. * @see {@link PMREMGenerator#fromCubemap}
  16914. */
  16915. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16916. if ( this._hasInitialized === false ) await this._renderer.init();
  16917. return this._fromTexture( cubemap, renderTarget );
  16918. }
  16919. /**
  16920. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16921. * your texture's network fetch for increased concurrency.
  16922. *
  16923. * @returns {Promise}
  16924. */
  16925. async compileCubemapShader() {
  16926. if ( this._cubemapMaterial === null ) {
  16927. this._cubemapMaterial = _getCubemapMaterial();
  16928. await this._compileMaterial( this._cubemapMaterial );
  16929. }
  16930. }
  16931. /**
  16932. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16933. * your texture's network fetch for increased concurrency.
  16934. *
  16935. * @returns {Promise}
  16936. */
  16937. async compileEquirectangularShader() {
  16938. if ( this._equirectMaterial === null ) {
  16939. this._equirectMaterial = _getEquirectMaterial();
  16940. await this._compileMaterial( this._equirectMaterial );
  16941. }
  16942. }
  16943. /**
  16944. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16945. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16946. * one of them will cause any others to also become unusable.
  16947. */
  16948. dispose() {
  16949. this._dispose();
  16950. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16951. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16952. if ( this._backgroundBox !== null ) {
  16953. this._backgroundBox.geometry.dispose();
  16954. this._backgroundBox.material.dispose();
  16955. }
  16956. }
  16957. // private interface
  16958. _setSizeFromTexture( texture ) {
  16959. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16960. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16961. } else { // Equirectangular
  16962. this._setSize( texture.image.width / 4 );
  16963. }
  16964. }
  16965. _setSize( cubeSize ) {
  16966. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16967. this._cubeSize = Math.pow( 2, this._lodMax );
  16968. }
  16969. _dispose() {
  16970. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16971. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16972. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16973. this._lodPlanes[ i ].dispose();
  16974. }
  16975. }
  16976. _cleanup( outputTarget ) {
  16977. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16978. outputTarget.scissorTest = false;
  16979. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16980. }
  16981. _fromTexture( texture, renderTarget ) {
  16982. this._setSizeFromTexture( texture );
  16983. _oldTarget = this._renderer.getRenderTarget();
  16984. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16985. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16986. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16987. this._init( cubeUVRenderTarget );
  16988. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16989. this._applyPMREM( cubeUVRenderTarget );
  16990. this._cleanup( cubeUVRenderTarget );
  16991. return cubeUVRenderTarget;
  16992. }
  16993. _allocateTarget() {
  16994. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16995. const height = 4 * this._cubeSize;
  16996. const cubeUVRenderTarget = _createRenderTarget( width, height );
  16997. return cubeUVRenderTarget;
  16998. }
  16999. _init( renderTarget ) {
  17000. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17001. if ( this._pingPongRenderTarget !== null ) {
  17002. this._dispose();
  17003. }
  17004. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17005. const { _lodMax } = this;
  17006. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  17007. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17008. }
  17009. }
  17010. async _compileMaterial( material ) {
  17011. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  17012. await this._renderer.compile( tmpMesh, _flatCamera );
  17013. }
  17014. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17015. const cubeCamera = _cubeCamera;
  17016. cubeCamera.near = near;
  17017. cubeCamera.far = far;
  17018. // px, py, pz, nx, ny, nz
  17019. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17020. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17021. const renderer = this._renderer;
  17022. const originalAutoClear = renderer.autoClear;
  17023. renderer.getClearColor( _clearColor$2 );
  17024. renderer.autoClear = false;
  17025. let backgroundBox = this._backgroundBox;
  17026. if ( backgroundBox === null ) {
  17027. const backgroundMaterial = new MeshBasicMaterial( {
  17028. name: 'PMREM.Background',
  17029. side: BackSide,
  17030. depthWrite: false,
  17031. depthTest: false
  17032. } );
  17033. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  17034. }
  17035. let useSolidColor = false;
  17036. const background = scene.background;
  17037. if ( background ) {
  17038. if ( background.isColor ) {
  17039. backgroundBox.material.color.copy( background );
  17040. scene.background = null;
  17041. useSolidColor = true;
  17042. }
  17043. } else {
  17044. backgroundBox.material.color.copy( _clearColor$2 );
  17045. useSolidColor = true;
  17046. }
  17047. renderer.setRenderTarget( cubeUVRenderTarget );
  17048. renderer.clear();
  17049. if ( useSolidColor ) {
  17050. renderer.render( backgroundBox, cubeCamera );
  17051. }
  17052. for ( let i = 0; i < 6; i ++ ) {
  17053. const col = i % 3;
  17054. if ( col === 0 ) {
  17055. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17056. cubeCamera.position.set( position.x, position.y, position.z );
  17057. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17058. } else if ( col === 1 ) {
  17059. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17060. cubeCamera.position.set( position.x, position.y, position.z );
  17061. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17062. } else {
  17063. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17064. cubeCamera.position.set( position.x, position.y, position.z );
  17065. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17066. }
  17067. const size = this._cubeSize;
  17068. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17069. renderer.render( scene, cubeCamera );
  17070. }
  17071. renderer.autoClear = originalAutoClear;
  17072. scene.background = background;
  17073. }
  17074. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17075. const renderer = this._renderer;
  17076. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17077. if ( isCubeTexture ) {
  17078. if ( this._cubemapMaterial === null ) {
  17079. this._cubemapMaterial = _getCubemapMaterial( texture );
  17080. }
  17081. } else {
  17082. if ( this._equirectMaterial === null ) {
  17083. this._equirectMaterial = _getEquirectMaterial( texture );
  17084. }
  17085. }
  17086. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17087. material.fragmentNode.value = texture;
  17088. const mesh = this._lodMeshes[ 0 ];
  17089. mesh.material = material;
  17090. const size = this._cubeSize;
  17091. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17092. renderer.setRenderTarget( cubeUVRenderTarget );
  17093. renderer.render( mesh, _flatCamera );
  17094. }
  17095. _applyPMREM( cubeUVRenderTarget ) {
  17096. const renderer = this._renderer;
  17097. const autoClear = renderer.autoClear;
  17098. renderer.autoClear = false;
  17099. const n = this._lodPlanes.length;
  17100. for ( let i = 1; i < n; i ++ ) {
  17101. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  17102. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  17103. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  17104. }
  17105. renderer.autoClear = autoClear;
  17106. }
  17107. /**
  17108. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17109. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17110. * the blur latitudinally (around the poles), and then longitudinally (towards
  17111. * the poles) to approximate the orthogonally-separable blur. It is least
  17112. * accurate at the poles, but still does a decent job.
  17113. *
  17114. * @private
  17115. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17116. * @param {number} lodIn - The input level-of-detail.
  17117. * @param {number} lodOut - The output level-of-detail.
  17118. * @param {number} sigma - The blur radius in radians.
  17119. * @param {Vector3} [poleAxis] - The pole axis.
  17120. */
  17121. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17122. const pingPongRenderTarget = this._pingPongRenderTarget;
  17123. this._halfBlur(
  17124. cubeUVRenderTarget,
  17125. pingPongRenderTarget,
  17126. lodIn,
  17127. lodOut,
  17128. sigma,
  17129. 'latitudinal',
  17130. poleAxis );
  17131. this._halfBlur(
  17132. pingPongRenderTarget,
  17133. cubeUVRenderTarget,
  17134. lodOut,
  17135. lodOut,
  17136. sigma,
  17137. 'longitudinal',
  17138. poleAxis );
  17139. }
  17140. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17141. const renderer = this._renderer;
  17142. const blurMaterial = this._blurMaterial;
  17143. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17144. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  17145. }
  17146. // Number of standard deviations at which to cut off the discrete approximation.
  17147. const STANDARD_DEVIATIONS = 3;
  17148. const blurMesh = this._lodMeshes[ lodOut ];
  17149. blurMesh.material = blurMaterial;
  17150. const blurUniforms = _uniformsMap.get( blurMaterial );
  17151. const pixels = this._sizeLods[ lodIn ] - 1;
  17152. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17153. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17154. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17155. if ( samples > MAX_SAMPLES ) {
  17156. console.warn( `sigmaRadians, ${
  17157. sigmaRadians}, is too large and will clip, as it requested ${
  17158. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17159. }
  17160. const weights = [];
  17161. let sum = 0;
  17162. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17163. const x = i / sigmaPixels;
  17164. const weight = Math.exp( - x * x / 2 );
  17165. weights.push( weight );
  17166. if ( i === 0 ) {
  17167. sum += weight;
  17168. } else if ( i < samples ) {
  17169. sum += 2 * weight;
  17170. }
  17171. }
  17172. for ( let i = 0; i < weights.length; i ++ ) {
  17173. weights[ i ] = weights[ i ] / sum;
  17174. }
  17175. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17176. blurUniforms.envMap.value = targetIn.texture;
  17177. blurUniforms.samples.value = samples;
  17178. blurUniforms.weights.array = weights;
  17179. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17180. if ( poleAxis ) {
  17181. blurUniforms.poleAxis.value = poleAxis;
  17182. }
  17183. const { _lodMax } = this;
  17184. blurUniforms.dTheta.value = radiansPerPixel;
  17185. blurUniforms.mipInt.value = _lodMax - lodIn;
  17186. const outputSize = this._sizeLods[ lodOut ];
  17187. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17188. const y = 4 * ( this._cubeSize - outputSize );
  17189. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17190. renderer.setRenderTarget( targetOut );
  17191. renderer.render( blurMesh, _flatCamera );
  17192. }
  17193. }
  17194. function _createPlanes( lodMax ) {
  17195. const lodPlanes = [];
  17196. const sizeLods = [];
  17197. const sigmas = [];
  17198. const lodMeshes = [];
  17199. let lod = lodMax;
  17200. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17201. for ( let i = 0; i < totalLods; i ++ ) {
  17202. const sizeLod = Math.pow( 2, lod );
  17203. sizeLods.push( sizeLod );
  17204. let sigma = 1.0 / sizeLod;
  17205. if ( i > lodMax - LOD_MIN ) {
  17206. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17207. } else if ( i === 0 ) {
  17208. sigma = 0;
  17209. }
  17210. sigmas.push( sigma );
  17211. const texelSize = 1.0 / ( sizeLod - 2 );
  17212. const min = - texelSize;
  17213. const max = 1 + texelSize;
  17214. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17215. const cubeFaces = 6;
  17216. const vertices = 6;
  17217. const positionSize = 3;
  17218. const uvSize = 2;
  17219. const faceIndexSize = 1;
  17220. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17221. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17222. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17223. for ( let face = 0; face < cubeFaces; face ++ ) {
  17224. const x = ( face % 3 ) * 2 / 3 - 1;
  17225. const y = face > 2 ? 0 : -1;
  17226. const coordinates = [
  17227. x, y, 0,
  17228. x + 2 / 3, y, 0,
  17229. x + 2 / 3, y + 1, 0,
  17230. x, y, 0,
  17231. x + 2 / 3, y + 1, 0,
  17232. x, y + 1, 0
  17233. ];
  17234. const faceIdx = _faceLib[ face ];
  17235. position.set( coordinates, positionSize * vertices * faceIdx );
  17236. uv.set( uv1, uvSize * vertices * faceIdx );
  17237. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17238. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17239. }
  17240. const planes = new BufferGeometry();
  17241. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17242. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17243. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17244. lodPlanes.push( planes );
  17245. lodMeshes.push( new Mesh( planes, null ) );
  17246. if ( lod > LOD_MIN ) {
  17247. lod --;
  17248. }
  17249. }
  17250. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17251. }
  17252. function _createRenderTarget( width, height ) {
  17253. const params = {
  17254. magFilter: LinearFilter,
  17255. minFilter: LinearFilter,
  17256. generateMipmaps: false,
  17257. type: HalfFloatType,
  17258. format: RGBAFormat,
  17259. colorSpace: LinearSRGBColorSpace,
  17260. //depthBuffer: false
  17261. };
  17262. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17263. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17264. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17265. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17266. cubeUVRenderTarget.scissorTest = true;
  17267. return cubeUVRenderTarget;
  17268. }
  17269. function _setViewport( target, x, y, width, height ) {
  17270. target.viewport.set( x, y, width, height );
  17271. target.scissor.set( x, y, width, height );
  17272. }
  17273. function _getMaterial( type ) {
  17274. const material = new NodeMaterial();
  17275. material.depthTest = false;
  17276. material.depthWrite = false;
  17277. material.blending = NoBlending;
  17278. material.name = `PMREM_${ type }`;
  17279. return material;
  17280. }
  17281. function _getBlurShader( lodMax, width, height ) {
  17282. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17283. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17284. const dTheta = uniform( 0 );
  17285. const n = float( MAX_SAMPLES );
  17286. const latitudinal = uniform( 0 ); // false, bool
  17287. const samples = uniform( 1 ); // int
  17288. const envMap = texture( null );
  17289. const mipInt = uniform( 0 ); // int
  17290. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17291. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17292. const CUBEUV_MAX_MIP = float( lodMax );
  17293. const materialUniforms = {
  17294. n,
  17295. latitudinal,
  17296. weights,
  17297. poleAxis,
  17298. outputDirection: _outputDirection,
  17299. dTheta,
  17300. samples,
  17301. envMap,
  17302. mipInt,
  17303. CUBEUV_TEXEL_WIDTH,
  17304. CUBEUV_TEXEL_HEIGHT,
  17305. CUBEUV_MAX_MIP
  17306. };
  17307. const material = _getMaterial( 'blur' );
  17308. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17309. _uniformsMap.set( material, materialUniforms );
  17310. return material;
  17311. }
  17312. function _getCubemapMaterial( envTexture ) {
  17313. const material = _getMaterial( 'cubemap' );
  17314. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17315. return material;
  17316. }
  17317. function _getEquirectMaterial( envTexture ) {
  17318. const material = _getMaterial( 'equirect' );
  17319. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17320. return material;
  17321. }
  17322. const _cache = new WeakMap();
  17323. /**
  17324. * Generates the cubeUV size based on the given image height.
  17325. *
  17326. * @private
  17327. * @param {number} imageHeight - The image height.
  17328. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17329. */
  17330. function _generateCubeUVSize( imageHeight ) {
  17331. const maxMip = Math.log2( imageHeight ) - 2;
  17332. const texelHeight = 1.0 / imageHeight;
  17333. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17334. return { texelWidth, texelHeight, maxMip };
  17335. }
  17336. /**
  17337. * Generates a PMREM from the given texture.
  17338. *
  17339. * @private
  17340. * @param {Texture} texture - The texture to create the PMREM for.
  17341. * @param {Renderer} renderer - The renderer.
  17342. * @param {PMREMGenerator} generator - The PMREM generator.
  17343. * @return {?Texture} The PMREM.
  17344. */
  17345. function _getPMREMFromTexture( texture, renderer, generator ) {
  17346. const cache = _getCache( renderer );
  17347. let cacheTexture = cache.get( texture );
  17348. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17349. if ( pmremVersion !== texture.pmremVersion ) {
  17350. const image = texture.image;
  17351. if ( texture.isCubeTexture ) {
  17352. if ( isCubeMapReady( image ) ) {
  17353. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17354. } else {
  17355. return null;
  17356. }
  17357. } else {
  17358. if ( isEquirectangularMapReady( image ) ) {
  17359. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17360. } else {
  17361. return null;
  17362. }
  17363. }
  17364. cacheTexture.pmremVersion = texture.pmremVersion;
  17365. cache.set( texture, cacheTexture );
  17366. }
  17367. return cacheTexture.texture;
  17368. }
  17369. /**
  17370. * Returns a cache that stores generated PMREMs for the respective textures.
  17371. * A cache must be maintained per renderer since PMREMs are render target textures
  17372. * which can't be shared across render contexts.
  17373. *
  17374. * @private
  17375. * @param {Renderer} renderer - The renderer.
  17376. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17377. */
  17378. function _getCache( renderer ) {
  17379. let rendererCache = _cache.get( renderer );
  17380. if ( rendererCache === undefined ) {
  17381. rendererCache = new WeakMap();
  17382. _cache.set( renderer, rendererCache );
  17383. }
  17384. return rendererCache;
  17385. }
  17386. /**
  17387. * This node represents a PMREM which is a special type of preprocessed
  17388. * environment map intended for PBR materials.
  17389. *
  17390. * ```js
  17391. * const material = new MeshStandardNodeMaterial();
  17392. * material.envNode = pmremTexture( envMap );
  17393. * ```
  17394. *
  17395. * @augments TempNode
  17396. */
  17397. class PMREMNode extends TempNode {
  17398. static get type() {
  17399. return 'PMREMNode';
  17400. }
  17401. /**
  17402. * Constructs a new function overloading node.
  17403. *
  17404. * @param {Texture} value - The input texture.
  17405. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17406. * @param {Node<float>} [levelNode=null] - The level node.
  17407. */
  17408. constructor( value, uvNode = null, levelNode = null ) {
  17409. super( 'vec3' );
  17410. /**
  17411. * Reference to the input texture.
  17412. *
  17413. * @private
  17414. * @type {Texture}
  17415. */
  17416. this._value = value;
  17417. /**
  17418. * Reference to the generated PMREM.
  17419. *
  17420. * @private
  17421. * @type {Texture | null}
  17422. * @default null
  17423. */
  17424. this._pmrem = null;
  17425. /**
  17426. * The uv node.
  17427. *
  17428. * @type {Node<vec2>}
  17429. */
  17430. this.uvNode = uvNode;
  17431. /**
  17432. * The level node.
  17433. *
  17434. * @type {Node<float>}
  17435. */
  17436. this.levelNode = levelNode;
  17437. /**
  17438. * Reference to a PMREM generator.
  17439. *
  17440. * @private
  17441. * @type {?PMREMGenerator}
  17442. * @default null
  17443. */
  17444. this._generator = null;
  17445. const defaultTexture = new Texture();
  17446. defaultTexture.isRenderTargetTexture = true;
  17447. /**
  17448. * The texture node holding the generated PMREM.
  17449. *
  17450. * @private
  17451. * @type {TextureNode}
  17452. */
  17453. this._texture = texture( defaultTexture );
  17454. /**
  17455. * A uniform representing the PMREM's width.
  17456. *
  17457. * @private
  17458. * @type {UniformNode<float>}
  17459. */
  17460. this._width = uniform( 0 );
  17461. /**
  17462. * A uniform representing the PMREM's height.
  17463. *
  17464. * @private
  17465. * @type {UniformNode<float>}
  17466. */
  17467. this._height = uniform( 0 );
  17468. /**
  17469. * A uniform representing the PMREM's max Mip.
  17470. *
  17471. * @private
  17472. * @type {UniformNode<float>}
  17473. */
  17474. this._maxMip = uniform( 0 );
  17475. /**
  17476. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17477. *
  17478. * @type {string}
  17479. * @default 'render'
  17480. */
  17481. this.updateBeforeType = NodeUpdateType.RENDER;
  17482. }
  17483. set value( value ) {
  17484. this._value = value;
  17485. this._pmrem = null;
  17486. }
  17487. /**
  17488. * The node's texture value.
  17489. *
  17490. * @type {Texture}
  17491. */
  17492. get value() {
  17493. return this._value;
  17494. }
  17495. /**
  17496. * Uses the given PMREM texture to update internal values.
  17497. *
  17498. * @param {Texture} texture - The PMREM texture.
  17499. */
  17500. updateFromTexture( texture ) {
  17501. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17502. this._texture.value = texture;
  17503. this._width.value = cubeUVSize.texelWidth;
  17504. this._height.value = cubeUVSize.texelHeight;
  17505. this._maxMip.value = cubeUVSize.maxMip;
  17506. }
  17507. updateBefore( frame ) {
  17508. let pmrem = this._pmrem;
  17509. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17510. const texture = this._value;
  17511. if ( pmremVersion !== texture.pmremVersion ) {
  17512. if ( texture.isPMREMTexture === true ) {
  17513. pmrem = texture;
  17514. } else {
  17515. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17516. }
  17517. if ( pmrem !== null ) {
  17518. this._pmrem = pmrem;
  17519. this.updateFromTexture( pmrem );
  17520. }
  17521. }
  17522. }
  17523. setup( builder ) {
  17524. if ( this._generator === null ) {
  17525. this._generator = new PMREMGenerator( builder.renderer );
  17526. }
  17527. this.updateBefore( builder );
  17528. //
  17529. let uvNode = this.uvNode;
  17530. if ( uvNode === null && builder.context.getUV ) {
  17531. uvNode = builder.context.getUV( this );
  17532. }
  17533. //
  17534. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  17535. //
  17536. let levelNode = this.levelNode;
  17537. if ( levelNode === null && builder.context.getTextureLevel ) {
  17538. levelNode = builder.context.getTextureLevel( this );
  17539. }
  17540. //
  17541. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  17542. }
  17543. dispose() {
  17544. super.dispose();
  17545. if ( this._generator !== null ) this._generator.dispose();
  17546. }
  17547. }
  17548. /**
  17549. * Returns `true` if the given cube map image has been fully loaded.
  17550. *
  17551. * @private
  17552. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  17553. * @return {boolean} Whether the given cube map is ready or not.
  17554. */
  17555. function isCubeMapReady( image ) {
  17556. if ( image === null || image === undefined ) return false;
  17557. let count = 0;
  17558. const length = 6;
  17559. for ( let i = 0; i < length; i ++ ) {
  17560. if ( image[ i ] !== undefined ) count ++;
  17561. }
  17562. return count === length;
  17563. }
  17564. /**
  17565. * Returns `true` if the given equirectangular image has been fully loaded.
  17566. *
  17567. * @private
  17568. * @param {(Image|Object)} image - The equirectangular image.
  17569. * @return {boolean} Whether the given cube map is ready or not.
  17570. */
  17571. function isEquirectangularMapReady( image ) {
  17572. if ( image === null || image === undefined ) return false;
  17573. return image.height > 0;
  17574. }
  17575. /**
  17576. * TSL function for creating a PMREM node.
  17577. *
  17578. * @tsl
  17579. * @function
  17580. * @param {Texture} value - The input texture.
  17581. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  17582. * @param {?Node<float>} [levelNode=null] - The level node.
  17583. * @returns {PMREMNode}
  17584. */
  17585. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  17586. const _envNodeCache = new WeakMap();
  17587. /**
  17588. * Represents a physical model for Image-based lighting (IBL). The environment
  17589. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  17590. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  17591. *
  17592. * @augments LightingNode
  17593. */
  17594. class EnvironmentNode extends LightingNode {
  17595. static get type() {
  17596. return 'EnvironmentNode';
  17597. }
  17598. /**
  17599. * Constructs a new environment node.
  17600. *
  17601. * @param {Node} [envNode=null] - A node representing the environment.
  17602. */
  17603. constructor( envNode = null ) {
  17604. super();
  17605. /**
  17606. * A node representing the environment.
  17607. *
  17608. * @type {?Node}
  17609. * @default null
  17610. */
  17611. this.envNode = envNode;
  17612. }
  17613. setup( builder ) {
  17614. const { material } = builder;
  17615. let envNode = this.envNode;
  17616. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  17617. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  17618. let cacheEnvNode = _envNodeCache.get( value );
  17619. if ( cacheEnvNode === undefined ) {
  17620. cacheEnvNode = pmremTexture( value );
  17621. _envNodeCache.set( value, cacheEnvNode );
  17622. }
  17623. envNode = cacheEnvNode;
  17624. }
  17625. //
  17626. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  17627. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  17628. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  17629. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  17630. const isolateRadiance = cache( radiance );
  17631. const isolateIrradiance = cache( irradiance );
  17632. //
  17633. builder.context.radiance.addAssign( isolateRadiance );
  17634. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  17635. //
  17636. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  17637. if ( clearcoatRadiance ) {
  17638. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  17639. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  17640. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  17641. }
  17642. }
  17643. }
  17644. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  17645. let reflectVec = null;
  17646. return {
  17647. getUV: () => {
  17648. if ( reflectVec === null ) {
  17649. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  17650. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  17651. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  17652. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  17653. }
  17654. return reflectVec;
  17655. },
  17656. getTextureLevel: () => {
  17657. return roughnessNode;
  17658. }
  17659. };
  17660. };
  17661. const createIrradianceContext = ( normalWorldNode ) => {
  17662. return {
  17663. getUV: () => {
  17664. return normalWorldNode;
  17665. },
  17666. getTextureLevel: () => {
  17667. return float( 1.0 );
  17668. }
  17669. };
  17670. };
  17671. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  17672. /**
  17673. * Node material version of {@link MeshStandardMaterial}.
  17674. *
  17675. * @augments NodeMaterial
  17676. */
  17677. class MeshStandardNodeMaterial extends NodeMaterial {
  17678. static get type() {
  17679. return 'MeshStandardNodeMaterial';
  17680. }
  17681. /**
  17682. * Constructs a new mesh standard node material.
  17683. *
  17684. * @param {Object} [parameters] - The configuration parameter.
  17685. */
  17686. constructor( parameters ) {
  17687. super();
  17688. /**
  17689. * This flag can be used for type testing.
  17690. *
  17691. * @type {boolean}
  17692. * @readonly
  17693. * @default true
  17694. */
  17695. this.isMeshStandardNodeMaterial = true;
  17696. /**
  17697. * Set to `true` because standard materials react on lights.
  17698. *
  17699. * @type {boolean}
  17700. * @default true
  17701. */
  17702. this.lights = true;
  17703. /**
  17704. * The emissive color of standard materials is by default inferred from the `emissive`,
  17705. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  17706. * overwrite the default and define the emissive color with a node instead.
  17707. *
  17708. * If you don't want to overwrite the emissive color but modify the existing
  17709. * value instead, use {@link materialEmissive}.
  17710. *
  17711. * @type {?Node<vec3>}
  17712. * @default null
  17713. */
  17714. this.emissiveNode = null;
  17715. /**
  17716. * The metalness of standard materials is by default inferred from the `metalness`,
  17717. * and `metalnessMap` properties. This node property allows to
  17718. * overwrite the default and define the metalness with a node instead.
  17719. *
  17720. * If you don't want to overwrite the metalness but modify the existing
  17721. * value instead, use {@link materialMetalness}.
  17722. *
  17723. * @type {?Node<float>}
  17724. * @default null
  17725. */
  17726. this.metalnessNode = null;
  17727. /**
  17728. * The roughness of standard materials is by default inferred from the `roughness`,
  17729. * and `roughnessMap` properties. This node property allows to
  17730. * overwrite the default and define the roughness with a node instead.
  17731. *
  17732. * If you don't want to overwrite the roughness but modify the existing
  17733. * value instead, use {@link materialRoughness}.
  17734. *
  17735. * @type {?Node<float>}
  17736. * @default null
  17737. */
  17738. this.roughnessNode = null;
  17739. this.setDefaultValues( _defaultValues$6 );
  17740. this.setValues( parameters );
  17741. }
  17742. /**
  17743. * Overwritten since this type of material uses {@link EnvironmentNode}
  17744. * to implement the PBR (PMREM based) environment mapping. Besides, the
  17745. * method honors `Scene.environment`.
  17746. *
  17747. * @param {NodeBuilder} builder - The current node builder.
  17748. * @return {?EnvironmentNode<vec3>} The environment node.
  17749. */
  17750. setupEnvironment( builder ) {
  17751. let envNode = super.setupEnvironment( builder );
  17752. if ( envNode === null && builder.environmentNode ) {
  17753. envNode = builder.environmentNode;
  17754. }
  17755. return envNode ? new EnvironmentNode( envNode ) : null;
  17756. }
  17757. /**
  17758. * Setups the lighting model.
  17759. *
  17760. * @return {PhysicalLightingModel} The lighting model.
  17761. */
  17762. setupLightingModel( /*builder*/ ) {
  17763. return new PhysicalLightingModel();
  17764. }
  17765. /**
  17766. * Setups the specular related node variables.
  17767. */
  17768. setupSpecular() {
  17769. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  17770. specularColor.assign( specularColorNode );
  17771. specularF90.assign( 1.0 );
  17772. }
  17773. /**
  17774. * Setups the standard specific node variables.
  17775. *
  17776. * @param {NodeBuilder} builder - The current node builder.
  17777. */
  17778. setupVariants() {
  17779. // METALNESS
  17780. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  17781. metalness.assign( metalnessNode );
  17782. // ROUGHNESS
  17783. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  17784. roughnessNode = getRoughness( { roughness: roughnessNode } );
  17785. roughness.assign( roughnessNode );
  17786. // SPECULAR COLOR
  17787. this.setupSpecular();
  17788. // DIFFUSE COLOR
  17789. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  17790. }
  17791. copy( source ) {
  17792. this.emissiveNode = source.emissiveNode;
  17793. this.metalnessNode = source.metalnessNode;
  17794. this.roughnessNode = source.roughnessNode;
  17795. return super.copy( source );
  17796. }
  17797. }
  17798. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  17799. /**
  17800. * Node material version of {@link MeshPhysicalMaterial}.
  17801. *
  17802. * @augments MeshStandardNodeMaterial
  17803. */
  17804. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  17805. static get type() {
  17806. return 'MeshPhysicalNodeMaterial';
  17807. }
  17808. /**
  17809. * Constructs a new mesh physical node material.
  17810. *
  17811. * @param {Object} [parameters] - The configuration parameter.
  17812. */
  17813. constructor( parameters ) {
  17814. super();
  17815. /**
  17816. * This flag can be used for type testing.
  17817. *
  17818. * @type {boolean}
  17819. * @readonly
  17820. * @default true
  17821. */
  17822. this.isMeshPhysicalNodeMaterial = true;
  17823. /**
  17824. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  17825. * and `clearcoatMap` properties. This node property allows to overwrite the default
  17826. * and define the clearcoat with a node instead.
  17827. *
  17828. * If you don't want to overwrite the clearcoat but modify the existing
  17829. * value instead, use {@link materialClearcoat}.
  17830. *
  17831. * @type {?Node<float>}
  17832. * @default null
  17833. */
  17834. this.clearcoatNode = null;
  17835. /**
  17836. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  17837. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  17838. * and define the clearcoat roughness with a node instead.
  17839. *
  17840. * If you don't want to overwrite the clearcoat roughness but modify the existing
  17841. * value instead, use {@link materialClearcoatRoughness}.
  17842. *
  17843. * @type {?Node<float>}
  17844. * @default null
  17845. */
  17846. this.clearcoatRoughnessNode = null;
  17847. /**
  17848. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  17849. * property. This node property allows to overwrite the default
  17850. * and define the clearcoat normal with a node instead.
  17851. *
  17852. * If you don't want to overwrite the clearcoat normal but modify the existing
  17853. * value instead, use {@link materialClearcoatNormal}.
  17854. *
  17855. * @type {?Node<vec3>}
  17856. * @default null
  17857. */
  17858. this.clearcoatNormalNode = null;
  17859. /**
  17860. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  17861. * and `sheenColorMap` properties. This node property allows to overwrite the default
  17862. * and define the sheen with a node instead.
  17863. *
  17864. * If you don't want to overwrite the sheen but modify the existing
  17865. * value instead, use {@link materialSheen}.
  17866. *
  17867. * @type {?Node<vec3>}
  17868. * @default null
  17869. */
  17870. this.sheenNode = null;
  17871. /**
  17872. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  17873. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  17874. * and define the sheen roughness with a node instead.
  17875. *
  17876. * If you don't want to overwrite the sheen roughness but modify the existing
  17877. * value instead, use {@link materialSheenRoughness}.
  17878. *
  17879. * @type {?Node<float>}
  17880. * @default null
  17881. */
  17882. this.sheenRoughnessNode = null;
  17883. /**
  17884. * The iridescence of physical materials is by default inferred from the `iridescence`
  17885. * property. This node property allows to overwrite the default
  17886. * and define the iridescence with a node instead.
  17887. *
  17888. * If you don't want to overwrite the iridescence but modify the existing
  17889. * value instead, use {@link materialIridescence}.
  17890. *
  17891. * @type {?Node<float>}
  17892. * @default null
  17893. */
  17894. this.iridescenceNode = null;
  17895. /**
  17896. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  17897. * property. This node property allows to overwrite the default
  17898. * and define the iridescence IOR with a node instead.
  17899. *
  17900. * If you don't want to overwrite the iridescence IOR but modify the existing
  17901. * value instead, use {@link materialIridescenceIOR}.
  17902. *
  17903. * @type {?Node<float>}
  17904. * @default null
  17905. */
  17906. this.iridescenceIORNode = null;
  17907. /**
  17908. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  17909. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  17910. * and define the iridescence thickness with a node instead.
  17911. *
  17912. * If you don't want to overwrite the iridescence thickness but modify the existing
  17913. * value instead, use {@link materialIridescenceThickness}.
  17914. *
  17915. * @type {?Node<float>}
  17916. * @default null
  17917. */
  17918. this.iridescenceThicknessNode = null;
  17919. /**
  17920. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  17921. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  17922. * and define the specular intensity with a node instead.
  17923. *
  17924. * If you don't want to overwrite the specular intensity but modify the existing
  17925. * value instead, use {@link materialSpecularIntensity}.
  17926. *
  17927. * @type {?Node<float>}
  17928. * @default null
  17929. */
  17930. this.specularIntensityNode = null;
  17931. /**
  17932. * The specular color of physical materials is by default inferred from the `specularColor`
  17933. * and `specularColorMap` properties. This node property allows to overwrite the default
  17934. * and define the specular color with a node instead.
  17935. *
  17936. * If you don't want to overwrite the specular color but modify the existing
  17937. * value instead, use {@link materialSpecularColor}.
  17938. *
  17939. * @type {?Node<vec3>}
  17940. * @default null
  17941. */
  17942. this.specularColorNode = null;
  17943. /**
  17944. * The ior of physical materials is by default inferred from the `ior`
  17945. * property. This node property allows to overwrite the default
  17946. * and define the ior with a node instead.
  17947. *
  17948. * If you don't want to overwrite the ior but modify the existing
  17949. * value instead, use {@link materialIOR}.
  17950. *
  17951. * @type {?Node<float>}
  17952. * @default null
  17953. */
  17954. this.iorNode = null;
  17955. /**
  17956. * The transmission of physical materials is by default inferred from the `transmission` and
  17957. * `transmissionMap` properties. This node property allows to overwrite the default
  17958. * and define the transmission with a node instead.
  17959. *
  17960. * If you don't want to overwrite the transmission but modify the existing
  17961. * value instead, use {@link materialTransmission}.
  17962. *
  17963. * @type {?Node<float>}
  17964. * @default null
  17965. */
  17966. this.transmissionNode = null;
  17967. /**
  17968. * The thickness of physical materials is by default inferred from the `thickness` and
  17969. * `thicknessMap` properties. This node property allows to overwrite the default
  17970. * and define the thickness with a node instead.
  17971. *
  17972. * If you don't want to overwrite the thickness but modify the existing
  17973. * value instead, use {@link materialThickness}.
  17974. *
  17975. * @type {?Node<float>}
  17976. * @default null
  17977. */
  17978. this.thicknessNode = null;
  17979. /**
  17980. * The attenuation distance of physical materials is by default inferred from the
  17981. * `attenuationDistance` property. This node property allows to overwrite the default
  17982. * and define the attenuation distance with a node instead.
  17983. *
  17984. * If you don't want to overwrite the attenuation distance but modify the existing
  17985. * value instead, use {@link materialAttenuationDistance}.
  17986. *
  17987. * @type {?Node<float>}
  17988. * @default null
  17989. */
  17990. this.attenuationDistanceNode = null;
  17991. /**
  17992. * The attenuation color of physical materials is by default inferred from the
  17993. * `attenuationColor` property. This node property allows to overwrite the default
  17994. * and define the attenuation color with a node instead.
  17995. *
  17996. * If you don't want to overwrite the attenuation color but modify the existing
  17997. * value instead, use {@link materialAttenuationColor}.
  17998. *
  17999. * @type {?Node<vec3>}
  18000. * @default null
  18001. */
  18002. this.attenuationColorNode = null;
  18003. /**
  18004. * The dispersion of physical materials is by default inferred from the
  18005. * `dispersion` property. This node property allows to overwrite the default
  18006. * and define the dispersion with a node instead.
  18007. *
  18008. * If you don't want to overwrite the dispersion but modify the existing
  18009. * value instead, use {@link materialDispersion}.
  18010. *
  18011. * @type {?Node<float>}
  18012. * @default null
  18013. */
  18014. this.dispersionNode = null;
  18015. /**
  18016. * The anisotropy of physical materials is by default inferred from the
  18017. * `anisotropy` property. This node property allows to overwrite the default
  18018. * and define the anisotropy with a node instead.
  18019. *
  18020. * If you don't want to overwrite the anisotropy but modify the existing
  18021. * value instead, use {@link materialAnisotropy}.
  18022. *
  18023. * @type {?Node<float>}
  18024. * @default null
  18025. */
  18026. this.anisotropyNode = null;
  18027. this.setDefaultValues( _defaultValues$5 );
  18028. this.setValues( parameters );
  18029. }
  18030. /**
  18031. * Whether the lighting model should use clearcoat or not.
  18032. *
  18033. * @type {boolean}
  18034. * @default true
  18035. */
  18036. get useClearcoat() {
  18037. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18038. }
  18039. /**
  18040. * Whether the lighting model should use iridescence or not.
  18041. *
  18042. * @type {boolean}
  18043. * @default true
  18044. */
  18045. get useIridescence() {
  18046. return this.iridescence > 0 || this.iridescenceNode !== null;
  18047. }
  18048. /**
  18049. * Whether the lighting model should use sheen or not.
  18050. *
  18051. * @type {boolean}
  18052. * @default true
  18053. */
  18054. get useSheen() {
  18055. return this.sheen > 0 || this.sheenNode !== null;
  18056. }
  18057. /**
  18058. * Whether the lighting model should use anisotropy or not.
  18059. *
  18060. * @type {boolean}
  18061. * @default true
  18062. */
  18063. get useAnisotropy() {
  18064. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18065. }
  18066. /**
  18067. * Whether the lighting model should use transmission or not.
  18068. *
  18069. * @type {boolean}
  18070. * @default true
  18071. */
  18072. get useTransmission() {
  18073. return this.transmission > 0 || this.transmissionNode !== null;
  18074. }
  18075. /**
  18076. * Whether the lighting model should use dispersion or not.
  18077. *
  18078. * @type {boolean}
  18079. * @default true
  18080. */
  18081. get useDispersion() {
  18082. return this.dispersion > 0 || this.dispersionNode !== null;
  18083. }
  18084. /**
  18085. * Setups the specular related node variables.
  18086. */
  18087. setupSpecular() {
  18088. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18089. ior.assign( iorNode );
  18090. 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 ) );
  18091. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18092. }
  18093. /**
  18094. * Setups the lighting model.
  18095. *
  18096. * @return {PhysicalLightingModel} The lighting model.
  18097. */
  18098. setupLightingModel( /*builder*/ ) {
  18099. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18100. }
  18101. /**
  18102. * Setups the physical specific node variables.
  18103. *
  18104. * @param {NodeBuilder} builder - The current node builder.
  18105. */
  18106. setupVariants( builder ) {
  18107. super.setupVariants( builder );
  18108. // CLEARCOAT
  18109. if ( this.useClearcoat ) {
  18110. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18111. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18112. clearcoat.assign( clearcoatNode );
  18113. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18114. }
  18115. // SHEEN
  18116. if ( this.useSheen ) {
  18117. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18118. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18119. sheen.assign( sheenNode );
  18120. sheenRoughness.assign( sheenRoughnessNode );
  18121. }
  18122. // IRIDESCENCE
  18123. if ( this.useIridescence ) {
  18124. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18125. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18126. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18127. iridescence.assign( iridescenceNode );
  18128. iridescenceIOR.assign( iridescenceIORNode );
  18129. iridescenceThickness.assign( iridescenceThicknessNode );
  18130. }
  18131. // ANISOTROPY
  18132. if ( this.useAnisotropy ) {
  18133. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18134. anisotropy.assign( anisotropyV.length() );
  18135. If( anisotropy.equal( 0.0 ), () => {
  18136. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18137. } ).Else( () => {
  18138. anisotropyV.divAssign( vec2( anisotropy ) );
  18139. anisotropy.assign( anisotropy.saturate() );
  18140. } );
  18141. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18142. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18143. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18144. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18145. }
  18146. // TRANSMISSION
  18147. if ( this.useTransmission ) {
  18148. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  18149. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  18150. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  18151. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  18152. transmission.assign( transmissionNode );
  18153. thickness.assign( thicknessNode );
  18154. attenuationDistance.assign( attenuationDistanceNode );
  18155. attenuationColor.assign( attenuationColorNode );
  18156. if ( this.useDispersion ) {
  18157. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  18158. dispersion.assign( dispersionNode );
  18159. }
  18160. }
  18161. }
  18162. /**
  18163. * Setups the clearcoat normal node.
  18164. *
  18165. * @return {Node<vec3>} The clearcoat normal.
  18166. */
  18167. setupClearcoatNormal() {
  18168. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  18169. }
  18170. setup( builder ) {
  18171. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18172. super.setup( builder );
  18173. }
  18174. copy( source ) {
  18175. this.clearcoatNode = source.clearcoatNode;
  18176. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18177. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18178. this.sheenNode = source.sheenNode;
  18179. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18180. this.iridescenceNode = source.iridescenceNode;
  18181. this.iridescenceIORNode = source.iridescenceIORNode;
  18182. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18183. this.specularIntensityNode = source.specularIntensityNode;
  18184. this.specularColorNode = source.specularColorNode;
  18185. this.transmissionNode = source.transmissionNode;
  18186. this.thicknessNode = source.thicknessNode;
  18187. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18188. this.attenuationColorNode = source.attenuationColorNode;
  18189. this.dispersionNode = source.dispersionNode;
  18190. this.anisotropyNode = source.anisotropyNode;
  18191. return super.copy( source );
  18192. }
  18193. }
  18194. /**
  18195. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18196. *
  18197. * @augments PhysicalLightingModel
  18198. */
  18199. class SSSLightingModel extends PhysicalLightingModel {
  18200. /**
  18201. * Constructs a new physical lighting model.
  18202. *
  18203. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18204. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18205. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18206. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18207. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18208. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18209. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18210. */
  18211. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18212. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18213. /**
  18214. * Whether the lighting model should use SSS or not.
  18215. *
  18216. * @type {boolean}
  18217. * @default false
  18218. */
  18219. this.useSSS = sss;
  18220. }
  18221. /**
  18222. * Extends the default implementation with a SSS term.
  18223. *
  18224. * 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/}
  18225. *
  18226. * @param {Object} input - The input data.
  18227. * @param {NodeBuilder} builder - The current node builder.
  18228. */
  18229. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18230. if ( this.useSSS === true ) {
  18231. const material = builder.material;
  18232. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18233. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18234. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18235. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18236. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18237. }
  18238. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18239. }
  18240. }
  18241. /**
  18242. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18243. * that implements a Subsurface scattering (SSS) term.
  18244. *
  18245. * @augments MeshPhysicalNodeMaterial
  18246. */
  18247. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18248. static get type() {
  18249. return 'MeshSSSNodeMaterial';
  18250. }
  18251. /**
  18252. * Constructs a new mesh SSS node material.
  18253. *
  18254. * @param {Object} [parameters] - The configuration parameter.
  18255. */
  18256. constructor( parameters ) {
  18257. super( parameters );
  18258. /**
  18259. * Represents the thickness color.
  18260. *
  18261. * @type {?Node<vec3>}
  18262. * @default null
  18263. */
  18264. this.thicknessColorNode = null;
  18265. /**
  18266. * Represents the distortion factor.
  18267. *
  18268. * @type {?Node<float>}
  18269. */
  18270. this.thicknessDistortionNode = float( 0.1 );
  18271. /**
  18272. * Represents the thickness ambient factor.
  18273. *
  18274. * @type {?Node<float>}
  18275. */
  18276. this.thicknessAmbientNode = float( 0.0 );
  18277. /**
  18278. * Represents the thickness attenuation.
  18279. *
  18280. * @type {?Node<float>}
  18281. */
  18282. this.thicknessAttenuationNode = float( .1 );
  18283. /**
  18284. * Represents the thickness power.
  18285. *
  18286. * @type {?Node<float>}
  18287. */
  18288. this.thicknessPowerNode = float( 2.0 );
  18289. /**
  18290. * Represents the thickness scale.
  18291. *
  18292. * @type {?Node<float>}
  18293. */
  18294. this.thicknessScaleNode = float( 10.0 );
  18295. }
  18296. /**
  18297. * Whether the lighting model should use SSS or not.
  18298. *
  18299. * @type {boolean}
  18300. * @default true
  18301. */
  18302. get useSSS() {
  18303. return this.thicknessColorNode !== null;
  18304. }
  18305. /**
  18306. * Setups the lighting model.
  18307. *
  18308. * @return {SSSLightingModel} The lighting model.
  18309. */
  18310. setupLightingModel( /*builder*/ ) {
  18311. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18312. }
  18313. copy( source ) {
  18314. this.thicknessColorNode = source.thicknessColorNode;
  18315. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18316. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18317. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18318. this.thicknessPowerNode = source.thicknessPowerNode;
  18319. this.thicknessScaleNode = source.thicknessScaleNode;
  18320. return super.copy( source );
  18321. }
  18322. }
  18323. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18324. // dotNL will be from -1.0 to 1.0
  18325. const dotNL = normal.dot( lightDirection );
  18326. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18327. if ( builder.material.gradientMap ) {
  18328. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18329. return vec3( gradientMap.r );
  18330. } else {
  18331. const fw = coord.fwidth().mul( 0.5 );
  18332. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18333. }
  18334. } );
  18335. /**
  18336. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18337. *
  18338. * @augments LightingModel
  18339. */
  18340. class ToonLightingModel extends LightingModel {
  18341. /**
  18342. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18343. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18344. *
  18345. * @param {Object} lightData - The light data.
  18346. * @param {NodeBuilder} builder - The current node builder.
  18347. */
  18348. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18349. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18350. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18351. }
  18352. /**
  18353. * Implements the indirect lighting.
  18354. *
  18355. * @param {NodeBuilder} builder - The current node builder.
  18356. */
  18357. indirect( builder ) {
  18358. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18359. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18360. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18361. }
  18362. }
  18363. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18364. /**
  18365. * Node material version of {@link MeshToonMaterial}.
  18366. *
  18367. * @augments NodeMaterial
  18368. */
  18369. class MeshToonNodeMaterial extends NodeMaterial {
  18370. static get type() {
  18371. return 'MeshToonNodeMaterial';
  18372. }
  18373. /**
  18374. * Constructs a new mesh toon node material.
  18375. *
  18376. * @param {Object} [parameters] - The configuration parameter.
  18377. */
  18378. constructor( parameters ) {
  18379. super();
  18380. /**
  18381. * This flag can be used for type testing.
  18382. *
  18383. * @type {boolean}
  18384. * @readonly
  18385. * @default true
  18386. */
  18387. this.isMeshToonNodeMaterial = true;
  18388. /**
  18389. * Set to `true` because toon materials react on lights.
  18390. *
  18391. * @type {boolean}
  18392. * @default true
  18393. */
  18394. this.lights = true;
  18395. this.setDefaultValues( _defaultValues$4 );
  18396. this.setValues( parameters );
  18397. }
  18398. /**
  18399. * Setups the lighting model.
  18400. *
  18401. * @return {ToonLightingModel} The lighting model.
  18402. */
  18403. setupLightingModel( /*builder*/ ) {
  18404. return new ToonLightingModel();
  18405. }
  18406. }
  18407. /**
  18408. * TSL function for creating a matcap uv node.
  18409. *
  18410. * Can be used to compute texture coordinates for projecting a
  18411. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18412. *
  18413. * @tsl
  18414. * @function
  18415. * @returns {Node<vec2>} The matcap UV coordinates.
  18416. */
  18417. const matcapUV = /*@__PURE__*/ Fn( () => {
  18418. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18419. const y = positionViewDirection.cross( x );
  18420. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18421. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18422. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18423. /**
  18424. * Node material version of {@link MeshMatcapMaterial}.
  18425. *
  18426. * @augments NodeMaterial
  18427. */
  18428. class MeshMatcapNodeMaterial extends NodeMaterial {
  18429. static get type() {
  18430. return 'MeshMatcapNodeMaterial';
  18431. }
  18432. /**
  18433. * Constructs a new mesh normal node material.
  18434. *
  18435. * @param {Object} [parameters] - The configuration parameter.
  18436. */
  18437. constructor( parameters ) {
  18438. super();
  18439. /**
  18440. * This flag can be used for type testing.
  18441. *
  18442. * @type {boolean}
  18443. * @readonly
  18444. * @default true
  18445. */
  18446. this.isMeshMatcapNodeMaterial = true;
  18447. this.setDefaultValues( _defaultValues$3 );
  18448. this.setValues( parameters );
  18449. }
  18450. /**
  18451. * Setups the matcap specific node variables.
  18452. *
  18453. * @param {NodeBuilder} builder - The current node builder.
  18454. */
  18455. setupVariants( builder ) {
  18456. const uv = matcapUV;
  18457. let matcapColor;
  18458. if ( builder.material.matcap ) {
  18459. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18460. } else {
  18461. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18462. }
  18463. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18464. }
  18465. }
  18466. /**
  18467. * Applies a rotation to the given position node.
  18468. *
  18469. * @augments TempNode
  18470. */
  18471. class RotateNode extends TempNode {
  18472. static get type() {
  18473. return 'RotateNode';
  18474. }
  18475. /**
  18476. * Constructs a new rotate node.
  18477. *
  18478. * @param {Node} positionNode - The position node.
  18479. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18480. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18481. */
  18482. constructor( positionNode, rotationNode ) {
  18483. super();
  18484. /**
  18485. * The position node.
  18486. *
  18487. * @type {Node}
  18488. */
  18489. this.positionNode = positionNode;
  18490. /**
  18491. * Represents the rotation that is applied to the position node.
  18492. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18493. *
  18494. * @type {Node}
  18495. */
  18496. this.rotationNode = rotationNode;
  18497. }
  18498. /**
  18499. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18500. *
  18501. * @param {NodeBuilder} builder - The current node builder.
  18502. * @return {string} The node's type.
  18503. */
  18504. getNodeType( builder ) {
  18505. return this.positionNode.getNodeType( builder );
  18506. }
  18507. setup( builder ) {
  18508. const { rotationNode, positionNode } = this;
  18509. const nodeType = this.getNodeType( builder );
  18510. if ( nodeType === 'vec2' ) {
  18511. const cosAngle = rotationNode.cos();
  18512. const sinAngle = rotationNode.sin();
  18513. const rotationMatrix = mat2(
  18514. cosAngle, sinAngle,
  18515. sinAngle.negate(), cosAngle
  18516. );
  18517. return rotationMatrix.mul( positionNode );
  18518. } else {
  18519. const rotation = rotationNode;
  18520. 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 ) );
  18521. 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 ) );
  18522. 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 ) );
  18523. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  18524. }
  18525. }
  18526. }
  18527. /**
  18528. * TSL function for creating a rotate node.
  18529. *
  18530. * @tsl
  18531. * @function
  18532. * @param {Node} positionNode - The position node.
  18533. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18534. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18535. * @returns {RotateNode}
  18536. */
  18537. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  18538. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  18539. /**
  18540. * Node material version of {@link SpriteMaterial}.
  18541. *
  18542. * @augments NodeMaterial
  18543. */
  18544. class SpriteNodeMaterial extends NodeMaterial {
  18545. static get type() {
  18546. return 'SpriteNodeMaterial';
  18547. }
  18548. /**
  18549. * Constructs a new sprite node material.
  18550. *
  18551. * @param {Object} [parameters] - The configuration parameter.
  18552. */
  18553. constructor( parameters ) {
  18554. super();
  18555. /**
  18556. * This flag can be used for type testing.
  18557. *
  18558. * @type {boolean}
  18559. * @readonly
  18560. * @default true
  18561. */
  18562. this.isSpriteNodeMaterial = true;
  18563. this._useSizeAttenuation = true;
  18564. /**
  18565. * This property makes it possible to define the position of the sprite with a
  18566. * node. That can be useful when the material is used with instanced rendering
  18567. * and node data are defined with an instanced attribute node:
  18568. * ```js
  18569. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  18570. * material.positionNode = instancedBufferAttribute( positionAttribute );
  18571. * ```
  18572. * Another possibility is to compute the instanced data with a compute shader:
  18573. * ```js
  18574. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  18575. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18576. * ```
  18577. *
  18578. * @type {?Node<vec2>}
  18579. * @default null
  18580. */
  18581. this.positionNode = null;
  18582. /**
  18583. * The rotation of sprite materials is by default inferred from the `rotation`,
  18584. * property. This node property allows to overwrite the default and define
  18585. * the rotation with a node instead.
  18586. *
  18587. * If you don't want to overwrite the rotation but modify the existing
  18588. * value instead, use {@link materialRotation}.
  18589. *
  18590. * @type {?Node<float>}
  18591. * @default null
  18592. */
  18593. this.rotationNode = null;
  18594. /**
  18595. * This node property provides an additional way to scale sprites next to
  18596. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  18597. * is multiplied with the scale value of this node in the vertex shader.
  18598. *
  18599. * @type {?Node<vec2>}
  18600. * @default null
  18601. */
  18602. this.scaleNode = null;
  18603. /**
  18604. * In Sprites, the transparent property is enabled by default.
  18605. *
  18606. * @type {boolean}
  18607. * @default true
  18608. */
  18609. this.transparent = true;
  18610. this.setDefaultValues( _defaultValues$2 );
  18611. this.setValues( parameters );
  18612. }
  18613. /**
  18614. * Setups the position node in view space. This method implements
  18615. * the sprite specific vertex shader.
  18616. *
  18617. * @param {NodeBuilder} builder - The current node builder.
  18618. * @return {Node<vec3>} The position in view space.
  18619. */
  18620. setupPositionView( builder ) {
  18621. const { object, camera } = builder;
  18622. const sizeAttenuation = this.sizeAttenuation;
  18623. const { positionNode, rotationNode, scaleNode } = this;
  18624. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  18625. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  18626. if ( scaleNode !== null ) {
  18627. scale = scale.mul( vec2( scaleNode ) );
  18628. }
  18629. if ( sizeAttenuation === false ) {
  18630. if ( camera.isPerspectiveCamera ) {
  18631. scale = scale.mul( mvPosition.z.negate() );
  18632. } else {
  18633. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  18634. scale = scale.mul( orthoScale.mul( 2 ) );
  18635. }
  18636. }
  18637. let alignedPosition = positionGeometry.xy;
  18638. if ( object.center && object.center.isVector2 === true ) {
  18639. const center = reference$1( 'center', 'vec2', object );
  18640. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  18641. }
  18642. alignedPosition = alignedPosition.mul( scale );
  18643. const rotation = float( rotationNode || materialRotation );
  18644. const rotatedPosition = rotate( alignedPosition, rotation );
  18645. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  18646. }
  18647. copy( source ) {
  18648. this.positionNode = source.positionNode;
  18649. this.rotationNode = source.rotationNode;
  18650. this.scaleNode = source.scaleNode;
  18651. return super.copy( source );
  18652. }
  18653. /**
  18654. * Whether to use size attenuation or not.
  18655. *
  18656. * @type {boolean}
  18657. * @default true
  18658. */
  18659. get sizeAttenuation() {
  18660. return this._useSizeAttenuation;
  18661. }
  18662. set sizeAttenuation( value ) {
  18663. if ( this._useSizeAttenuation !== value ) {
  18664. this._useSizeAttenuation = value;
  18665. this.needsUpdate = true;
  18666. }
  18667. }
  18668. }
  18669. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  18670. /**
  18671. * Node material version of {@link PointsMaterial}.
  18672. *
  18673. * @augments SpriteNodeMaterial
  18674. */
  18675. class PointsNodeMaterial extends SpriteNodeMaterial {
  18676. static get type() {
  18677. return 'PointsNodeMaterial';
  18678. }
  18679. /**
  18680. * Constructs a new points node material.
  18681. *
  18682. * @param {Object} [parameters] - The configuration parameter.
  18683. */
  18684. constructor( parameters ) {
  18685. super();
  18686. /**
  18687. * This node property provides an additional way to set the point size.
  18688. *
  18689. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  18690. * this node has no effect when the material is used with {@link Points} and a WebGPU
  18691. * backend. If an application wants to render points with a size larger than 1 pixel,
  18692. * the material should be used with {@link Sprite} and instancing.
  18693. *
  18694. * @type {?Node<vec2>}
  18695. * @default null
  18696. */
  18697. this.sizeNode = null;
  18698. /**
  18699. * This flag can be used for type testing.
  18700. *
  18701. * @type {boolean}
  18702. * @readonly
  18703. * @default true
  18704. */
  18705. this.isPointsNodeMaterial = true;
  18706. this.setDefaultValues( _defaultValues$1 );
  18707. this.setValues( parameters );
  18708. }
  18709. setupPositionView() {
  18710. const { positionNode } = this;
  18711. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  18712. }
  18713. setupVertex( builder ) {
  18714. const { material, camera } = builder;
  18715. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  18716. let mvp = super.setupVertex( builder );
  18717. // skip further processing if the material is not a node material
  18718. if ( material.isNodeMaterial !== true ) {
  18719. return mvp;
  18720. }
  18721. // point size
  18722. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  18723. const dpr = builder.renderer.getPixelRatio();
  18724. pointSize = pointSize.mul( dpr );
  18725. // size attenuation
  18726. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  18727. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  18728. const scale = float( 0.5 ).mul( screenSize.y ).div( dpr );
  18729. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  18730. }
  18731. // scale
  18732. if ( scaleNode && scaleNode.isNode ) {
  18733. pointSize = pointSize.mul( vec2( scaleNode ) );
  18734. }
  18735. // compute offset
  18736. let offset = positionGeometry.xy;
  18737. // apply rotation
  18738. if ( rotationNode && rotationNode.isNode ) {
  18739. const rotation = float( rotationNode );
  18740. offset = rotate( offset, rotation );
  18741. }
  18742. // account for point size
  18743. offset = offset.mul( pointSize );
  18744. // scale by viewport size
  18745. offset = offset.div( viewportSize.div( 2 ) );
  18746. // compensate for the perspective divide
  18747. offset = offset.mul( mvp.w );
  18748. // add offset
  18749. mvp = mvp.add( vec4( offset, 0, 0 ) );
  18750. return mvp;
  18751. }
  18752. /**
  18753. * Whether alpha to coverage should be used or not.
  18754. *
  18755. * @type {boolean}
  18756. * @default true
  18757. */
  18758. get alphaToCoverage() {
  18759. return this._useAlphaToCoverage;
  18760. }
  18761. set alphaToCoverage( value ) {
  18762. if ( this._useAlphaToCoverage !== value ) {
  18763. this._useAlphaToCoverage = value;
  18764. this.needsUpdate = true;
  18765. }
  18766. }
  18767. }
  18768. /**
  18769. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  18770. *
  18771. * @augments LightingModel
  18772. */
  18773. class ShadowMaskModel extends LightingModel {
  18774. /**
  18775. * Constructs a new shadow mask model.
  18776. */
  18777. constructor() {
  18778. super();
  18779. /**
  18780. * The shadow mask node.
  18781. *
  18782. * @type {Node}
  18783. */
  18784. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  18785. }
  18786. /**
  18787. * Only used to save the shadow mask.
  18788. *
  18789. * @param {Object} input - The input data.
  18790. */
  18791. direct( { lightNode } ) {
  18792. if ( lightNode.shadowNode !== null ) {
  18793. this.shadowNode.mulAssign( lightNode.shadowNode );
  18794. }
  18795. }
  18796. /**
  18797. * Uses the shadow mask to produce the final color.
  18798. *
  18799. * @param {NodeBuilder} builder - The current node builder.
  18800. */
  18801. finish( { context } ) {
  18802. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  18803. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  18804. }
  18805. }
  18806. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  18807. /**
  18808. * Node material version of {@link ShadowMaterial}.
  18809. *
  18810. * @augments NodeMaterial
  18811. */
  18812. class ShadowNodeMaterial extends NodeMaterial {
  18813. static get type() {
  18814. return 'ShadowNodeMaterial';
  18815. }
  18816. /**
  18817. * Constructs a new shadow node material.
  18818. *
  18819. * @param {Object} [parameters] - The configuration parameter.
  18820. */
  18821. constructor( parameters ) {
  18822. super();
  18823. /**
  18824. * This flag can be used for type testing.
  18825. *
  18826. * @type {boolean}
  18827. * @readonly
  18828. * @default true
  18829. */
  18830. this.isShadowNodeMaterial = true;
  18831. /**
  18832. * Set to `true` because so it's possible to implement
  18833. * the shadow mask effect.
  18834. *
  18835. * @type {boolean}
  18836. * @default true
  18837. */
  18838. this.lights = true;
  18839. /**
  18840. * Overwritten since shadow materials are transparent
  18841. * by default.
  18842. *
  18843. * @type {boolean}
  18844. * @default true
  18845. */
  18846. this.transparent = true;
  18847. this.setDefaultValues( _defaultValues );
  18848. this.setValues( parameters );
  18849. }
  18850. /**
  18851. * Setups the lighting model.
  18852. *
  18853. * @return {ShadowMaskModel} The lighting model.
  18854. */
  18855. setupLightingModel( /*builder*/ ) {
  18856. return new ShadowMaskModel();
  18857. }
  18858. }
  18859. const scatteringDensity = property( 'vec3' );
  18860. const linearDepthRay = property( 'vec3' );
  18861. const outgoingRayLight = property( 'vec3' );
  18862. /**
  18863. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  18864. * This model calculates the scattering and transmittance of light through a volumetric medium.
  18865. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  18866. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  18867. *
  18868. * @augments LightingModel
  18869. */
  18870. class VolumetricLightingModel extends LightingModel {
  18871. constructor() {
  18872. super();
  18873. }
  18874. start( builder ) {
  18875. const { material, context } = builder;
  18876. const startPos = property( 'vec3' );
  18877. const endPos = property( 'vec3' );
  18878. // This approach dynamically changes the direction of the ray,
  18879. // 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.
  18880. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  18881. startPos.assign( cameraPosition );
  18882. endPos.assign( positionWorld );
  18883. } ).Else( () => {
  18884. startPos.assign( positionWorld );
  18885. endPos.assign( cameraPosition );
  18886. } );
  18887. //
  18888. const viewVector = endPos.sub( startPos );
  18889. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  18890. const stepSize = viewVector.length().div( steps ).toVar();
  18891. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  18892. const distTravelled = float( 0.0 ).toVar();
  18893. const transmittance = vec3( 1 ).toVar();
  18894. if ( material.offsetNode ) {
  18895. // reduce banding
  18896. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  18897. }
  18898. Loop( steps, () => {
  18899. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  18900. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  18901. if ( material.depthNode !== null ) {
  18902. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  18903. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  18904. }
  18905. context.positionWorld = positionRay;
  18906. context.shadowPositionWorld = positionRay;
  18907. context.positionView = positionViewRay;
  18908. scatteringDensity.assign( 0 );
  18909. let scatteringNode;
  18910. if ( material.scatteringNode ) {
  18911. scatteringNode = material.scatteringNode( {
  18912. positionRay
  18913. } );
  18914. }
  18915. super.start( builder );
  18916. if ( scatteringNode ) {
  18917. scatteringDensity.mulAssign( scatteringNode );
  18918. }
  18919. // beer's law
  18920. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  18921. transmittance.mulAssign( falloff );
  18922. // move along the ray
  18923. distTravelled.addAssign( stepSize );
  18924. } );
  18925. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  18926. }
  18927. scatteringLight( lightColor, builder ) {
  18928. const sceneDepthNode = builder.context.sceneDepthNode;
  18929. if ( sceneDepthNode ) {
  18930. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  18931. scatteringDensity.addAssign( lightColor );
  18932. } );
  18933. } else {
  18934. scatteringDensity.addAssign( lightColor );
  18935. }
  18936. }
  18937. direct( { lightNode, lightColor }, builder ) {
  18938. // Ignore lights with infinite distance
  18939. if ( lightNode.light.distance === undefined ) return;
  18940. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  18941. const directLight = lightColor.xyz.toVar();
  18942. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  18943. this.scatteringLight( directLight, builder );
  18944. }
  18945. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  18946. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  18947. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  18948. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  18949. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  18950. const P = builder.context.positionView;
  18951. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  18952. this.scatteringLight( directLight, builder );
  18953. }
  18954. finish( builder ) {
  18955. builder.context.outgoingLight.assign( outgoingRayLight );
  18956. }
  18957. }
  18958. /**
  18959. * Volume node material.
  18960. *
  18961. * @augments NodeMaterial
  18962. */
  18963. class VolumeNodeMaterial extends NodeMaterial {
  18964. static get type() {
  18965. return 'VolumeNodeMaterial';
  18966. }
  18967. /**
  18968. * Constructs a new volume node material.
  18969. *
  18970. * @param {Object} [parameters] - The configuration parameter.
  18971. */
  18972. constructor( parameters ) {
  18973. super();
  18974. /**
  18975. * This flag can be used for type testing.
  18976. *
  18977. * @type {boolean}
  18978. * @readonly
  18979. * @default true
  18980. */
  18981. this.isVolumeNodeMaterial = true;
  18982. /**
  18983. * Number of steps used for raymarching.
  18984. *
  18985. * @type {number}
  18986. * @default 25
  18987. */
  18988. this.steps = 25;
  18989. /**
  18990. * Offsets the distance a ray has been traveled through a volume.
  18991. * Can be used to implement dithering to reduce banding.
  18992. *
  18993. * @type {Node<float>}
  18994. * @default null
  18995. */
  18996. this.offsetNode = null;
  18997. /**
  18998. * Node used for scattering calculations.
  18999. *
  19000. * @type {Function|FunctionNode<vec4>}
  19001. * @default null
  19002. */
  19003. this.scatteringNode = null;
  19004. this.lights = true;
  19005. this.transparent = true;
  19006. this.side = BackSide;
  19007. this.depthTest = false;
  19008. this.depthWrite = false;
  19009. this.setValues( parameters );
  19010. }
  19011. setupLightingModel() {
  19012. return new VolumetricLightingModel();
  19013. }
  19014. }
  19015. /**
  19016. * This module manages the internal animation loop of the renderer.
  19017. *
  19018. * @private
  19019. */
  19020. class Animation {
  19021. /**
  19022. * Constructs a new animation loop management component.
  19023. *
  19024. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19025. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19026. */
  19027. constructor( nodes, info ) {
  19028. /**
  19029. * Renderer component for managing nodes related logic.
  19030. *
  19031. * @type {Nodes}
  19032. */
  19033. this.nodes = nodes;
  19034. /**
  19035. * Renderer component for managing metrics and monitoring data.
  19036. *
  19037. * @type {Info}
  19038. */
  19039. this.info = info;
  19040. /**
  19041. * A reference to the context from `requestAnimationFrame()` can
  19042. * be called (usually `window`).
  19043. *
  19044. * @type {?(Window|XRSession)}
  19045. */
  19046. this._context = typeof self !== 'undefined' ? self : null;
  19047. /**
  19048. * The user-defined animation loop.
  19049. *
  19050. * @type {?Function}
  19051. * @default null
  19052. */
  19053. this._animationLoop = null;
  19054. /**
  19055. * The requestId which is returned from the `requestAnimationFrame()` call.
  19056. * Can be used to cancel the stop the animation loop.
  19057. *
  19058. * @type {?number}
  19059. * @default null
  19060. */
  19061. this._requestId = null;
  19062. }
  19063. /**
  19064. * Starts the internal animation loop.
  19065. */
  19066. start() {
  19067. const update = ( time, xrFrame ) => {
  19068. this._requestId = this._context.requestAnimationFrame( update );
  19069. if ( this.info.autoReset === true ) this.info.reset();
  19070. this.nodes.nodeFrame.update();
  19071. this.info.frame = this.nodes.nodeFrame.frameId;
  19072. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19073. };
  19074. update();
  19075. }
  19076. /**
  19077. * Stops the internal animation loop.
  19078. */
  19079. stop() {
  19080. this._context.cancelAnimationFrame( this._requestId );
  19081. this._requestId = null;
  19082. }
  19083. /**
  19084. * Returns the user-level animation loop.
  19085. *
  19086. * @return {?Function} The animation loop.
  19087. */
  19088. getAnimationLoop() {
  19089. return this._animationLoop;
  19090. }
  19091. /**
  19092. * Defines the user-level animation loop.
  19093. *
  19094. * @param {?Function} callback - The animation loop.
  19095. */
  19096. setAnimationLoop( callback ) {
  19097. this._animationLoop = callback;
  19098. }
  19099. /**
  19100. * Returns the animation context.
  19101. *
  19102. * @return {Window|XRSession} The animation context.
  19103. */
  19104. getContext() {
  19105. return this._context;
  19106. }
  19107. /**
  19108. * Defines the context in which `requestAnimationFrame()` is executed.
  19109. *
  19110. * @param {Window|XRSession} context - The context to set.
  19111. */
  19112. setContext( context ) {
  19113. this._context = context;
  19114. }
  19115. /**
  19116. * Frees all internal resources and stops the animation loop.
  19117. */
  19118. dispose() {
  19119. this.stop();
  19120. }
  19121. }
  19122. /**
  19123. * Data structure for the renderer. It allows defining values
  19124. * with chained, hierarchical keys. Keys are meant to be
  19125. * objects since the module internally works with Weak Maps
  19126. * for performance reasons.
  19127. *
  19128. * @private
  19129. */
  19130. class ChainMap {
  19131. /**
  19132. * Constructs a new Chain Map.
  19133. */
  19134. constructor() {
  19135. /**
  19136. * The root Weak Map.
  19137. *
  19138. * @type {WeakMap}
  19139. */
  19140. this.weakMap = new WeakMap();
  19141. }
  19142. /**
  19143. * Returns the value for the given array of keys.
  19144. *
  19145. * @param {Array<Object>} keys - List of keys.
  19146. * @return {any} The value. Returns `undefined` if no value was found.
  19147. */
  19148. get( keys ) {
  19149. let map = this.weakMap;
  19150. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19151. map = map.get( keys[ i ] );
  19152. if ( map === undefined ) return undefined;
  19153. }
  19154. return map.get( keys[ keys.length - 1 ] );
  19155. }
  19156. /**
  19157. * Sets the value for the given keys.
  19158. *
  19159. * @param {Array<Object>} keys - List of keys.
  19160. * @param {any} value - The value to set.
  19161. * @return {ChainMap} A reference to this Chain Map.
  19162. */
  19163. set( keys, value ) {
  19164. let map = this.weakMap;
  19165. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19166. const key = keys[ i ];
  19167. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  19168. map = map.get( key );
  19169. }
  19170. map.set( keys[ keys.length - 1 ], value );
  19171. return this;
  19172. }
  19173. /**
  19174. * Deletes a value for the given keys.
  19175. *
  19176. * @param {Array<Object>} keys - The keys.
  19177. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19178. */
  19179. delete( keys ) {
  19180. let map = this.weakMap;
  19181. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19182. map = map.get( keys[ i ] );
  19183. if ( map === undefined ) return false;
  19184. }
  19185. return map.delete( keys[ keys.length - 1 ] );
  19186. }
  19187. }
  19188. let _id$9 = 0;
  19189. function getKeys( obj ) {
  19190. const keys = Object.keys( obj );
  19191. let proto = Object.getPrototypeOf( obj );
  19192. while ( proto ) {
  19193. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19194. for ( const key in descriptors ) {
  19195. if ( descriptors[ key ] !== undefined ) {
  19196. const descriptor = descriptors[ key ];
  19197. if ( descriptor && typeof descriptor.get === 'function' ) {
  19198. keys.push( key );
  19199. }
  19200. }
  19201. }
  19202. proto = Object.getPrototypeOf( proto );
  19203. }
  19204. return keys;
  19205. }
  19206. /**
  19207. * A render object is the renderer's representation of single entity that gets drawn
  19208. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19209. * scene since render objects also depend from the used material, the current render context
  19210. * and the current scene's lighting.
  19211. *
  19212. * In general, the basic process of the renderer is:
  19213. *
  19214. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19215. * - Process the render lists by calling one or more render commands for each render item.
  19216. * - For each render command, request a render object and perform the draw.
  19217. *
  19218. * The module provides an interface to get data required for the draw command like the actual
  19219. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19220. * creating render objects should only be done when necessary.
  19221. *
  19222. * @private
  19223. */
  19224. class RenderObject {
  19225. /**
  19226. * Constructs a new render object.
  19227. *
  19228. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19229. * @param {Geometries} geometries - Renderer component for managing geometries.
  19230. * @param {Renderer} renderer - The renderer.
  19231. * @param {Object3D} object - The 3D object.
  19232. * @param {Material} material - The 3D object's material.
  19233. * @param {Scene} scene - The scene the 3D object belongs to.
  19234. * @param {Camera} camera - The camera the object should be rendered with.
  19235. * @param {LightsNode} lightsNode - The lights node.
  19236. * @param {RenderContext} renderContext - The render context.
  19237. * @param {ClippingContext} clippingContext - The clipping context.
  19238. */
  19239. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19240. this.id = _id$9 ++;
  19241. /**
  19242. * Renderer component for managing nodes related logic.
  19243. *
  19244. * @type {Nodes}
  19245. * @private
  19246. */
  19247. this._nodes = nodes;
  19248. /**
  19249. * Renderer component for managing geometries.
  19250. *
  19251. * @type {Geometries}
  19252. * @private
  19253. */
  19254. this._geometries = geometries;
  19255. /**
  19256. * The renderer.
  19257. *
  19258. * @type {Renderer}
  19259. */
  19260. this.renderer = renderer;
  19261. /**
  19262. * The 3D object.
  19263. *
  19264. * @type {Object3D}
  19265. */
  19266. this.object = object;
  19267. /**
  19268. * The 3D object's material.
  19269. *
  19270. * @type {Material}
  19271. */
  19272. this.material = material;
  19273. /**
  19274. * The scene the 3D object belongs to.
  19275. *
  19276. * @type {Scene}
  19277. */
  19278. this.scene = scene;
  19279. /**
  19280. * The camera the 3D object should be rendered with.
  19281. *
  19282. * @type {Camera}
  19283. */
  19284. this.camera = camera;
  19285. /**
  19286. * The lights node.
  19287. *
  19288. * @type {LightsNode}
  19289. */
  19290. this.lightsNode = lightsNode;
  19291. /**
  19292. * The render context.
  19293. *
  19294. * @type {RenderContext}
  19295. */
  19296. this.context = renderContext;
  19297. /**
  19298. * The 3D object's geometry.
  19299. *
  19300. * @type {BufferGeometry}
  19301. */
  19302. this.geometry = object.geometry;
  19303. /**
  19304. * The render object's version.
  19305. *
  19306. * @type {number}
  19307. */
  19308. this.version = material.version;
  19309. /**
  19310. * The draw range of the geometry.
  19311. *
  19312. * @type {?Object}
  19313. * @default null
  19314. */
  19315. this.drawRange = null;
  19316. /**
  19317. * An array holding the buffer attributes
  19318. * of the render object. This entails attribute
  19319. * definitions on geometry and node level.
  19320. *
  19321. * @type {?Array<BufferAttribute>}
  19322. * @default null
  19323. */
  19324. this.attributes = null;
  19325. /**
  19326. * An object holding the version of the
  19327. * attributes. The keys are the attribute names
  19328. * and the values are the attribute versions.
  19329. *
  19330. * @type {?Object<string, number>}
  19331. * @default null
  19332. */
  19333. this.attributesId = null;
  19334. /**
  19335. * A reference to a render pipeline the render
  19336. * object is processed with.
  19337. *
  19338. * @type {RenderPipeline}
  19339. * @default null
  19340. */
  19341. this.pipeline = null;
  19342. /**
  19343. * Only relevant for objects using
  19344. * multiple materials. This represents a group entry
  19345. * from the respective `BufferGeometry`.
  19346. *
  19347. * @type {?{start: number, count: number}}
  19348. * @default null
  19349. */
  19350. this.group = null;
  19351. /**
  19352. * An array holding the vertex buffers which can
  19353. * be buffer attributes but also interleaved buffers.
  19354. *
  19355. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19356. * @default null
  19357. */
  19358. this.vertexBuffers = null;
  19359. /**
  19360. * The parameters for the draw command.
  19361. *
  19362. * @type {?Object}
  19363. * @default null
  19364. */
  19365. this.drawParams = null;
  19366. /**
  19367. * If this render object is used inside a render bundle,
  19368. * this property points to the respective bundle group.
  19369. *
  19370. * @type {?BundleGroup}
  19371. * @default null
  19372. */
  19373. this.bundle = null;
  19374. /**
  19375. * The clipping context.
  19376. *
  19377. * @type {ClippingContext}
  19378. */
  19379. this.clippingContext = clippingContext;
  19380. /**
  19381. * The clipping context's cache key.
  19382. *
  19383. * @type {string}
  19384. */
  19385. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19386. /**
  19387. * The initial node cache key.
  19388. *
  19389. * @type {number}
  19390. */
  19391. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19392. /**
  19393. * The initial cache key.
  19394. *
  19395. * @type {number}
  19396. */
  19397. this.initialCacheKey = this.getCacheKey();
  19398. /**
  19399. * The node builder state.
  19400. *
  19401. * @type {?NodeBuilderState}
  19402. * @private
  19403. * @default null
  19404. */
  19405. this._nodeBuilderState = null;
  19406. /**
  19407. * An array of bindings.
  19408. *
  19409. * @type {?Array<BindGroup>}
  19410. * @private
  19411. * @default null
  19412. */
  19413. this._bindings = null;
  19414. /**
  19415. * Reference to the node material observer.
  19416. *
  19417. * @type {?NodeMaterialObserver}
  19418. * @private
  19419. * @default null
  19420. */
  19421. this._monitor = null;
  19422. /**
  19423. * An event listener which is defined by `RenderObjects`. It performs
  19424. * clean up tasks when `dispose()` on this render object.
  19425. *
  19426. * @method
  19427. */
  19428. this.onDispose = null;
  19429. /**
  19430. * This flag can be used for type testing.
  19431. *
  19432. * @type {boolean}
  19433. * @readonly
  19434. * @default true
  19435. */
  19436. this.isRenderObject = true;
  19437. /**
  19438. * An event listener which is executed when `dispose()` is called on
  19439. * the material of this render object.
  19440. *
  19441. * @method
  19442. */
  19443. this.onMaterialDispose = () => {
  19444. this.dispose();
  19445. };
  19446. /**
  19447. * An event listener which is executed when `dispose()` is called on
  19448. * the geometry of this render object.
  19449. *
  19450. * @method
  19451. */
  19452. this.onGeometryDispose = () => {
  19453. // clear geometry cache attributes
  19454. this.attributes = null;
  19455. this.attributesId = null;
  19456. };
  19457. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19458. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19459. }
  19460. /**
  19461. * Updates the clipping context.
  19462. *
  19463. * @param {ClippingContext} context - The clipping context to set.
  19464. */
  19465. updateClipping( context ) {
  19466. this.clippingContext = context;
  19467. }
  19468. /**
  19469. * Whether the clipping requires an update or not.
  19470. *
  19471. * @type {boolean}
  19472. * @readonly
  19473. */
  19474. get clippingNeedsUpdate() {
  19475. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19476. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19477. return true;
  19478. }
  19479. /**
  19480. * The number of clipping planes defined in context of hardware clipping.
  19481. *
  19482. * @type {number}
  19483. * @readonly
  19484. */
  19485. get hardwareClippingPlanes() {
  19486. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19487. }
  19488. /**
  19489. * Returns the node builder state of this render object.
  19490. *
  19491. * @return {NodeBuilderState} The node builder state.
  19492. */
  19493. getNodeBuilderState() {
  19494. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  19495. }
  19496. /**
  19497. * Returns the node material observer of this render object.
  19498. *
  19499. * @return {NodeMaterialObserver} The node material observer.
  19500. */
  19501. getMonitor() {
  19502. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  19503. }
  19504. /**
  19505. * Returns an array of bind groups of this render object.
  19506. *
  19507. * @return {Array<BindGroup>} The bindings.
  19508. */
  19509. getBindings() {
  19510. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  19511. }
  19512. /**
  19513. * Returns a binding group by group name of this render object.
  19514. *
  19515. * @param {string} name - The name of the binding group.
  19516. * @return {?BindGroup} The bindings.
  19517. */
  19518. getBindingGroup( name ) {
  19519. for ( const bindingGroup of this.getBindings() ) {
  19520. if ( bindingGroup.name === name ) {
  19521. return bindingGroup;
  19522. }
  19523. }
  19524. }
  19525. /**
  19526. * Returns the index of the render object's geometry.
  19527. *
  19528. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19529. */
  19530. getIndex() {
  19531. return this._geometries.getIndex( this );
  19532. }
  19533. /**
  19534. * Returns the indirect buffer attribute.
  19535. *
  19536. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19537. */
  19538. getIndirect() {
  19539. return this._geometries.getIndirect( this );
  19540. }
  19541. /**
  19542. * Returns an array that acts as a key for identifying the render object in a chain map.
  19543. *
  19544. * @return {Array<Object>} An array with object references.
  19545. */
  19546. getChainArray() {
  19547. return [ this.object, this.material, this.context, this.lightsNode ];
  19548. }
  19549. /**
  19550. * This method is used when the geometry of a 3D object has been exchanged and the
  19551. * respective render object now requires an update.
  19552. *
  19553. * @param {BufferGeometry} geometry - The geometry to set.
  19554. */
  19555. setGeometry( geometry ) {
  19556. this.geometry = geometry;
  19557. this.attributes = null;
  19558. this.attributesId = null;
  19559. }
  19560. /**
  19561. * Returns the buffer attributes of the render object. The returned array holds
  19562. * attribute definitions on geometry and node level.
  19563. *
  19564. * @return {Array<BufferAttribute>} An array with buffer attributes.
  19565. */
  19566. getAttributes() {
  19567. if ( this.attributes !== null ) return this.attributes;
  19568. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  19569. const geometry = this.geometry;
  19570. const attributes = [];
  19571. const vertexBuffers = new Set();
  19572. const attributesId = {};
  19573. for ( const nodeAttribute of nodeAttributes ) {
  19574. let attribute;
  19575. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  19576. // node attribute
  19577. attribute = nodeAttribute.node.attribute;
  19578. } else {
  19579. // geometry attribute
  19580. attribute = geometry.getAttribute( nodeAttribute.name );
  19581. attributesId[ nodeAttribute.name ] = attribute.version;
  19582. }
  19583. if ( attribute === undefined ) continue;
  19584. attributes.push( attribute );
  19585. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  19586. vertexBuffers.add( bufferAttribute );
  19587. }
  19588. this.attributes = attributes;
  19589. this.attributesId = attributesId;
  19590. this.vertexBuffers = Array.from( vertexBuffers.values() );
  19591. return attributes;
  19592. }
  19593. /**
  19594. * Returns the vertex buffers of the render object.
  19595. *
  19596. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  19597. */
  19598. getVertexBuffers() {
  19599. if ( this.vertexBuffers === null ) this.getAttributes();
  19600. return this.vertexBuffers;
  19601. }
  19602. /**
  19603. * Returns the draw parameters for the render object.
  19604. *
  19605. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  19606. */
  19607. getDrawParameters() {
  19608. const { object, material, geometry, group, drawRange } = this;
  19609. const drawParams = this.drawParams || ( this.drawParams = {
  19610. vertexCount: 0,
  19611. firstVertex: 0,
  19612. instanceCount: 0,
  19613. firstInstance: 0
  19614. } );
  19615. const index = this.getIndex();
  19616. const hasIndex = ( index !== null );
  19617. let instanceCount = 1;
  19618. if ( geometry.isInstancedBufferGeometry === true ) {
  19619. instanceCount = geometry.instanceCount;
  19620. } else if ( object.count !== undefined ) {
  19621. instanceCount = Math.max( 0, object.count );
  19622. }
  19623. if ( instanceCount === 0 ) return null;
  19624. drawParams.instanceCount = instanceCount;
  19625. if ( object.isBatchedMesh === true ) return drawParams;
  19626. let rangeFactor = 1;
  19627. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  19628. rangeFactor = 2;
  19629. }
  19630. let firstVertex = drawRange.start * rangeFactor;
  19631. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  19632. if ( group !== null ) {
  19633. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  19634. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  19635. }
  19636. const position = geometry.attributes.position;
  19637. let itemCount = Infinity;
  19638. if ( hasIndex ) {
  19639. itemCount = index.count;
  19640. } else if ( position !== undefined && position !== null ) {
  19641. itemCount = position.count;
  19642. }
  19643. firstVertex = Math.max( firstVertex, 0 );
  19644. lastVertex = Math.min( lastVertex, itemCount );
  19645. const count = lastVertex - firstVertex;
  19646. if ( count < 0 || count === Infinity ) return null;
  19647. drawParams.vertexCount = count;
  19648. drawParams.firstVertex = firstVertex;
  19649. return drawParams;
  19650. }
  19651. /**
  19652. * Returns the render object's geometry cache key.
  19653. *
  19654. * The geometry cache key is part of the material cache key.
  19655. *
  19656. * @return {string} The geometry cache key.
  19657. */
  19658. getGeometryCacheKey() {
  19659. const { geometry } = this;
  19660. let cacheKey = '';
  19661. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  19662. const attribute = geometry.attributes[ name ];
  19663. cacheKey += name + ',';
  19664. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  19665. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  19666. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  19667. if ( attribute.normalized ) cacheKey += 'n,';
  19668. }
  19669. // structural equality isn't sufficient for morph targets since the
  19670. // data are maintained in textures. only if the targets are all equal
  19671. // the texture and thus the instance of `MorphNode` can be shared.
  19672. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  19673. const targets = geometry.morphAttributes[ name ];
  19674. cacheKey += 'morph-' + name + ',';
  19675. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  19676. const attribute = targets[ i ];
  19677. cacheKey += attribute.id + ',';
  19678. }
  19679. }
  19680. if ( geometry.index ) {
  19681. cacheKey += 'index,';
  19682. }
  19683. return cacheKey;
  19684. }
  19685. /**
  19686. * Returns the render object's material cache key.
  19687. *
  19688. * The material cache key is part of the render object cache key.
  19689. *
  19690. * @return {number} The material cache key.
  19691. */
  19692. getMaterialCacheKey() {
  19693. const { object, material, renderer } = this;
  19694. let cacheKey = material.customProgramCacheKey();
  19695. for ( const property of getKeys( material ) ) {
  19696. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  19697. const value = material[ property ];
  19698. let valueKey;
  19699. if ( value !== null ) {
  19700. // some material values require a formatting
  19701. const type = typeof value;
  19702. if ( type === 'number' ) {
  19703. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  19704. } else if ( type === 'object' ) {
  19705. valueKey = '{';
  19706. if ( value.isTexture ) {
  19707. valueKey += value.mapping;
  19708. // WebGPU must honor the sampler data because they are part of the bindings
  19709. if ( renderer.backend.isWebGPUBackend === true ) {
  19710. valueKey += value.magFilter;
  19711. valueKey += value.minFilter;
  19712. valueKey += value.wrapS;
  19713. valueKey += value.wrapT;
  19714. valueKey += value.wrapR;
  19715. }
  19716. }
  19717. valueKey += '}';
  19718. } else {
  19719. valueKey = String( value );
  19720. }
  19721. } else {
  19722. valueKey = String( value );
  19723. }
  19724. cacheKey += /*property + ':' +*/ valueKey + ',';
  19725. }
  19726. cacheKey += this.clippingContextCacheKey + ',';
  19727. if ( object.geometry ) {
  19728. cacheKey += this.getGeometryCacheKey();
  19729. }
  19730. if ( object.skeleton ) {
  19731. cacheKey += object.skeleton.bones.length + ',';
  19732. }
  19733. if ( object.isBatchedMesh ) {
  19734. cacheKey += object._matricesTexture.uuid + ',';
  19735. if ( object._colorsTexture !== null ) {
  19736. cacheKey += object._colorsTexture.uuid + ',';
  19737. }
  19738. }
  19739. if ( object.count > 1 ) {
  19740. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  19741. cacheKey += object.uuid + ',';
  19742. }
  19743. cacheKey += object.receiveShadow + ',';
  19744. return hashString( cacheKey );
  19745. }
  19746. /**
  19747. * Whether the geometry requires an update or not.
  19748. *
  19749. * @type {boolean}
  19750. * @readonly
  19751. */
  19752. get needsGeometryUpdate() {
  19753. if ( this.geometry.id !== this.object.geometry.id ) return true;
  19754. if ( this.attributes !== null ) {
  19755. const attributesId = this.attributesId;
  19756. for ( const name in attributesId ) {
  19757. const attribute = this.geometry.getAttribute( name );
  19758. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  19759. return true;
  19760. }
  19761. }
  19762. }
  19763. return false;
  19764. }
  19765. /**
  19766. * Whether the render object requires an update or not.
  19767. *
  19768. * Note: There are two distinct places where render objects are checked for an update.
  19769. *
  19770. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  19771. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  19772. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  19773. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  19774. * a need for a refresh due to material, geometry or object related value changes.
  19775. *
  19776. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  19777. * that performs the 'needsUpdate' check.
  19778. *
  19779. * @type {boolean}
  19780. * @readonly
  19781. */
  19782. get needsUpdate() {
  19783. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  19784. }
  19785. /**
  19786. * Returns the dynamic cache key which represents a key that is computed per draw command.
  19787. *
  19788. * @return {number} The cache key.
  19789. */
  19790. getDynamicCacheKey() {
  19791. let cacheKey = 0;
  19792. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  19793. // the renderer is inside a shadow pass.
  19794. if ( this.material.isShadowPassMaterial !== true ) {
  19795. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  19796. }
  19797. if ( this.camera.isArrayCamera ) {
  19798. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  19799. }
  19800. if ( this.object.receiveShadow ) {
  19801. cacheKey = hash$1( cacheKey, 1 );
  19802. }
  19803. return cacheKey;
  19804. }
  19805. /**
  19806. * Returns the render object's cache key.
  19807. *
  19808. * @return {number} The cache key.
  19809. */
  19810. getCacheKey() {
  19811. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  19812. }
  19813. /**
  19814. * Frees internal resources.
  19815. */
  19816. dispose() {
  19817. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  19818. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  19819. this.onDispose();
  19820. }
  19821. }
  19822. const _chainKeys$5 = [];
  19823. /**
  19824. * This module manages the render objects of the renderer.
  19825. *
  19826. * @private
  19827. */
  19828. class RenderObjects {
  19829. /**
  19830. * Constructs a new render object management component.
  19831. *
  19832. * @param {Renderer} renderer - The renderer.
  19833. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19834. * @param {Geometries} geometries - Renderer component for managing geometries.
  19835. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  19836. * @param {Bindings} bindings - Renderer component for managing bindings.
  19837. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19838. */
  19839. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  19840. /**
  19841. * The renderer.
  19842. *
  19843. * @type {Renderer}
  19844. */
  19845. this.renderer = renderer;
  19846. /**
  19847. * Renderer component for managing nodes related logic.
  19848. *
  19849. * @type {Nodes}
  19850. */
  19851. this.nodes = nodes;
  19852. /**
  19853. * Renderer component for managing geometries.
  19854. *
  19855. * @type {Geometries}
  19856. */
  19857. this.geometries = geometries;
  19858. /**
  19859. * Renderer component for managing pipelines.
  19860. *
  19861. * @type {Pipelines}
  19862. */
  19863. this.pipelines = pipelines;
  19864. /**
  19865. * Renderer component for managing bindings.
  19866. *
  19867. * @type {Bindings}
  19868. */
  19869. this.bindings = bindings;
  19870. /**
  19871. * Renderer component for managing metrics and monitoring data.
  19872. *
  19873. * @type {Info}
  19874. */
  19875. this.info = info;
  19876. /**
  19877. * A dictionary that manages render contexts in chain maps
  19878. * for each pass ID.
  19879. *
  19880. * @type {Object<string,ChainMap>}
  19881. */
  19882. this.chainMaps = {};
  19883. }
  19884. /**
  19885. * Returns a render object for the given object and state data.
  19886. *
  19887. * @param {Object3D} object - The 3D object.
  19888. * @param {Material} material - The 3D object's material.
  19889. * @param {Scene} scene - The scene the 3D object belongs to.
  19890. * @param {Camera} camera - The camera the 3D object should be rendered with.
  19891. * @param {LightsNode} lightsNode - The lights node.
  19892. * @param {RenderContext} renderContext - The render context.
  19893. * @param {ClippingContext} clippingContext - The clipping context.
  19894. * @param {string} [passId] - An optional ID for identifying the pass.
  19895. * @return {RenderObject} The render object.
  19896. */
  19897. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19898. const chainMap = this.getChainMap( passId );
  19899. // reuse chainArray
  19900. _chainKeys$5[ 0 ] = object;
  19901. _chainKeys$5[ 1 ] = material;
  19902. _chainKeys$5[ 2 ] = renderContext;
  19903. _chainKeys$5[ 3 ] = lightsNode;
  19904. let renderObject = chainMap.get( _chainKeys$5 );
  19905. if ( renderObject === undefined ) {
  19906. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19907. chainMap.set( _chainKeys$5, renderObject );
  19908. } else {
  19909. renderObject.updateClipping( clippingContext );
  19910. if ( renderObject.needsGeometryUpdate ) {
  19911. renderObject.setGeometry( object.geometry );
  19912. }
  19913. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  19914. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  19915. renderObject.dispose();
  19916. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19917. } else {
  19918. renderObject.version = material.version;
  19919. }
  19920. }
  19921. }
  19922. _chainKeys$5.length = 0;
  19923. return renderObject;
  19924. }
  19925. /**
  19926. * Returns a chain map for the given pass ID.
  19927. *
  19928. * @param {string} [passId='default'] - The pass ID.
  19929. * @return {ChainMap} The chain map.
  19930. */
  19931. getChainMap( passId = 'default' ) {
  19932. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  19933. }
  19934. /**
  19935. * Frees internal resources.
  19936. */
  19937. dispose() {
  19938. this.chainMaps = {};
  19939. }
  19940. /**
  19941. * Factory method for creating render objects with the given list of parameters.
  19942. *
  19943. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19944. * @param {Geometries} geometries - Renderer component for managing geometries.
  19945. * @param {Renderer} renderer - The renderer.
  19946. * @param {Object3D} object - The 3D object.
  19947. * @param {Material} material - The object's material.
  19948. * @param {Scene} scene - The scene the 3D object belongs to.
  19949. * @param {Camera} camera - The camera the object should be rendered with.
  19950. * @param {LightsNode} lightsNode - The lights node.
  19951. * @param {RenderContext} renderContext - The render context.
  19952. * @param {ClippingContext} clippingContext - The clipping context.
  19953. * @param {string} [passId] - An optional ID for identifying the pass.
  19954. * @return {RenderObject} The render object.
  19955. */
  19956. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19957. const chainMap = this.getChainMap( passId );
  19958. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  19959. renderObject.onDispose = () => {
  19960. this.pipelines.delete( renderObject );
  19961. this.bindings.delete( renderObject );
  19962. this.nodes.delete( renderObject );
  19963. chainMap.delete( renderObject.getChainArray() );
  19964. };
  19965. return renderObject;
  19966. }
  19967. }
  19968. /**
  19969. * Data structure for the renderer. It is intended to manage
  19970. * data of objects in dictionaries.
  19971. *
  19972. * @private
  19973. */
  19974. class DataMap {
  19975. /**
  19976. * Constructs a new data map.
  19977. */
  19978. constructor() {
  19979. /**
  19980. * `DataMap` internally uses a weak map
  19981. * to manage its data.
  19982. *
  19983. * @type {WeakMap}
  19984. */
  19985. this.data = new WeakMap();
  19986. }
  19987. /**
  19988. * Returns the dictionary for the given object.
  19989. *
  19990. * @param {Object} object - The object.
  19991. * @return {Object} The dictionary.
  19992. */
  19993. get( object ) {
  19994. let map = this.data.get( object );
  19995. if ( map === undefined ) {
  19996. map = {};
  19997. this.data.set( object, map );
  19998. }
  19999. return map;
  20000. }
  20001. /**
  20002. * Deletes the dictionary for the given object.
  20003. *
  20004. * @param {Object} object - The object.
  20005. * @return {?Object} The deleted dictionary.
  20006. */
  20007. delete( object ) {
  20008. let map = null;
  20009. if ( this.data.has( object ) ) {
  20010. map = this.data.get( object );
  20011. this.data.delete( object );
  20012. }
  20013. return map;
  20014. }
  20015. /**
  20016. * Returns `true` if the given object has a dictionary defined.
  20017. *
  20018. * @param {Object} object - The object to test.
  20019. * @return {boolean} Whether a dictionary is defined or not.
  20020. */
  20021. has( object ) {
  20022. return this.data.has( object );
  20023. }
  20024. /**
  20025. * Frees internal resources.
  20026. */
  20027. dispose() {
  20028. this.data = new WeakMap();
  20029. }
  20030. }
  20031. const AttributeType = {
  20032. VERTEX: 1,
  20033. INDEX: 2,
  20034. STORAGE: 3,
  20035. INDIRECT: 4
  20036. };
  20037. // size of a chunk in bytes (STD140 layout)
  20038. const GPU_CHUNK_BYTES = 16;
  20039. // @TODO: Move to src/constants.js
  20040. const BlendColorFactor = 211;
  20041. const OneMinusBlendColorFactor = 212;
  20042. /**
  20043. * This renderer module manages geometry attributes.
  20044. *
  20045. * @private
  20046. * @augments DataMap
  20047. */
  20048. class Attributes extends DataMap {
  20049. /**
  20050. * Constructs a new attribute management component.
  20051. *
  20052. * @param {Backend} backend - The renderer's backend.
  20053. */
  20054. constructor( backend ) {
  20055. super();
  20056. /**
  20057. * The renderer's backend.
  20058. *
  20059. * @type {Backend}
  20060. */
  20061. this.backend = backend;
  20062. }
  20063. /**
  20064. * Deletes the data for the given attribute.
  20065. *
  20066. * @param {BufferAttribute} attribute - The attribute.
  20067. * @return {Object|null} The deleted attribute data.
  20068. */
  20069. delete( attribute ) {
  20070. const attributeData = super.delete( attribute );
  20071. if ( attributeData !== null ) {
  20072. this.backend.destroyAttribute( attribute );
  20073. }
  20074. return attributeData;
  20075. }
  20076. /**
  20077. * Updates the given attribute. This method creates attribute buffers
  20078. * for new attributes and updates data for existing ones.
  20079. *
  20080. * @param {BufferAttribute} attribute - The attribute to update.
  20081. * @param {number} type - The attribute type.
  20082. */
  20083. update( attribute, type ) {
  20084. const data = this.get( attribute );
  20085. if ( data.version === undefined ) {
  20086. if ( type === AttributeType.VERTEX ) {
  20087. this.backend.createAttribute( attribute );
  20088. } else if ( type === AttributeType.INDEX ) {
  20089. this.backend.createIndexAttribute( attribute );
  20090. } else if ( type === AttributeType.STORAGE ) {
  20091. this.backend.createStorageAttribute( attribute );
  20092. } else if ( type === AttributeType.INDIRECT ) {
  20093. this.backend.createIndirectStorageAttribute( attribute );
  20094. }
  20095. data.version = this._getBufferAttribute( attribute ).version;
  20096. } else {
  20097. const bufferAttribute = this._getBufferAttribute( attribute );
  20098. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20099. this.backend.updateAttribute( attribute );
  20100. data.version = bufferAttribute.version;
  20101. }
  20102. }
  20103. }
  20104. /**
  20105. * Utility method for handling interleaved buffer attributes correctly.
  20106. * To process them, their `InterleavedBuffer` is returned.
  20107. *
  20108. * @param {BufferAttribute} attribute - The attribute.
  20109. * @return {BufferAttribute|InterleavedBuffer}
  20110. */
  20111. _getBufferAttribute( attribute ) {
  20112. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20113. return attribute;
  20114. }
  20115. }
  20116. /**
  20117. * Returns the wireframe version for the given geometry.
  20118. *
  20119. * @private
  20120. * @function
  20121. * @param {BufferGeometry} geometry - The geometry.
  20122. * @return {number} The version.
  20123. */
  20124. function getWireframeVersion( geometry ) {
  20125. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  20126. }
  20127. /**
  20128. * Returns a wireframe index attribute for the given geometry.
  20129. *
  20130. * @private
  20131. * @function
  20132. * @param {BufferGeometry} geometry - The geometry.
  20133. * @return {BufferAttribute} The wireframe index attribute.
  20134. */
  20135. function getWireframeIndex( geometry ) {
  20136. const indices = [];
  20137. const geometryIndex = geometry.index;
  20138. const geometryPosition = geometry.attributes.position;
  20139. if ( geometryIndex !== null ) {
  20140. const array = geometryIndex.array;
  20141. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  20142. const a = array[ i + 0 ];
  20143. const b = array[ i + 1 ];
  20144. const c = array[ i + 2 ];
  20145. indices.push( a, b, b, c, c, a );
  20146. }
  20147. } else {
  20148. const array = geometryPosition.array;
  20149. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  20150. const a = i + 0;
  20151. const b = i + 1;
  20152. const c = i + 2;
  20153. indices.push( a, b, b, c, c, a );
  20154. }
  20155. }
  20156. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  20157. attribute.version = getWireframeVersion( geometry );
  20158. return attribute;
  20159. }
  20160. /**
  20161. * This renderer module manages geometries.
  20162. *
  20163. * @private
  20164. * @augments DataMap
  20165. */
  20166. class Geometries extends DataMap {
  20167. /**
  20168. * Constructs a new geometry management component.
  20169. *
  20170. * @param {Attributes} attributes - Renderer component for managing attributes.
  20171. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20172. */
  20173. constructor( attributes, info ) {
  20174. super();
  20175. /**
  20176. * Renderer component for managing attributes.
  20177. *
  20178. * @type {Attributes}
  20179. */
  20180. this.attributes = attributes;
  20181. /**
  20182. * Renderer component for managing metrics and monitoring data.
  20183. *
  20184. * @type {Info}
  20185. */
  20186. this.info = info;
  20187. /**
  20188. * Weak Map for managing attributes for wireframe rendering.
  20189. *
  20190. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20191. */
  20192. this.wireframes = new WeakMap();
  20193. /**
  20194. * This Weak Map is used to make sure buffer attributes are
  20195. * updated only once per render call.
  20196. *
  20197. * @type {WeakMap<BufferAttribute,number>}
  20198. */
  20199. this.attributeCall = new WeakMap();
  20200. }
  20201. /**
  20202. * Returns `true` if the given render object has an initialized geometry.
  20203. *
  20204. * @param {RenderObject} renderObject - The render object.
  20205. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20206. */
  20207. has( renderObject ) {
  20208. const geometry = renderObject.geometry;
  20209. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20210. }
  20211. /**
  20212. * Prepares the geometry of the given render object for rendering.
  20213. *
  20214. * @param {RenderObject} renderObject - The render object.
  20215. */
  20216. updateForRender( renderObject ) {
  20217. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20218. this.updateAttributes( renderObject );
  20219. }
  20220. /**
  20221. * Initializes the geometry of the given render object.
  20222. *
  20223. * @param {RenderObject} renderObject - The render object.
  20224. */
  20225. initGeometry( renderObject ) {
  20226. const geometry = renderObject.geometry;
  20227. const geometryData = this.get( geometry );
  20228. geometryData.initialized = true;
  20229. this.info.memory.geometries ++;
  20230. const onDispose = () => {
  20231. this.info.memory.geometries --;
  20232. const index = geometry.index;
  20233. const geometryAttributes = renderObject.getAttributes();
  20234. if ( index !== null ) {
  20235. this.attributes.delete( index );
  20236. }
  20237. for ( const geometryAttribute of geometryAttributes ) {
  20238. this.attributes.delete( geometryAttribute );
  20239. }
  20240. const wireframeAttribute = this.wireframes.get( geometry );
  20241. if ( wireframeAttribute !== undefined ) {
  20242. this.attributes.delete( wireframeAttribute );
  20243. }
  20244. geometry.removeEventListener( 'dispose', onDispose );
  20245. };
  20246. geometry.addEventListener( 'dispose', onDispose );
  20247. }
  20248. /**
  20249. * Updates the geometry attributes of the given render object.
  20250. *
  20251. * @param {RenderObject} renderObject - The render object.
  20252. */
  20253. updateAttributes( renderObject ) {
  20254. // attributes
  20255. const attributes = renderObject.getAttributes();
  20256. for ( const attribute of attributes ) {
  20257. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20258. this.updateAttribute( attribute, AttributeType.STORAGE );
  20259. } else {
  20260. this.updateAttribute( attribute, AttributeType.VERTEX );
  20261. }
  20262. }
  20263. // indexes
  20264. const index = this.getIndex( renderObject );
  20265. if ( index !== null ) {
  20266. this.updateAttribute( index, AttributeType.INDEX );
  20267. }
  20268. // indirect
  20269. const indirect = renderObject.geometry.indirect;
  20270. if ( indirect !== null ) {
  20271. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20272. }
  20273. }
  20274. /**
  20275. * Updates the given attribute.
  20276. *
  20277. * @param {BufferAttribute} attribute - The attribute to update.
  20278. * @param {number} type - The attribute type.
  20279. */
  20280. updateAttribute( attribute, type ) {
  20281. const callId = this.info.render.calls;
  20282. if ( ! attribute.isInterleavedBufferAttribute ) {
  20283. if ( this.attributeCall.get( attribute ) !== callId ) {
  20284. this.attributes.update( attribute, type );
  20285. this.attributeCall.set( attribute, callId );
  20286. }
  20287. } else {
  20288. if ( this.attributeCall.get( attribute ) === undefined ) {
  20289. this.attributes.update( attribute, type );
  20290. this.attributeCall.set( attribute, callId );
  20291. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20292. this.attributes.update( attribute, type );
  20293. this.attributeCall.set( attribute.data, callId );
  20294. this.attributeCall.set( attribute, callId );
  20295. }
  20296. }
  20297. }
  20298. /**
  20299. * Returns the indirect buffer attribute of the given render object.
  20300. *
  20301. * @param {RenderObject} renderObject - The render object.
  20302. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20303. */
  20304. getIndirect( renderObject ) {
  20305. return renderObject.geometry.indirect;
  20306. }
  20307. /**
  20308. * Returns the index of the given render object's geometry. This is implemented
  20309. * in a method to return a wireframe index if necessary.
  20310. *
  20311. * @param {RenderObject} renderObject - The render object.
  20312. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20313. */
  20314. getIndex( renderObject ) {
  20315. const { geometry, material } = renderObject;
  20316. let index = geometry.index;
  20317. if ( material.wireframe === true ) {
  20318. const wireframes = this.wireframes;
  20319. let wireframeAttribute = wireframes.get( geometry );
  20320. if ( wireframeAttribute === undefined ) {
  20321. wireframeAttribute = getWireframeIndex( geometry );
  20322. wireframes.set( geometry, wireframeAttribute );
  20323. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20324. this.attributes.delete( wireframeAttribute );
  20325. wireframeAttribute = getWireframeIndex( geometry );
  20326. wireframes.set( geometry, wireframeAttribute );
  20327. }
  20328. index = wireframeAttribute;
  20329. }
  20330. return index;
  20331. }
  20332. }
  20333. /**
  20334. * This renderer module provides a series of statistical information
  20335. * about the GPU memory and the rendering process. Useful for debugging
  20336. * and monitoring.
  20337. */
  20338. class Info {
  20339. /**
  20340. * Constructs a new info component.
  20341. */
  20342. constructor() {
  20343. /**
  20344. * Whether frame related metrics should automatically
  20345. * be resetted or not. This property should be set to `false`
  20346. * by apps which manage their own animation loop. They must
  20347. * then call `renderer.info.reset()` once per frame manually.
  20348. *
  20349. * @type {boolean}
  20350. * @default true
  20351. */
  20352. this.autoReset = true;
  20353. /**
  20354. * The current frame ID. This ID is managed
  20355. * by `NodeFrame`.
  20356. *
  20357. * @type {number}
  20358. * @readonly
  20359. * @default 0
  20360. */
  20361. this.frame = 0;
  20362. /**
  20363. * The number of render calls since the
  20364. * app has been started.
  20365. *
  20366. * @type {number}
  20367. * @readonly
  20368. * @default 0
  20369. */
  20370. this.calls = 0;
  20371. /**
  20372. * Render related metrics.
  20373. *
  20374. * @type {Object}
  20375. * @readonly
  20376. * @property {number} calls - The number of render calls since the app has been started.
  20377. * @property {number} frameCalls - The number of render calls of the current frame.
  20378. * @property {number} drawCalls - The number of draw calls of the current frame.
  20379. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20380. * @property {number} points - The number of rendered point primitives of the current frame.
  20381. * @property {number} lines - The number of rendered line primitives of the current frame.
  20382. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  20383. */
  20384. this.render = {
  20385. calls: 0,
  20386. frameCalls: 0,
  20387. drawCalls: 0,
  20388. triangles: 0,
  20389. points: 0,
  20390. lines: 0,
  20391. timestamp: 0,
  20392. };
  20393. /**
  20394. * Compute related metrics.
  20395. *
  20396. * @type {Object}
  20397. * @readonly
  20398. * @property {number} calls - The number of compute calls since the app has been started.
  20399. * @property {number} frameCalls - The number of compute calls of the current frame.
  20400. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20401. */
  20402. this.compute = {
  20403. calls: 0,
  20404. frameCalls: 0,
  20405. timestamp: 0
  20406. };
  20407. /**
  20408. * Memory related metrics.
  20409. *
  20410. * @type {Object}
  20411. * @readonly
  20412. * @property {number} geometries - The number of active geometries.
  20413. * @property {number} frameCalls - The number of active textures.
  20414. */
  20415. this.memory = {
  20416. geometries: 0,
  20417. textures: 0
  20418. };
  20419. }
  20420. /**
  20421. * This method should be executed per draw call and updates the corresponding metrics.
  20422. *
  20423. * @param {Object3D} object - The 3D object that is going to be rendered.
  20424. * @param {number} count - The vertex or index count.
  20425. * @param {number} instanceCount - The instance count.
  20426. */
  20427. update( object, count, instanceCount ) {
  20428. this.render.drawCalls ++;
  20429. if ( object.isMesh || object.isSprite ) {
  20430. this.render.triangles += instanceCount * ( count / 3 );
  20431. } else if ( object.isPoints ) {
  20432. this.render.points += instanceCount * count;
  20433. } else if ( object.isLineSegments ) {
  20434. this.render.lines += instanceCount * ( count / 2 );
  20435. } else if ( object.isLine ) {
  20436. this.render.lines += instanceCount * ( count - 1 );
  20437. } else {
  20438. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  20439. }
  20440. }
  20441. /**
  20442. * Resets frame related metrics.
  20443. */
  20444. reset() {
  20445. this.render.drawCalls = 0;
  20446. this.render.frameCalls = 0;
  20447. this.compute.frameCalls = 0;
  20448. this.render.triangles = 0;
  20449. this.render.points = 0;
  20450. this.render.lines = 0;
  20451. }
  20452. /**
  20453. * Performs a complete reset of the object.
  20454. */
  20455. dispose() {
  20456. this.reset();
  20457. this.calls = 0;
  20458. this.render.calls = 0;
  20459. this.compute.calls = 0;
  20460. this.render.timestamp = 0;
  20461. this.compute.timestamp = 0;
  20462. this.memory.geometries = 0;
  20463. this.memory.textures = 0;
  20464. }
  20465. }
  20466. /**
  20467. * Abstract class for representing pipelines.
  20468. *
  20469. * @private
  20470. * @abstract
  20471. */
  20472. class Pipeline {
  20473. /**
  20474. * Constructs a new pipeline.
  20475. *
  20476. * @param {string} cacheKey - The pipeline's cache key.
  20477. */
  20478. constructor( cacheKey ) {
  20479. /**
  20480. * The pipeline's cache key.
  20481. *
  20482. * @type {string}
  20483. */
  20484. this.cacheKey = cacheKey;
  20485. /**
  20486. * How often the pipeline is currently in use.
  20487. *
  20488. * @type {number}
  20489. * @default 0
  20490. */
  20491. this.usedTimes = 0;
  20492. }
  20493. }
  20494. /**
  20495. * Class for representing render pipelines.
  20496. *
  20497. * @private
  20498. * @augments Pipeline
  20499. */
  20500. class RenderPipeline extends Pipeline {
  20501. /**
  20502. * Constructs a new render pipeline.
  20503. *
  20504. * @param {string} cacheKey - The pipeline's cache key.
  20505. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  20506. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  20507. */
  20508. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  20509. super( cacheKey );
  20510. /**
  20511. * The pipeline's vertex shader.
  20512. *
  20513. * @type {ProgrammableStage}
  20514. */
  20515. this.vertexProgram = vertexProgram;
  20516. /**
  20517. * The pipeline's fragment shader.
  20518. *
  20519. * @type {ProgrammableStage}
  20520. */
  20521. this.fragmentProgram = fragmentProgram;
  20522. }
  20523. }
  20524. /**
  20525. * Class for representing compute pipelines.
  20526. *
  20527. * @private
  20528. * @augments Pipeline
  20529. */
  20530. class ComputePipeline extends Pipeline {
  20531. /**
  20532. * Constructs a new render pipeline.
  20533. *
  20534. * @param {string} cacheKey - The pipeline's cache key.
  20535. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  20536. */
  20537. constructor( cacheKey, computeProgram ) {
  20538. super( cacheKey );
  20539. /**
  20540. * The pipeline's compute shader.
  20541. *
  20542. * @type {ProgrammableStage}
  20543. */
  20544. this.computeProgram = computeProgram;
  20545. /**
  20546. * This flag can be used for type testing.
  20547. *
  20548. * @type {boolean}
  20549. * @readonly
  20550. * @default true
  20551. */
  20552. this.isComputePipeline = true;
  20553. }
  20554. }
  20555. let _id$8 = 0;
  20556. /**
  20557. * Class for representing programmable stages which are vertex,
  20558. * fragment or compute shaders. Unlike fixed-function states (like blending),
  20559. * they represent the programmable part of a pipeline.
  20560. *
  20561. * @private
  20562. */
  20563. class ProgrammableStage {
  20564. /**
  20565. * Constructs a new programmable stage.
  20566. *
  20567. * @param {string} code - The shader code.
  20568. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  20569. * @param {string} name - The name of the shader.
  20570. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20571. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20572. */
  20573. constructor( code, stage, name, transforms = null, attributes = null ) {
  20574. /**
  20575. * The id of the programmable stage.
  20576. *
  20577. * @type {number}
  20578. */
  20579. this.id = _id$8 ++;
  20580. /**
  20581. * The shader code.
  20582. *
  20583. * @type {string}
  20584. */
  20585. this.code = code;
  20586. /**
  20587. * The type of stage.
  20588. *
  20589. * @type {string}
  20590. */
  20591. this.stage = stage;
  20592. /**
  20593. * The name of the stage.
  20594. * This is used for debugging purposes.
  20595. *
  20596. * @type {string}
  20597. */
  20598. this.name = name;
  20599. /**
  20600. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20601. *
  20602. * @type {?Array<Object>}
  20603. */
  20604. this.transforms = transforms;
  20605. /**
  20606. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20607. *
  20608. * @type {?Array<Object>}
  20609. */
  20610. this.attributes = attributes;
  20611. /**
  20612. * How often the programmable stage is currently in use.
  20613. *
  20614. * @type {number}
  20615. * @default 0
  20616. */
  20617. this.usedTimes = 0;
  20618. }
  20619. }
  20620. /**
  20621. * This renderer module manages the pipelines of the renderer.
  20622. *
  20623. * @private
  20624. * @augments DataMap
  20625. */
  20626. class Pipelines extends DataMap {
  20627. /**
  20628. * Constructs a new pipeline management component.
  20629. *
  20630. * @param {Backend} backend - The renderer's backend.
  20631. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20632. */
  20633. constructor( backend, nodes ) {
  20634. super();
  20635. /**
  20636. * The renderer's backend.
  20637. *
  20638. * @type {Backend}
  20639. */
  20640. this.backend = backend;
  20641. /**
  20642. * Renderer component for managing nodes related logic.
  20643. *
  20644. * @type {Nodes}
  20645. */
  20646. this.nodes = nodes;
  20647. /**
  20648. * A references to the bindings management component.
  20649. * This reference will be set inside the `Bindings`
  20650. * constructor.
  20651. *
  20652. * @type {?Bindings}
  20653. * @default null
  20654. */
  20655. this.bindings = null;
  20656. /**
  20657. * Internal cache for maintaining pipelines.
  20658. * The key of the map is a cache key, the value the pipeline.
  20659. *
  20660. * @type {Map<string,Pipeline>}
  20661. */
  20662. this.caches = new Map();
  20663. /**
  20664. * This dictionary maintains for each shader stage type (vertex,
  20665. * fragment and compute) the programmable stage objects which
  20666. * represent the actual shader code.
  20667. *
  20668. * @type {Object<string,Map>}
  20669. */
  20670. this.programs = {
  20671. vertex: new Map(),
  20672. fragment: new Map(),
  20673. compute: new Map()
  20674. };
  20675. }
  20676. /**
  20677. * Returns a compute pipeline for the given compute node.
  20678. *
  20679. * @param {Node} computeNode - The compute node.
  20680. * @param {Array<BindGroup>} bindings - The bindings.
  20681. * @return {ComputePipeline} The compute pipeline.
  20682. */
  20683. getForCompute( computeNode, bindings ) {
  20684. const { backend } = this;
  20685. const data = this.get( computeNode );
  20686. if ( this._needsComputeUpdate( computeNode ) ) {
  20687. const previousPipeline = data.pipeline;
  20688. if ( previousPipeline ) {
  20689. previousPipeline.usedTimes --;
  20690. previousPipeline.computeProgram.usedTimes --;
  20691. }
  20692. // get shader
  20693. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  20694. // programmable stage
  20695. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  20696. if ( stageCompute === undefined ) {
  20697. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  20698. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  20699. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  20700. backend.createProgram( stageCompute );
  20701. }
  20702. // determine compute pipeline
  20703. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  20704. let pipeline = this.caches.get( cacheKey );
  20705. if ( pipeline === undefined ) {
  20706. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20707. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  20708. }
  20709. // keep track of all used times
  20710. pipeline.usedTimes ++;
  20711. stageCompute.usedTimes ++;
  20712. //
  20713. data.version = computeNode.version;
  20714. data.pipeline = pipeline;
  20715. }
  20716. return data.pipeline;
  20717. }
  20718. /**
  20719. * Returns a render pipeline for the given render object.
  20720. *
  20721. * @param {RenderObject} renderObject - The render object.
  20722. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20723. * @return {RenderPipeline} The render pipeline.
  20724. */
  20725. getForRender( renderObject, promises = null ) {
  20726. const { backend } = this;
  20727. const data = this.get( renderObject );
  20728. if ( this._needsRenderUpdate( renderObject ) ) {
  20729. const previousPipeline = data.pipeline;
  20730. if ( previousPipeline ) {
  20731. previousPipeline.usedTimes --;
  20732. previousPipeline.vertexProgram.usedTimes --;
  20733. previousPipeline.fragmentProgram.usedTimes --;
  20734. }
  20735. // get shader
  20736. const nodeBuilderState = renderObject.getNodeBuilderState();
  20737. const name = renderObject.material ? renderObject.material.name : '';
  20738. // programmable stages
  20739. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  20740. if ( stageVertex === undefined ) {
  20741. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  20742. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  20743. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  20744. backend.createProgram( stageVertex );
  20745. }
  20746. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  20747. if ( stageFragment === undefined ) {
  20748. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  20749. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  20750. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  20751. backend.createProgram( stageFragment );
  20752. }
  20753. // determine render pipeline
  20754. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20755. let pipeline = this.caches.get( cacheKey );
  20756. if ( pipeline === undefined ) {
  20757. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20758. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  20759. } else {
  20760. renderObject.pipeline = pipeline;
  20761. }
  20762. // keep track of all used times
  20763. pipeline.usedTimes ++;
  20764. stageVertex.usedTimes ++;
  20765. stageFragment.usedTimes ++;
  20766. //
  20767. data.pipeline = pipeline;
  20768. }
  20769. return data.pipeline;
  20770. }
  20771. /**
  20772. * Deletes the pipeline for the given render object.
  20773. *
  20774. * @param {RenderObject} object - The render object.
  20775. * @return {?Object} The deleted dictionary.
  20776. */
  20777. delete( object ) {
  20778. const pipeline = this.get( object ).pipeline;
  20779. if ( pipeline ) {
  20780. // pipeline
  20781. pipeline.usedTimes --;
  20782. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  20783. // programs
  20784. if ( pipeline.isComputePipeline ) {
  20785. pipeline.computeProgram.usedTimes --;
  20786. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  20787. } else {
  20788. pipeline.fragmentProgram.usedTimes --;
  20789. pipeline.vertexProgram.usedTimes --;
  20790. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  20791. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  20792. }
  20793. }
  20794. return super.delete( object );
  20795. }
  20796. /**
  20797. * Frees internal resources.
  20798. */
  20799. dispose() {
  20800. super.dispose();
  20801. this.caches = new Map();
  20802. this.programs = {
  20803. vertex: new Map(),
  20804. fragment: new Map(),
  20805. compute: new Map()
  20806. };
  20807. }
  20808. /**
  20809. * Updates the pipeline for the given render object.
  20810. *
  20811. * @param {RenderObject} renderObject - The render object.
  20812. */
  20813. updateForRender( renderObject ) {
  20814. this.getForRender( renderObject );
  20815. }
  20816. /**
  20817. * Returns a compute pipeline for the given parameters.
  20818. *
  20819. * @private
  20820. * @param {Node} computeNode - The compute node.
  20821. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20822. * @param {string} cacheKey - The cache key.
  20823. * @param {Array<BindGroup>} bindings - The bindings.
  20824. * @return {ComputePipeline} The compute pipeline.
  20825. */
  20826. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  20827. // check for existing pipeline
  20828. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  20829. let pipeline = this.caches.get( cacheKey );
  20830. if ( pipeline === undefined ) {
  20831. pipeline = new ComputePipeline( cacheKey, stageCompute );
  20832. this.caches.set( cacheKey, pipeline );
  20833. this.backend.createComputePipeline( pipeline, bindings );
  20834. }
  20835. return pipeline;
  20836. }
  20837. /**
  20838. * Returns a render pipeline for the given parameters.
  20839. *
  20840. * @private
  20841. * @param {RenderObject} renderObject - The render object.
  20842. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20843. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20844. * @param {string} cacheKey - The cache key.
  20845. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20846. * @return {ComputePipeline} The compute pipeline.
  20847. */
  20848. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  20849. // check for existing pipeline
  20850. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20851. let pipeline = this.caches.get( cacheKey );
  20852. if ( pipeline === undefined ) {
  20853. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  20854. this.caches.set( cacheKey, pipeline );
  20855. renderObject.pipeline = pipeline;
  20856. // The `promises` array is `null` by default and only set to an empty array when
  20857. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  20858. // pending promises that resolve when the render pipelines are ready for rendering.
  20859. this.backend.createRenderPipeline( renderObject, promises );
  20860. }
  20861. return pipeline;
  20862. }
  20863. /**
  20864. * Computes a cache key representing a compute pipeline.
  20865. *
  20866. * @private
  20867. * @param {Node} computeNode - The compute node.
  20868. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20869. * @return {string} The cache key.
  20870. */
  20871. _getComputeCacheKey( computeNode, stageCompute ) {
  20872. return computeNode.id + ',' + stageCompute.id;
  20873. }
  20874. /**
  20875. * Computes a cache key representing a render pipeline.
  20876. *
  20877. * @private
  20878. * @param {RenderObject} renderObject - The render object.
  20879. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20880. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20881. * @return {string} The cache key.
  20882. */
  20883. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  20884. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  20885. }
  20886. /**
  20887. * Releases the given pipeline.
  20888. *
  20889. * @private
  20890. * @param {Pipeline} pipeline - The pipeline to release.
  20891. */
  20892. _releasePipeline( pipeline ) {
  20893. this.caches.delete( pipeline.cacheKey );
  20894. }
  20895. /**
  20896. * Releases the shader program.
  20897. *
  20898. * @private
  20899. * @param {Object} program - The shader program to release.
  20900. */
  20901. _releaseProgram( program ) {
  20902. const code = program.code;
  20903. const stage = program.stage;
  20904. this.programs[ stage ].delete( code );
  20905. }
  20906. /**
  20907. * Returns `true` if the compute pipeline for the given compute node requires an update.
  20908. *
  20909. * @private
  20910. * @param {Node} computeNode - The compute node.
  20911. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  20912. */
  20913. _needsComputeUpdate( computeNode ) {
  20914. const data = this.get( computeNode );
  20915. return data.pipeline === undefined || data.version !== computeNode.version;
  20916. }
  20917. /**
  20918. * Returns `true` if the render pipeline for the given render object requires an update.
  20919. *
  20920. * @private
  20921. * @param {RenderObject} renderObject - The render object.
  20922. * @return {boolean} Whether the render object for the given render object requires an update or not.
  20923. */
  20924. _needsRenderUpdate( renderObject ) {
  20925. const data = this.get( renderObject );
  20926. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  20927. }
  20928. }
  20929. /**
  20930. * This renderer module manages the bindings of the renderer.
  20931. *
  20932. * @private
  20933. * @augments DataMap
  20934. */
  20935. class Bindings extends DataMap {
  20936. /**
  20937. * Constructs a new bindings management component.
  20938. *
  20939. * @param {Backend} backend - The renderer's backend.
  20940. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20941. * @param {Textures} textures - Renderer component for managing textures.
  20942. * @param {Attributes} attributes - Renderer component for managing attributes.
  20943. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20944. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20945. */
  20946. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  20947. super();
  20948. /**
  20949. * The renderer's backend.
  20950. *
  20951. * @type {Backend}
  20952. */
  20953. this.backend = backend;
  20954. /**
  20955. * Renderer component for managing textures.
  20956. *
  20957. * @type {Textures}
  20958. */
  20959. this.textures = textures;
  20960. /**
  20961. * Renderer component for managing pipelines.
  20962. *
  20963. * @type {Pipelines}
  20964. */
  20965. this.pipelines = pipelines;
  20966. /**
  20967. * Renderer component for managing attributes.
  20968. *
  20969. * @type {Attributes}
  20970. */
  20971. this.attributes = attributes;
  20972. /**
  20973. * Renderer component for managing nodes related logic.
  20974. *
  20975. * @type {Nodes}
  20976. */
  20977. this.nodes = nodes;
  20978. /**
  20979. * Renderer component for managing metrics and monitoring data.
  20980. *
  20981. * @type {Info}
  20982. */
  20983. this.info = info;
  20984. this.pipelines.bindings = this; // assign bindings to pipelines
  20985. }
  20986. /**
  20987. * Returns the bind groups for the given render object.
  20988. *
  20989. * @param {RenderObject} renderObject - The render object.
  20990. * @return {Array<BindGroup>} The bind groups.
  20991. */
  20992. getForRender( renderObject ) {
  20993. const bindings = renderObject.getBindings();
  20994. for ( const bindGroup of bindings ) {
  20995. const groupData = this.get( bindGroup );
  20996. if ( groupData.bindGroup === undefined ) {
  20997. // each object defines an array of bindings (ubos, textures, samplers etc.)
  20998. this._init( bindGroup );
  20999. this.backend.createBindings( bindGroup, bindings, 0 );
  21000. groupData.bindGroup = bindGroup;
  21001. }
  21002. }
  21003. return bindings;
  21004. }
  21005. /**
  21006. * Returns the bind groups for the given compute node.
  21007. *
  21008. * @param {Node} computeNode - The compute node.
  21009. * @return {Array<BindGroup>} The bind groups.
  21010. */
  21011. getForCompute( computeNode ) {
  21012. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21013. for ( const bindGroup of bindings ) {
  21014. const groupData = this.get( bindGroup );
  21015. if ( groupData.bindGroup === undefined ) {
  21016. this._init( bindGroup );
  21017. this.backend.createBindings( bindGroup, bindings, 0 );
  21018. groupData.bindGroup = bindGroup;
  21019. }
  21020. }
  21021. return bindings;
  21022. }
  21023. /**
  21024. * Updates the bindings for the given compute node.
  21025. *
  21026. * @param {Node} computeNode - The compute node.
  21027. */
  21028. updateForCompute( computeNode ) {
  21029. this._updateBindings( this.getForCompute( computeNode ) );
  21030. }
  21031. /**
  21032. * Updates the bindings for the given render object.
  21033. *
  21034. * @param {RenderObject} renderObject - The render object.
  21035. */
  21036. updateForRender( renderObject ) {
  21037. this._updateBindings( this.getForRender( renderObject ) );
  21038. }
  21039. /**
  21040. * Updates the given array of bindings.
  21041. *
  21042. * @param {Array<BindGroup>} bindings - The bind groups.
  21043. */
  21044. _updateBindings( bindings ) {
  21045. for ( const bindGroup of bindings ) {
  21046. this._update( bindGroup, bindings );
  21047. }
  21048. }
  21049. /**
  21050. * Initializes the given bind group.
  21051. *
  21052. * @param {BindGroup} bindGroup - The bind group to initialize.
  21053. */
  21054. _init( bindGroup ) {
  21055. for ( const binding of bindGroup.bindings ) {
  21056. if ( binding.isSampledTexture ) {
  21057. this.textures.updateTexture( binding.texture );
  21058. } else if ( binding.isStorageBuffer ) {
  21059. const attribute = binding.attribute;
  21060. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21061. this.attributes.update( attribute, attributeType );
  21062. }
  21063. }
  21064. }
  21065. /**
  21066. * Updates the given bind group.
  21067. *
  21068. * @param {BindGroup} bindGroup - The bind group to update.
  21069. * @param {Array<BindGroup>} bindings - The bind groups.
  21070. */
  21071. _update( bindGroup, bindings ) {
  21072. const { backend } = this;
  21073. let needsBindingsUpdate = false;
  21074. let cacheBindings = true;
  21075. let cacheIndex = 0;
  21076. let version = 0;
  21077. // iterate over all bindings and check if buffer updates or a new binding group is required
  21078. for ( const binding of bindGroup.bindings ) {
  21079. if ( binding.isNodeUniformsGroup ) {
  21080. const updated = this.nodes.updateGroup( binding );
  21081. // every uniforms group is a uniform buffer. So if no update is required,
  21082. // we move one with the next binding. Otherwise the next if block will update the group.
  21083. if ( updated === false ) continue;
  21084. }
  21085. if ( binding.isStorageBuffer ) {
  21086. const attribute = binding.attribute;
  21087. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21088. this.attributes.update( attribute, attributeType );
  21089. }
  21090. if ( binding.isUniformBuffer ) {
  21091. const updated = binding.update();
  21092. if ( updated ) {
  21093. backend.updateBinding( binding );
  21094. }
  21095. } else if ( binding.isSampledTexture ) {
  21096. const updated = binding.update();
  21097. // get the texture data after the update, to sync the texture reference from node
  21098. const texture = binding.texture;
  21099. const texturesTextureData = this.textures.get( texture );
  21100. if ( updated ) {
  21101. // version: update the texture data or create a new one
  21102. this.textures.updateTexture( texture );
  21103. // generation: update the bindings if a new texture has been created
  21104. if ( binding.generation !== texturesTextureData.generation ) {
  21105. binding.generation = texturesTextureData.generation;
  21106. needsBindingsUpdate = true;
  21107. }
  21108. }
  21109. const textureData = backend.get( texture );
  21110. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  21111. cacheBindings = false;
  21112. } else {
  21113. cacheIndex = cacheIndex * 10 + texture.id;
  21114. version += texture.version;
  21115. }
  21116. if ( texture.isStorageTexture === true ) {
  21117. const textureData = this.get( texture );
  21118. if ( binding.store === true ) {
  21119. textureData.needsMipmap = true;
  21120. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  21121. this.backend.generateMipmaps( texture );
  21122. textureData.needsMipmap = false;
  21123. }
  21124. }
  21125. } else if ( binding.isSampler ) {
  21126. binding.update();
  21127. }
  21128. }
  21129. if ( needsBindingsUpdate === true ) {
  21130. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  21131. }
  21132. }
  21133. }
  21134. /**
  21135. * Default sorting function for opaque render items.
  21136. *
  21137. * @private
  21138. * @function
  21139. * @param {Object} a - The first render item.
  21140. * @param {Object} b - The second render item.
  21141. * @return {number} A numeric value which defines the sort order.
  21142. */
  21143. function painterSortStable( a, b ) {
  21144. if ( a.groupOrder !== b.groupOrder ) {
  21145. return a.groupOrder - b.groupOrder;
  21146. } else if ( a.renderOrder !== b.renderOrder ) {
  21147. return a.renderOrder - b.renderOrder;
  21148. } else if ( a.z !== b.z ) {
  21149. return a.z - b.z;
  21150. } else {
  21151. return a.id - b.id;
  21152. }
  21153. }
  21154. /**
  21155. * Default sorting function for transparent render items.
  21156. *
  21157. * @private
  21158. * @function
  21159. * @param {Object} a - The first render item.
  21160. * @param {Object} b - The second render item.
  21161. * @return {number} A numeric value which defines the sort order.
  21162. */
  21163. function reversePainterSortStable( a, b ) {
  21164. if ( a.groupOrder !== b.groupOrder ) {
  21165. return a.groupOrder - b.groupOrder;
  21166. } else if ( a.renderOrder !== b.renderOrder ) {
  21167. return a.renderOrder - b.renderOrder;
  21168. } else if ( a.z !== b.z ) {
  21169. return b.z - a.z;
  21170. } else {
  21171. return a.id - b.id;
  21172. }
  21173. }
  21174. /**
  21175. * Returns `true` if the given transparent material requires a double pass.
  21176. *
  21177. * @private
  21178. * @function
  21179. * @param {Material} material - The transparent material.
  21180. * @return {boolean} Whether the given material requires a double pass or not.
  21181. */
  21182. function needsDoublePass( material ) {
  21183. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  21184. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21185. }
  21186. /**
  21187. * When the renderer analyzes the scene at the beginning of a render call,
  21188. * it stores 3D object for further processing in render lists. Depending on the
  21189. * properties of a 3D objects (like their transformation or material state), the
  21190. * objects are maintained in ordered lists for the actual rendering.
  21191. *
  21192. * Render lists are unique per scene and camera combination.
  21193. *
  21194. * @private
  21195. * @augments Pipeline
  21196. */
  21197. class RenderList {
  21198. /**
  21199. * Constructs a render list.
  21200. *
  21201. * @param {Lighting} lighting - The lighting management component.
  21202. * @param {Scene} scene - The scene.
  21203. * @param {Camera} camera - The camera the scene is rendered with.
  21204. */
  21205. constructor( lighting, scene, camera ) {
  21206. /**
  21207. * 3D objects are transformed into render items and stored in this array.
  21208. *
  21209. * @type {Array<Object>}
  21210. */
  21211. this.renderItems = [];
  21212. /**
  21213. * The current render items index.
  21214. *
  21215. * @type {number}
  21216. * @default 0
  21217. */
  21218. this.renderItemsIndex = 0;
  21219. /**
  21220. * A list with opaque render items.
  21221. *
  21222. * @type {Array<Object>}
  21223. */
  21224. this.opaque = [];
  21225. /**
  21226. * A list with transparent render items which require
  21227. * double pass rendering (e.g. transmissive objects).
  21228. *
  21229. * @type {Array<Object>}
  21230. */
  21231. this.transparentDoublePass = [];
  21232. /**
  21233. * A list with transparent render items.
  21234. *
  21235. * @type {Array<Object>}
  21236. */
  21237. this.transparent = [];
  21238. /**
  21239. * A list with transparent render bundle data.
  21240. *
  21241. * @type {Array<Object>}
  21242. */
  21243. this.bundles = [];
  21244. /**
  21245. * The render list's lights node. This node is later
  21246. * relevant for the actual analytical light nodes which
  21247. * compute the scene's lighting in the shader.
  21248. *
  21249. * @type {LightsNode}
  21250. */
  21251. this.lightsNode = lighting.getNode( scene, camera );
  21252. /**
  21253. * The scene's lights stored in an array. This array
  21254. * is used to setup the lights node.
  21255. *
  21256. * @type {Array<Light>}
  21257. */
  21258. this.lightsArray = [];
  21259. /**
  21260. * The scene.
  21261. *
  21262. * @type {Scene}
  21263. */
  21264. this.scene = scene;
  21265. /**
  21266. * The camera the scene is rendered with.
  21267. *
  21268. * @type {Camera}
  21269. */
  21270. this.camera = camera;
  21271. /**
  21272. * How many objects perform occlusion query tests.
  21273. *
  21274. * @type {number}
  21275. * @default 0
  21276. */
  21277. this.occlusionQueryCount = 0;
  21278. }
  21279. /**
  21280. * This method is called right at the beginning of a render call
  21281. * before the scene is analyzed. It prepares the internal data
  21282. * structures for the upcoming render lists generation.
  21283. *
  21284. * @return {RenderList} A reference to this render list.
  21285. */
  21286. begin() {
  21287. this.renderItemsIndex = 0;
  21288. this.opaque.length = 0;
  21289. this.transparentDoublePass.length = 0;
  21290. this.transparent.length = 0;
  21291. this.bundles.length = 0;
  21292. this.lightsArray.length = 0;
  21293. this.occlusionQueryCount = 0;
  21294. return this;
  21295. }
  21296. /**
  21297. * Returns a render item for the giving render item state. The state is defined
  21298. * by a series of object-related parameters.
  21299. *
  21300. * The method avoids object creation by holding render items and reusing them in
  21301. * subsequent render calls (just with different property values).
  21302. *
  21303. * @param {Object3D} object - The 3D object.
  21304. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21305. * @param {Material} material - The 3D object's material.
  21306. * @param {number} groupOrder - The current group order.
  21307. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21308. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21309. * @param {ClippingContext} clippingContext - The current clipping context.
  21310. * @return {Object} The render item.
  21311. */
  21312. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21313. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21314. if ( renderItem === undefined ) {
  21315. renderItem = {
  21316. id: object.id,
  21317. object: object,
  21318. geometry: geometry,
  21319. material: material,
  21320. groupOrder: groupOrder,
  21321. renderOrder: object.renderOrder,
  21322. z: z,
  21323. group: group,
  21324. clippingContext: clippingContext
  21325. };
  21326. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21327. } else {
  21328. renderItem.id = object.id;
  21329. renderItem.object = object;
  21330. renderItem.geometry = geometry;
  21331. renderItem.material = material;
  21332. renderItem.groupOrder = groupOrder;
  21333. renderItem.renderOrder = object.renderOrder;
  21334. renderItem.z = z;
  21335. renderItem.group = group;
  21336. renderItem.clippingContext = clippingContext;
  21337. }
  21338. this.renderItemsIndex ++;
  21339. return renderItem;
  21340. }
  21341. /**
  21342. * Pushes the given object as a render item to the internal render lists.
  21343. * The selected lists depend on the object properties.
  21344. *
  21345. * @param {Object3D} object - The 3D object.
  21346. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21347. * @param {Material} material - The 3D object's material.
  21348. * @param {number} groupOrder - The current group order.
  21349. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21350. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21351. * @param {ClippingContext} clippingContext - The current clipping context.
  21352. */
  21353. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21354. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21355. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21356. if ( material.transparent === true || material.transmission > 0 ) {
  21357. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21358. this.transparent.push( renderItem );
  21359. } else {
  21360. this.opaque.push( renderItem );
  21361. }
  21362. }
  21363. /**
  21364. * Inserts the given object as a render item at the start of the internal render lists.
  21365. * The selected lists depend on the object properties.
  21366. *
  21367. * @param {Object3D} object - The 3D object.
  21368. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21369. * @param {Material} material - The 3D object's material.
  21370. * @param {number} groupOrder - The current group order.
  21371. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21372. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21373. * @param {ClippingContext} clippingContext - The current clipping context.
  21374. */
  21375. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21376. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21377. if ( material.transparent === true || material.transmission > 0 ) {
  21378. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21379. this.transparent.unshift( renderItem );
  21380. } else {
  21381. this.opaque.unshift( renderItem );
  21382. }
  21383. }
  21384. /**
  21385. * Pushes render bundle group data into the render list.
  21386. *
  21387. * @param {Object} group - Bundle group data.
  21388. */
  21389. pushBundle( group ) {
  21390. this.bundles.push( group );
  21391. }
  21392. /**
  21393. * Pushes a light into the render list.
  21394. *
  21395. * @param {Light} light - The light.
  21396. */
  21397. pushLight( light ) {
  21398. this.lightsArray.push( light );
  21399. }
  21400. /**
  21401. * Sorts the internal render lists.
  21402. *
  21403. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  21404. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  21405. */
  21406. sort( customOpaqueSort, customTransparentSort ) {
  21407. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  21408. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  21409. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  21410. }
  21411. /**
  21412. * This method performs finalizing tasks right after the render lists
  21413. * have been generated.
  21414. */
  21415. finish() {
  21416. // update lights
  21417. this.lightsNode.setLights( this.lightsArray );
  21418. // Clear references from inactive renderItems in the list
  21419. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  21420. const renderItem = this.renderItems[ i ];
  21421. if ( renderItem.id === null ) break;
  21422. renderItem.id = null;
  21423. renderItem.object = null;
  21424. renderItem.geometry = null;
  21425. renderItem.material = null;
  21426. renderItem.groupOrder = null;
  21427. renderItem.renderOrder = null;
  21428. renderItem.z = null;
  21429. renderItem.group = null;
  21430. renderItem.clippingContext = null;
  21431. }
  21432. }
  21433. }
  21434. const _chainKeys$4 = [];
  21435. /**
  21436. * This renderer module manages the render lists which are unique
  21437. * per scene and camera combination.
  21438. *
  21439. * @private
  21440. */
  21441. class RenderLists {
  21442. /**
  21443. * Constructs a render lists management component.
  21444. *
  21445. * @param {Lighting} lighting - The lighting management component.
  21446. */
  21447. constructor( lighting ) {
  21448. /**
  21449. * The lighting management component.
  21450. *
  21451. * @type {Lighting}
  21452. */
  21453. this.lighting = lighting;
  21454. /**
  21455. * The internal chain map which holds the render lists.
  21456. *
  21457. * @type {ChainMap}
  21458. */
  21459. this.lists = new ChainMap();
  21460. }
  21461. /**
  21462. * Returns a render list for the given scene and camera.
  21463. *
  21464. * @param {Scene} scene - The scene.
  21465. * @param {Camera} camera - The camera.
  21466. * @return {RenderList} The render list.
  21467. */
  21468. get( scene, camera ) {
  21469. const lists = this.lists;
  21470. _chainKeys$4[ 0 ] = scene;
  21471. _chainKeys$4[ 1 ] = camera;
  21472. let list = lists.get( _chainKeys$4 );
  21473. if ( list === undefined ) {
  21474. list = new RenderList( this.lighting, scene, camera );
  21475. lists.set( _chainKeys$4, list );
  21476. }
  21477. _chainKeys$4.length = 0;
  21478. return list;
  21479. }
  21480. /**
  21481. * Frees all internal resources.
  21482. */
  21483. dispose() {
  21484. this.lists = new ChainMap();
  21485. }
  21486. }
  21487. let _id$7 = 0;
  21488. /**
  21489. * Any render or compute command is executed in a specific context that defines
  21490. * the state of the renderer and its backend. Typical examples for such context
  21491. * data are the current clear values or data from the active framebuffer. This
  21492. * module is used to represent these contexts as objects.
  21493. *
  21494. * @private
  21495. */
  21496. class RenderContext {
  21497. /**
  21498. * Constructs a new render context.
  21499. */
  21500. constructor() {
  21501. /**
  21502. * The context's ID.
  21503. *
  21504. * @type {number}
  21505. */
  21506. this.id = _id$7 ++;
  21507. /**
  21508. * Whether the current active framebuffer has a color attachment.
  21509. *
  21510. * @type {boolean}
  21511. * @default true
  21512. */
  21513. this.color = true;
  21514. /**
  21515. * Whether the color attachment should be cleared or not.
  21516. *
  21517. * @type {boolean}
  21518. * @default true
  21519. */
  21520. this.clearColor = true;
  21521. /**
  21522. * The clear color value.
  21523. *
  21524. * @type {Object}
  21525. * @default true
  21526. */
  21527. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  21528. /**
  21529. * Whether the current active framebuffer has a depth attachment.
  21530. *
  21531. * @type {boolean}
  21532. * @default true
  21533. */
  21534. this.depth = true;
  21535. /**
  21536. * Whether the depth attachment should be cleared or not.
  21537. *
  21538. * @type {boolean}
  21539. * @default true
  21540. */
  21541. this.clearDepth = true;
  21542. /**
  21543. * The clear depth value.
  21544. *
  21545. * @type {number}
  21546. * @default 1
  21547. */
  21548. this.clearDepthValue = 1;
  21549. /**
  21550. * Whether the current active framebuffer has a stencil attachment.
  21551. *
  21552. * @type {boolean}
  21553. * @default false
  21554. */
  21555. this.stencil = false;
  21556. /**
  21557. * Whether the stencil attachment should be cleared or not.
  21558. *
  21559. * @type {boolean}
  21560. * @default true
  21561. */
  21562. this.clearStencil = true;
  21563. /**
  21564. * The clear stencil value.
  21565. *
  21566. * @type {number}
  21567. * @default 1
  21568. */
  21569. this.clearStencilValue = 1;
  21570. /**
  21571. * By default the viewport encloses the entire framebuffer If a smaller
  21572. * viewport is manually defined, this property is to `true` by the renderer.
  21573. *
  21574. * @type {boolean}
  21575. * @default false
  21576. */
  21577. this.viewport = false;
  21578. /**
  21579. * The viewport value. This value is in physical pixels meaning it incorporates
  21580. * the renderer's pixel ratio. The viewport property of render targets or
  21581. * the renderer is in logical pixels.
  21582. *
  21583. * @type {Vector4}
  21584. */
  21585. this.viewportValue = new Vector4();
  21586. /**
  21587. * When the scissor test is active and scissor rectangle smaller than the
  21588. * framebuffers dimensions, this property is to `true` by the renderer.
  21589. *
  21590. * @type {boolean}
  21591. * @default false
  21592. */
  21593. this.scissor = false;
  21594. /**
  21595. * The scissor rectangle.
  21596. *
  21597. * @type {Vector4}
  21598. */
  21599. this.scissorValue = new Vector4();
  21600. /**
  21601. * The active render target.
  21602. *
  21603. * @type {?RenderTarget}
  21604. * @default null
  21605. */
  21606. this.renderTarget = null;
  21607. /**
  21608. * The textures of the active render target.
  21609. * `null` when no render target is set.
  21610. *
  21611. * @type {?Array<Texture>}
  21612. * @default null
  21613. */
  21614. this.textures = null;
  21615. /**
  21616. * The depth texture of the active render target.
  21617. * `null` when no render target is set.
  21618. *
  21619. * @type {?DepthTexture}
  21620. * @default null
  21621. */
  21622. this.depthTexture = null;
  21623. /**
  21624. * The active cube face.
  21625. *
  21626. * @type {number}
  21627. * @default 0
  21628. */
  21629. this.activeCubeFace = 0;
  21630. /**
  21631. * The active mipmap level.
  21632. *
  21633. * @type {number}
  21634. * @default 0
  21635. */
  21636. this.activeMipmapLevel = 0;
  21637. /**
  21638. * The number of MSAA samples. This value is always `1` when
  21639. * MSAA isn't used.
  21640. *
  21641. * @type {number}
  21642. * @default 1
  21643. */
  21644. this.sampleCount = 1;
  21645. /**
  21646. * The active render target's width in physical pixels.
  21647. *
  21648. * @type {number}
  21649. * @default 0
  21650. */
  21651. this.width = 0;
  21652. /**
  21653. * The active render target's height in physical pixels.
  21654. *
  21655. * @type {number}
  21656. * @default 0
  21657. */
  21658. this.height = 0;
  21659. /**
  21660. * The occlusion query count.
  21661. *
  21662. * @type {number}
  21663. * @default 0
  21664. */
  21665. this.occlusionQueryCount = 0;
  21666. /**
  21667. * The current clipping context.
  21668. *
  21669. * @type {?ClippingContext}
  21670. * @default null
  21671. */
  21672. this.clippingContext = null;
  21673. /**
  21674. * This flag can be used for type testing.
  21675. *
  21676. * @type {boolean}
  21677. * @readonly
  21678. * @default true
  21679. */
  21680. this.isRenderContext = true;
  21681. }
  21682. /**
  21683. * Returns the cache key of this render context.
  21684. *
  21685. * @return {number} The cache key.
  21686. */
  21687. getCacheKey() {
  21688. return getCacheKey( this );
  21689. }
  21690. }
  21691. /**
  21692. * Computes a cache key for the given render context. This key
  21693. * should identify the render target state so it is possible to
  21694. * configure the correct attachments in the respective backend.
  21695. *
  21696. * @param {RenderContext} renderContext - The render context.
  21697. * @return {number} The cache key.
  21698. */
  21699. function getCacheKey( renderContext ) {
  21700. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  21701. const values = [ activeCubeFace, activeMipmapLevel ];
  21702. for ( const texture of textures ) {
  21703. values.push( texture.id );
  21704. }
  21705. return hashArray( values );
  21706. }
  21707. const _chainKeys$3 = [];
  21708. const _defaultScene = /*@__PURE__*/ new Scene();
  21709. const _defaultCamera = /*@__PURE__*/ new Camera();
  21710. /**
  21711. * This module manages the render contexts of the renderer.
  21712. *
  21713. * @private
  21714. */
  21715. class RenderContexts {
  21716. /**
  21717. * Constructs a new render context management component.
  21718. */
  21719. constructor() {
  21720. /**
  21721. * A dictionary that manages render contexts in chain maps
  21722. * for each attachment state.
  21723. *
  21724. * @type {Object<string,ChainMap>}
  21725. */
  21726. this.chainMaps = {};
  21727. }
  21728. /**
  21729. * Returns a render context for the given scene, camera and render target.
  21730. *
  21731. * @param {Scene} scene - The scene.
  21732. * @param {Camera} camera - The camera that is used to render the scene.
  21733. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21734. * @return {RenderContext} The render context.
  21735. */
  21736. get( scene, camera, renderTarget = null ) {
  21737. _chainKeys$3[ 0 ] = scene;
  21738. _chainKeys$3[ 1 ] = camera;
  21739. let attachmentState;
  21740. if ( renderTarget === null ) {
  21741. attachmentState = 'default';
  21742. } else {
  21743. const format = renderTarget.texture.format;
  21744. const count = renderTarget.textures.length;
  21745. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  21746. }
  21747. const chainMap = this._getChainMap( attachmentState );
  21748. let renderState = chainMap.get( _chainKeys$3 );
  21749. if ( renderState === undefined ) {
  21750. renderState = new RenderContext();
  21751. chainMap.set( _chainKeys$3, renderState );
  21752. }
  21753. _chainKeys$3.length = 0;
  21754. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21755. return renderState;
  21756. }
  21757. /**
  21758. * Returns a render context intended for clear operations.
  21759. *
  21760. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21761. * @return {RenderContext} The render context.
  21762. */
  21763. getForClear( renderTarget = null ) {
  21764. return this.get( _defaultScene, _defaultCamera, renderTarget );
  21765. }
  21766. /**
  21767. * Returns a chain map for the given attachment state.
  21768. *
  21769. * @private
  21770. * @param {string} attachmentState - The attachment state.
  21771. * @return {ChainMap} The chain map.
  21772. */
  21773. _getChainMap( attachmentState ) {
  21774. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  21775. }
  21776. /**
  21777. * Frees internal resources.
  21778. */
  21779. dispose() {
  21780. this.chainMaps = {};
  21781. }
  21782. }
  21783. const _size$3 = /*@__PURE__*/ new Vector3();
  21784. /**
  21785. * This module manages the textures of the renderer.
  21786. *
  21787. * @private
  21788. * @augments DataMap
  21789. */
  21790. class Textures extends DataMap {
  21791. /**
  21792. * Constructs a new texture management component.
  21793. *
  21794. * @param {Renderer} renderer - The renderer.
  21795. * @param {Backend} backend - The renderer's backend.
  21796. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21797. */
  21798. constructor( renderer, backend, info ) {
  21799. super();
  21800. /**
  21801. * The renderer.
  21802. *
  21803. * @type {Renderer}
  21804. */
  21805. this.renderer = renderer;
  21806. /**
  21807. * The backend.
  21808. *
  21809. * @type {Backend}
  21810. */
  21811. this.backend = backend;
  21812. /**
  21813. * Renderer component for managing metrics and monitoring data.
  21814. *
  21815. * @type {Info}
  21816. */
  21817. this.info = info;
  21818. }
  21819. /**
  21820. * Updates the given render target. Based on the given render target configuration,
  21821. * it updates the texture states representing the attachments of the framebuffer.
  21822. *
  21823. * @param {RenderTarget} renderTarget - The render target to update.
  21824. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  21825. */
  21826. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  21827. const renderTargetData = this.get( renderTarget );
  21828. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21829. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  21830. const textures = renderTarget.textures;
  21831. const size = this.getSize( textures[ 0 ] );
  21832. const mipWidth = size.width >> activeMipmapLevel;
  21833. const mipHeight = size.height >> activeMipmapLevel;
  21834. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  21835. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  21836. let textureNeedsUpdate = false;
  21837. if ( depthTexture === undefined && useDepthTexture ) {
  21838. depthTexture = new DepthTexture();
  21839. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  21840. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  21841. depthTexture.image.width = mipWidth;
  21842. depthTexture.image.height = mipHeight;
  21843. depthTexture.image.depth = size.depth;
  21844. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  21845. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  21846. }
  21847. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  21848. textureNeedsUpdate = true;
  21849. if ( depthTexture ) {
  21850. depthTexture.needsUpdate = true;
  21851. depthTexture.image.width = mipWidth;
  21852. depthTexture.image.height = mipHeight;
  21853. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  21854. }
  21855. }
  21856. renderTargetData.width = size.width;
  21857. renderTargetData.height = size.height;
  21858. renderTargetData.textures = textures;
  21859. renderTargetData.depthTexture = depthTexture || null;
  21860. renderTargetData.depth = renderTarget.depthBuffer;
  21861. renderTargetData.stencil = renderTarget.stencilBuffer;
  21862. renderTargetData.renderTarget = renderTarget;
  21863. if ( renderTargetData.sampleCount !== sampleCount ) {
  21864. textureNeedsUpdate = true;
  21865. if ( depthTexture ) {
  21866. depthTexture.needsUpdate = true;
  21867. }
  21868. renderTargetData.sampleCount = sampleCount;
  21869. }
  21870. //
  21871. const options = { sampleCount };
  21872. // XR render targets require no texture updates
  21873. if ( renderTarget.isXRRenderTarget !== true ) {
  21874. for ( let i = 0; i < textures.length; i ++ ) {
  21875. const texture = textures[ i ];
  21876. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  21877. this.updateTexture( texture, options );
  21878. }
  21879. if ( depthTexture ) {
  21880. this.updateTexture( depthTexture, options );
  21881. }
  21882. }
  21883. // dispose handler
  21884. if ( renderTargetData.initialized !== true ) {
  21885. renderTargetData.initialized = true;
  21886. // dispose
  21887. const onDispose = () => {
  21888. renderTarget.removeEventListener( 'dispose', onDispose );
  21889. for ( let i = 0; i < textures.length; i ++ ) {
  21890. this._destroyTexture( textures[ i ] );
  21891. }
  21892. if ( depthTexture ) {
  21893. this._destroyTexture( depthTexture );
  21894. }
  21895. this.delete( renderTarget );
  21896. this.backend.delete( renderTarget );
  21897. };
  21898. renderTarget.addEventListener( 'dispose', onDispose );
  21899. }
  21900. }
  21901. /**
  21902. * Updates the given texture. Depending on the texture state, this method
  21903. * triggers the upload of texture data to the GPU memory. If the texture data are
  21904. * not yet ready for the upload, it uses default texture data for as a placeholder.
  21905. *
  21906. * @param {Texture} texture - The texture to update.
  21907. * @param {Object} [options={}] - The options.
  21908. */
  21909. updateTexture( texture, options = {} ) {
  21910. const textureData = this.get( texture );
  21911. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  21912. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  21913. const backend = this.backend;
  21914. if ( isRenderTarget && textureData.initialized === true ) {
  21915. // it's an update
  21916. backend.destroySampler( texture );
  21917. backend.destroyTexture( texture );
  21918. }
  21919. //
  21920. if ( texture.isFramebufferTexture ) {
  21921. const renderTarget = this.renderer.getRenderTarget();
  21922. if ( renderTarget ) {
  21923. texture.type = renderTarget.texture.type;
  21924. } else {
  21925. texture.type = UnsignedByteType;
  21926. }
  21927. }
  21928. //
  21929. const { width, height, depth } = this.getSize( texture );
  21930. options.width = width;
  21931. options.height = height;
  21932. options.depth = depth;
  21933. options.needsMipmaps = this.needsMipmaps( texture );
  21934. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  21935. // TODO: Uniformly handle mipmap definitions
  21936. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  21937. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  21938. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  21939. //
  21940. if ( isRenderTarget || texture.isStorageTexture === true ) {
  21941. backend.createSampler( texture );
  21942. backend.createTexture( texture, options );
  21943. textureData.generation = texture.version;
  21944. } else {
  21945. const needsCreate = textureData.initialized !== true;
  21946. if ( needsCreate ) backend.createSampler( texture );
  21947. if ( texture.version > 0 ) {
  21948. const image = texture.image;
  21949. if ( image === undefined ) {
  21950. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  21951. } else if ( image.complete === false ) {
  21952. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  21953. } else {
  21954. if ( texture.images ) {
  21955. const images = [];
  21956. for ( const image of texture.images ) {
  21957. images.push( image );
  21958. }
  21959. options.images = images;
  21960. } else {
  21961. options.image = image;
  21962. }
  21963. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  21964. backend.createTexture( texture, options );
  21965. textureData.isDefaultTexture = false;
  21966. textureData.generation = texture.version;
  21967. }
  21968. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  21969. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  21970. }
  21971. } else {
  21972. // async update
  21973. backend.createDefaultTexture( texture );
  21974. textureData.isDefaultTexture = true;
  21975. textureData.generation = texture.version;
  21976. }
  21977. }
  21978. // dispose handler
  21979. if ( textureData.initialized !== true ) {
  21980. textureData.initialized = true;
  21981. textureData.generation = texture.version;
  21982. //
  21983. this.info.memory.textures ++;
  21984. //
  21985. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  21986. console.warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  21987. }
  21988. // dispose
  21989. const onDispose = () => {
  21990. texture.removeEventListener( 'dispose', onDispose );
  21991. this._destroyTexture( texture );
  21992. };
  21993. texture.addEventListener( 'dispose', onDispose );
  21994. }
  21995. //
  21996. textureData.version = texture.version;
  21997. }
  21998. /**
  21999. * Computes the size of the given texture and writes the result
  22000. * into the target vector. This vector is also returned by the
  22001. * method.
  22002. *
  22003. * If no texture data are available for the compute yet, the method
  22004. * returns default size values.
  22005. *
  22006. * @param {Texture} texture - The texture to compute the size for.
  22007. * @param {Vector3} target - The target vector.
  22008. * @return {Vector3} The target vector.
  22009. */
  22010. getSize( texture, target = _size$3 ) {
  22011. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22012. if ( image ) {
  22013. if ( image.image !== undefined ) image = image.image;
  22014. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22015. target.width = image.videoWidth || 1;
  22016. target.height = image.videoHeight || 1;
  22017. target.depth = 1;
  22018. } else if ( image instanceof VideoFrame ) {
  22019. target.width = image.displayWidth || 1;
  22020. target.height = image.displayHeight || 1;
  22021. target.depth = 1;
  22022. } else {
  22023. target.width = image.width || 1;
  22024. target.height = image.height || 1;
  22025. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22026. }
  22027. } else {
  22028. target.width = target.height = target.depth = 1;
  22029. }
  22030. return target;
  22031. }
  22032. /**
  22033. * Computes the number of mipmap levels for the given texture.
  22034. *
  22035. * @param {Texture} texture - The texture.
  22036. * @param {number} width - The texture's width.
  22037. * @param {number} height - The texture's height.
  22038. * @return {number} The number of mipmap levels.
  22039. */
  22040. getMipLevels( texture, width, height ) {
  22041. let mipLevelCount;
  22042. if ( texture.mipmaps.length > 0 ) {
  22043. mipLevelCount = texture.mipmaps.length;
  22044. } else {
  22045. if ( texture.isCompressedTexture === true ) {
  22046. // it is not possible to compute mipmaps for compressed textures. So
  22047. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22048. // level of 1
  22049. mipLevelCount = 1;
  22050. } else {
  22051. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22052. }
  22053. }
  22054. return mipLevelCount;
  22055. }
  22056. /**
  22057. * Returns `true` if the given texture makes use of mipmapping.
  22058. *
  22059. * @param {Texture} texture - The texture.
  22060. * @return {boolean} Whether mipmaps are required or not.
  22061. */
  22062. needsMipmaps( texture ) {
  22063. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  22064. }
  22065. /**
  22066. * Frees internal resource when the given texture isn't
  22067. * required anymore.
  22068. *
  22069. * @param {Texture} texture - The texture to destroy.
  22070. */
  22071. _destroyTexture( texture ) {
  22072. if ( this.has( texture ) === true ) {
  22073. this.backend.destroySampler( texture );
  22074. this.backend.destroyTexture( texture );
  22075. this.delete( texture );
  22076. this.info.memory.textures --;
  22077. }
  22078. }
  22079. }
  22080. /**
  22081. * A four-component version of {@link Color} which is internally
  22082. * used by the renderer to represents clear color with alpha as
  22083. * one object.
  22084. *
  22085. * @private
  22086. * @augments Color
  22087. */
  22088. class Color4 extends Color {
  22089. /**
  22090. * Constructs a new four-component color.
  22091. * You can also pass a single THREE.Color, hex or
  22092. * string argument to this constructor.
  22093. *
  22094. * @param {number|string} [r=1] - The red value.
  22095. * @param {number} [g=1] - The green value.
  22096. * @param {number} [b=1] - The blue value.
  22097. * @param {number} [a=1] - The alpha value.
  22098. */
  22099. constructor( r, g, b, a = 1 ) {
  22100. super( r, g, b );
  22101. this.a = a;
  22102. }
  22103. /**
  22104. * Overwrites the default to honor alpha.
  22105. * You can also pass a single THREE.Color, hex or
  22106. * string argument to this method.
  22107. *
  22108. * @param {number|string|Color} r - The red value.
  22109. * @param {number} [g] - The green value.
  22110. * @param {number} [b] - The blue value.
  22111. * @param {number} [a=1] - The alpha value.
  22112. * @return {Color4} A reference to this object.
  22113. */
  22114. set( r, g, b, a = 1 ) {
  22115. this.a = a;
  22116. return super.set( r, g, b );
  22117. }
  22118. /**
  22119. * Overwrites the default to honor alpha.
  22120. *
  22121. * @param {Color4} color - The color to copy.
  22122. * @return {Color4} A reference to this object.
  22123. */
  22124. copy( color ) {
  22125. if ( color.a !== undefined ) this.a = color.a;
  22126. return super.copy( color );
  22127. }
  22128. /**
  22129. * Overwrites the default to honor alpha.
  22130. *
  22131. * @return {Color4} The cloned color.
  22132. */
  22133. clone() {
  22134. return new this.constructor( this.r, this.g, this.b, this.a );
  22135. }
  22136. }
  22137. /**
  22138. * Special version of {@link PropertyNode} which is used for parameters.
  22139. *
  22140. * @augments PropertyNode
  22141. */
  22142. class ParameterNode extends PropertyNode {
  22143. static get type() {
  22144. return 'ParameterNode';
  22145. }
  22146. /**
  22147. * Constructs a new parameter node.
  22148. *
  22149. * @param {string} nodeType - The type of the node.
  22150. * @param {?string} [name=null] - The name of the parameter in the shader.
  22151. */
  22152. constructor( nodeType, name = null ) {
  22153. super( nodeType, name );
  22154. /**
  22155. * This flag can be used for type testing.
  22156. *
  22157. * @type {boolean}
  22158. * @readonly
  22159. * @default true
  22160. */
  22161. this.isParameterNode = true;
  22162. }
  22163. getHash() {
  22164. return this.uuid;
  22165. }
  22166. generate() {
  22167. return this.name;
  22168. }
  22169. }
  22170. /**
  22171. * TSL function for creating a parameter node.
  22172. *
  22173. * @tsl
  22174. * @function
  22175. * @param {string} type - The type of the node.
  22176. * @param {?string} name - The name of the parameter in the shader.
  22177. * @returns {ParameterNode}
  22178. */
  22179. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  22180. /**
  22181. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  22182. * They are usually needed in cases like `If`, `Else`.
  22183. *
  22184. * @augments Node
  22185. */
  22186. class StackNode extends Node {
  22187. static get type() {
  22188. return 'StackNode';
  22189. }
  22190. /**
  22191. * Constructs a new stack node.
  22192. *
  22193. * @param {?StackNode} [parent=null] - The parent stack node.
  22194. */
  22195. constructor( parent = null ) {
  22196. super();
  22197. /**
  22198. * List of nodes.
  22199. *
  22200. * @type {Array<Node>}
  22201. */
  22202. this.nodes = [];
  22203. /**
  22204. * The output node.
  22205. *
  22206. * @type {?Node}
  22207. * @default null
  22208. */
  22209. this.outputNode = null;
  22210. /**
  22211. * The parent stack node.
  22212. *
  22213. * @type {?StackNode}
  22214. * @default null
  22215. */
  22216. this.parent = parent;
  22217. /**
  22218. * The current conditional node.
  22219. *
  22220. * @private
  22221. * @type {ConditionalNode}
  22222. * @default null
  22223. */
  22224. this._currentCond = null;
  22225. /**
  22226. * The expression node. Only
  22227. * relevant for Switch/Case.
  22228. *
  22229. * @private
  22230. * @type {Node}
  22231. * @default null
  22232. */
  22233. this._expressionNode = null;
  22234. /**
  22235. * This flag can be used for type testing.
  22236. *
  22237. * @type {boolean}
  22238. * @readonly
  22239. * @default true
  22240. */
  22241. this.isStackNode = true;
  22242. }
  22243. getNodeType( builder ) {
  22244. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  22245. }
  22246. getMemberType( builder, name ) {
  22247. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  22248. }
  22249. /**
  22250. * Adds a node to this stack.
  22251. *
  22252. * @param {Node} node - The node to add.
  22253. * @return {StackNode} A reference to this stack node.
  22254. */
  22255. add( node ) {
  22256. if ( node.isNode !== true ) {
  22257. console.error( 'THREE.TSL: Invalid node added to stack.' );
  22258. return this;
  22259. }
  22260. this.nodes.push( node );
  22261. return this;
  22262. }
  22263. /**
  22264. * Represent an `if` statement in TSL.
  22265. *
  22266. * @param {Node} boolNode - Represents the condition.
  22267. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22268. * @return {StackNode} A reference to this stack node.
  22269. */
  22270. If( boolNode, method ) {
  22271. const methodNode = new ShaderNode( method );
  22272. this._currentCond = select( boolNode, methodNode );
  22273. return this.add( this._currentCond );
  22274. }
  22275. /**
  22276. * Represent an `elseif` statement in TSL.
  22277. *
  22278. * @param {Node} boolNode - Represents the condition.
  22279. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22280. * @return {StackNode} A reference to this stack node.
  22281. */
  22282. ElseIf( boolNode, method ) {
  22283. const methodNode = new ShaderNode( method );
  22284. const ifNode = select( boolNode, methodNode );
  22285. this._currentCond.elseNode = ifNode;
  22286. this._currentCond = ifNode;
  22287. return this;
  22288. }
  22289. /**
  22290. * Represent an `else` statement in TSL.
  22291. *
  22292. * @param {Function} method - TSL code which is executed in the `else` case.
  22293. * @return {StackNode} A reference to this stack node.
  22294. */
  22295. Else( method ) {
  22296. this._currentCond.elseNode = new ShaderNode( method );
  22297. return this;
  22298. }
  22299. /**
  22300. * Represents a `switch` statement in TSL.
  22301. *
  22302. * @param {any} expression - Represents the expression.
  22303. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22304. * @return {StackNode} A reference to this stack node.
  22305. */
  22306. Switch( expression ) {
  22307. this._expressionNode = nodeObject( expression );
  22308. return this;
  22309. }
  22310. /**
  22311. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22312. * The last parameter must be the callback method that should be executed in the `true` case.
  22313. *
  22314. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22315. * @return {StackNode} A reference to this stack node.
  22316. */
  22317. Case( ...params ) {
  22318. const caseNodes = [];
  22319. // extract case nodes from the parameter list
  22320. if ( params.length >= 2 ) {
  22321. for ( let i = 0; i < params.length - 1; i ++ ) {
  22322. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22323. }
  22324. } else {
  22325. console.error( 'THREE.TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22326. }
  22327. // extract method
  22328. const method = params[ params.length - 1 ];
  22329. const methodNode = new ShaderNode( method );
  22330. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22331. let caseNode = caseNodes[ 0 ];
  22332. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22333. caseNode = caseNode.or( caseNodes[ i ] );
  22334. }
  22335. // build condition
  22336. const condNode = select( caseNode, methodNode );
  22337. if ( this._currentCond === null ) {
  22338. this._currentCond = condNode;
  22339. return this.add( this._currentCond );
  22340. } else {
  22341. this._currentCond.elseNode = condNode;
  22342. this._currentCond = condNode;
  22343. return this;
  22344. }
  22345. }
  22346. /**
  22347. * Represents the default code block of a Switch/Case statement.
  22348. *
  22349. * @param {Function} method - TSL code which is executed in the `else` case.
  22350. * @return {StackNode} A reference to this stack node.
  22351. */
  22352. Default( method ) {
  22353. this.Else( method );
  22354. return this;
  22355. }
  22356. setup( builder ) {
  22357. const nodeProperties = builder.getNodeProperties( this );
  22358. let index = 0;
  22359. for ( const childNode of this.getChildren() ) {
  22360. if ( childNode.isVarNode && childNode.intent === true ) {
  22361. const properties = builder.getNodeProperties( childNode );
  22362. if ( properties.assign !== true ) {
  22363. continue;
  22364. }
  22365. }
  22366. nodeProperties[ 'node' + index ++ ] = childNode;
  22367. }
  22368. // return a outputNode if exists or null
  22369. return nodeProperties.outputNode || null;
  22370. }
  22371. get hasOutput() {
  22372. return this.outputNode && this.outputNode.isNode;
  22373. }
  22374. build( builder, ...params ) {
  22375. const previousBuildStack = builder.currentStack;
  22376. const previousStack = getCurrentStack();
  22377. setCurrentStack( this );
  22378. builder.currentStack = this;
  22379. const buildStage = builder.buildStage;
  22380. for ( const node of this.nodes ) {
  22381. if ( node.isVarNode && node.intent === true ) {
  22382. const properties = builder.getNodeProperties( node );
  22383. if ( properties.assign !== true ) {
  22384. continue;
  22385. }
  22386. }
  22387. if ( buildStage === 'setup' ) {
  22388. node.build( builder );
  22389. } else if ( buildStage === 'analyze' ) {
  22390. node.build( builder, this );
  22391. } else if ( buildStage === 'generate' ) {
  22392. const stages = builder.getDataFromNode( node, 'any' ).stages;
  22393. const parents = stages && stages[ builder.shaderStage ];
  22394. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  22395. continue; // skip var nodes that are only used in .toVarying()
  22396. }
  22397. node.build( builder, 'void' );
  22398. }
  22399. }
  22400. //
  22401. let result;
  22402. if ( this.hasOutput ) {
  22403. result = this.outputNode.build( builder, ...params );
  22404. } else {
  22405. result = super.build( builder, ...params );
  22406. }
  22407. setCurrentStack( previousStack );
  22408. builder.currentStack = previousBuildStack;
  22409. return result;
  22410. }
  22411. }
  22412. /**
  22413. * TSL function for creating a stack node.
  22414. *
  22415. * @tsl
  22416. * @function
  22417. * @param {?StackNode} [parent=null] - The parent stack node.
  22418. * @returns {StackNode}
  22419. */
  22420. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  22421. /**
  22422. * Generates a layout for struct members.
  22423. * This function takes an object representing struct members and returns an array of member layouts.
  22424. * Each member layout includes the member's name, type, and whether it is atomic.
  22425. *
  22426. * @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.
  22427. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  22428. */
  22429. function getMembersLayout( members ) {
  22430. return Object.entries( members ).map( ( [ name, value ] ) => {
  22431. if ( typeof value === 'string' ) {
  22432. return { name, type: value, atomic: false };
  22433. }
  22434. return { name, type: value.type, atomic: value.atomic || false };
  22435. } );
  22436. }
  22437. /**
  22438. * Represents a struct type node in the node-based system.
  22439. * This class is used to define and manage the layout and types of struct members.
  22440. * It extends the base Node class and provides methods to get the length of the struct,
  22441. * retrieve member types, and generate the struct type for a builder.
  22442. *
  22443. * @augments Node
  22444. */
  22445. class StructTypeNode extends Node {
  22446. static get type() {
  22447. return 'StructTypeNode';
  22448. }
  22449. /**
  22450. * Creates an instance of StructTypeNode.
  22451. *
  22452. * @param {Object} membersLayout - The layout of the members for the struct.
  22453. * @param {?string} [name=null] - The optional name of the struct.
  22454. */
  22455. constructor( membersLayout, name = null ) {
  22456. super( 'struct' );
  22457. /**
  22458. * The layout of the members for the struct
  22459. *
  22460. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  22461. */
  22462. this.membersLayout = getMembersLayout( membersLayout );
  22463. /**
  22464. * The name of the struct.
  22465. *
  22466. * @type {?string}
  22467. * @default null
  22468. */
  22469. this.name = name;
  22470. /**
  22471. * This flag can be used for type testing.
  22472. *
  22473. * @type {boolean}
  22474. * @readonly
  22475. * @default true
  22476. */
  22477. this.isStructLayoutNode = true;
  22478. }
  22479. /**
  22480. * Returns the length of the struct.
  22481. * The length is calculated by summing the lengths of the struct's members.
  22482. *
  22483. * @returns {number} The length of the struct.
  22484. */
  22485. getLength() {
  22486. const GPU_CHUNK_BYTES = 8;
  22487. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  22488. let offset = 0; // global buffer offset in bytes
  22489. for ( const member of this.membersLayout ) {
  22490. const type = member.type;
  22491. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  22492. const boundary = getByteBoundaryFromType( type );
  22493. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  22494. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  22495. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  22496. offset += chunkPadding;
  22497. // Check for chunk overflow
  22498. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  22499. // Add padding to the end of the chunk
  22500. offset += ( GPU_CHUNK_BYTES - chunkStart );
  22501. }
  22502. offset += itemSize;
  22503. }
  22504. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  22505. }
  22506. getMemberType( builder, name ) {
  22507. const member = this.membersLayout.find( m => m.name === name );
  22508. return member ? member.type : 'void';
  22509. }
  22510. getNodeType( builder ) {
  22511. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22512. return structType.name;
  22513. }
  22514. setup( builder ) {
  22515. builder.addInclude( this );
  22516. }
  22517. generate( builder ) {
  22518. return this.getNodeType( builder );
  22519. }
  22520. }
  22521. /**
  22522. * StructNode allows to create custom structures with multiple members.
  22523. * This can also be used to define structures in attribute and uniform data.
  22524. *
  22525. * ```js
  22526. * // Define a custom struct
  22527. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  22528. *
  22529. * // Create a new instance of the struct
  22530. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  22531. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  22532. *
  22533. * // Access the struct members
  22534. * const min = bb.get( 'min' );
  22535. *
  22536. * // Assign a new value to a member
  22537. * min.assign( vec3() );
  22538. * ```
  22539. * @augments Node
  22540. */
  22541. class StructNode extends Node {
  22542. static get type() {
  22543. return 'StructNode';
  22544. }
  22545. constructor( structLayoutNode, values ) {
  22546. super( 'vec3' );
  22547. this.structLayoutNode = structLayoutNode;
  22548. this.values = values;
  22549. this.isStructNode = true;
  22550. }
  22551. getNodeType( builder ) {
  22552. return this.structLayoutNode.getNodeType( builder );
  22553. }
  22554. getMemberType( builder, name ) {
  22555. return this.structLayoutNode.getMemberType( builder, name );
  22556. }
  22557. generate( builder ) {
  22558. const nodeVar = builder.getVarFromNode( this );
  22559. const structType = nodeVar.type;
  22560. const propertyName = builder.getPropertyName( nodeVar );
  22561. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  22562. return nodeVar.name;
  22563. }
  22564. }
  22565. /**
  22566. * TSL function for creating a struct node.
  22567. *
  22568. * @tsl
  22569. * @function
  22570. * @param {Object} membersLayout - The layout of the struct members.
  22571. * @param {?string} [name=null] - The name of the struct.
  22572. * @returns {Function} The struct function.
  22573. */
  22574. const struct = ( membersLayout, name = null ) => {
  22575. const structLayout = new StructTypeNode( membersLayout, name );
  22576. const struct = ( ...params ) => {
  22577. let values = null;
  22578. if ( params.length > 0 ) {
  22579. if ( params[ 0 ].isNode ) {
  22580. values = {};
  22581. const names = Object.keys( membersLayout );
  22582. for ( let i = 0; i < params.length; i ++ ) {
  22583. values[ names[ i ] ] = params[ i ];
  22584. }
  22585. } else {
  22586. values = params[ 0 ];
  22587. }
  22588. }
  22589. return nodeObject( new StructNode( structLayout, values ) );
  22590. };
  22591. struct.layout = structLayout;
  22592. struct.isStruct = true;
  22593. return struct;
  22594. };
  22595. /**
  22596. * This node can be used to define multiple outputs in a shader programs.
  22597. *
  22598. * @augments Node
  22599. */
  22600. class OutputStructNode extends Node {
  22601. static get type() {
  22602. return 'OutputStructNode';
  22603. }
  22604. /**
  22605. * Constructs a new output struct node. The constructor can be invoked with an
  22606. * arbitrary number of nodes representing the members.
  22607. *
  22608. * @param {...Node} members - A parameter list of nodes.
  22609. */
  22610. constructor( ...members ) {
  22611. super();
  22612. /**
  22613. * An array of nodes which defines the output.
  22614. *
  22615. * @type {Array<Node>}
  22616. */
  22617. this.members = members;
  22618. /**
  22619. * This flag can be used for type testing.
  22620. *
  22621. * @type {boolean}
  22622. * @readonly
  22623. * @default true
  22624. */
  22625. this.isOutputStructNode = true;
  22626. }
  22627. getNodeType( builder ) {
  22628. const properties = builder.getNodeProperties( this );
  22629. if ( properties.membersLayout === undefined ) {
  22630. const members = this.members;
  22631. const membersLayout = [];
  22632. for ( let i = 0; i < members.length; i ++ ) {
  22633. const name = 'm' + i;
  22634. const type = members[ i ].getNodeType( builder );
  22635. membersLayout.push( { name, type, index: i } );
  22636. }
  22637. properties.membersLayout = membersLayout;
  22638. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  22639. }
  22640. return properties.structType.name;
  22641. }
  22642. generate( builder ) {
  22643. const propertyName = builder.getOutputStructName();
  22644. const members = this.members;
  22645. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  22646. for ( let i = 0; i < members.length; i ++ ) {
  22647. const snippet = members[ i ].build( builder );
  22648. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  22649. }
  22650. return propertyName;
  22651. }
  22652. }
  22653. /**
  22654. * TSL function for creating an output struct node.
  22655. *
  22656. * @tsl
  22657. * @function
  22658. * @param {...Node} members - A parameter list of nodes.
  22659. * @returns {OutputStructNode}
  22660. */
  22661. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  22662. /**
  22663. * Returns the MRT texture index for the given name.
  22664. *
  22665. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  22666. * @param {string} name - The name of the MRT texture which index is requested.
  22667. * @return {number} The texture index.
  22668. */
  22669. function getTextureIndex( textures, name ) {
  22670. for ( let i = 0; i < textures.length; i ++ ) {
  22671. if ( textures[ i ].name === name ) {
  22672. return i;
  22673. }
  22674. }
  22675. return -1;
  22676. }
  22677. /**
  22678. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  22679. * post-processing is shown below:
  22680. * ```js
  22681. * const mrtNode = mrt( {
  22682. * output: output,
  22683. * normal: normalView
  22684. * } ) );
  22685. * ```
  22686. * The MRT output is defined as a dictionary.
  22687. *
  22688. * @augments OutputStructNode
  22689. */
  22690. class MRTNode extends OutputStructNode {
  22691. static get type() {
  22692. return 'MRTNode';
  22693. }
  22694. /**
  22695. * Constructs a new output struct node.
  22696. *
  22697. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22698. */
  22699. constructor( outputNodes ) {
  22700. super();
  22701. /**
  22702. * A dictionary representing the MRT outputs. The key
  22703. * is the name of the output, the value the node which produces
  22704. * the output result.
  22705. *
  22706. * @type {Object<string, Node>}
  22707. */
  22708. this.outputNodes = outputNodes;
  22709. /**
  22710. * This flag can be used for type testing.
  22711. *
  22712. * @type {boolean}
  22713. * @readonly
  22714. * @default true
  22715. */
  22716. this.isMRTNode = true;
  22717. }
  22718. /**
  22719. * Returns `true` if the MRT node has an output with the given name.
  22720. *
  22721. * @param {string} name - The name of the output.
  22722. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  22723. */
  22724. has( name ) {
  22725. return this.outputNodes[ name ] !== undefined;
  22726. }
  22727. /**
  22728. * Returns the output node for the given name.
  22729. *
  22730. * @param {string} name - The name of the output.
  22731. * @return {Node} The output node.
  22732. */
  22733. get( name ) {
  22734. return this.outputNodes[ name ];
  22735. }
  22736. /**
  22737. * Merges the outputs of the given MRT node with the outputs of this node.
  22738. *
  22739. * @param {MRTNode} mrtNode - The MRT to merge.
  22740. * @return {MRTNode} A new MRT node with merged outputs..
  22741. */
  22742. merge( mrtNode ) {
  22743. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  22744. return mrt( outputs );
  22745. }
  22746. setup( builder ) {
  22747. const outputNodes = this.outputNodes;
  22748. const mrt = builder.renderer.getRenderTarget();
  22749. const members = [];
  22750. const textures = mrt.textures;
  22751. for ( const name in outputNodes ) {
  22752. const index = getTextureIndex( textures, name );
  22753. members[ index ] = vec4( outputNodes[ name ] );
  22754. }
  22755. this.members = members;
  22756. return super.setup( builder );
  22757. }
  22758. }
  22759. /**
  22760. * TSL function for creating a MRT node.
  22761. *
  22762. * @tsl
  22763. * @function
  22764. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22765. * @returns {MRTNode}
  22766. */
  22767. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  22768. /**
  22769. * Generates a hash value in the range `[0, 1]` from the given seed.
  22770. *
  22771. * @tsl
  22772. * @function
  22773. * @param {Node<float>} seed - The seed.
  22774. * @return {Node<float>} The hash value.
  22775. */
  22776. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  22777. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  22778. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  22779. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  22780. const result = word.shiftRight( 22 ).bitXor( word );
  22781. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  22782. } );
  22783. /**
  22784. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22785. * The corners are mapped to `0` and the center to `1`.
  22786. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22787. *
  22788. * @tsl
  22789. * @function
  22790. * @param {Node<float>} x - The value to remap.
  22791. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  22792. * @return {Node<float>} The remapped value.
  22793. */
  22794. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  22795. /**
  22796. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22797. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  22798. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22799. *
  22800. * @tsl
  22801. * @function
  22802. * @param {Node<float>} x - The value to remap.
  22803. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  22804. * @return {Node<float>} The remapped value.
  22805. */
  22806. 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 ) );
  22807. /**
  22808. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22809. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  22810. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22811. *
  22812. * @tsl
  22813. * @function
  22814. * @param {Node<float>} x - The value to remap.
  22815. * @param {Node<float>} a - First control parameter.
  22816. * @param {Node<float>} b - Second control parameter.
  22817. * @return {Node<float>} The remapped value.
  22818. */
  22819. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  22820. /**
  22821. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  22822. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22823. *
  22824. * @tsl
  22825. * @function
  22826. * @param {Node<float>} x - The value to compute the sin for.
  22827. * @param {Node<float>} k - Controls the amount of bounces.
  22828. * @return {Node<float>} The result value.
  22829. */
  22830. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  22831. // https://github.com/cabbibo/glsl-tri-noise-3d
  22832. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  22833. return x.fract().sub( .5 ).abs();
  22834. } ).setLayout( {
  22835. name: 'tri',
  22836. type: 'float',
  22837. inputs: [
  22838. { name: 'x', type: 'float' }
  22839. ]
  22840. } );
  22841. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  22842. 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. ) ) ) ) );
  22843. } ).setLayout( {
  22844. name: 'tri3',
  22845. type: 'vec3',
  22846. inputs: [
  22847. { name: 'p', type: 'vec3' }
  22848. ]
  22849. } );
  22850. /**
  22851. * Generates a noise value from the given position, speed and time parameters.
  22852. *
  22853. * @tsl
  22854. * @function
  22855. * @param {Node<vec3>} position - The position.
  22856. * @param {Node<float>} speed - The speed.
  22857. * @param {Node<float>} time - The time.
  22858. * @return {Node<float>} The generated noise.
  22859. */
  22860. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  22861. const p = vec3( position ).toVar();
  22862. const z = float( 1.4 ).toVar();
  22863. const rz = float( 0.0 ).toVar();
  22864. const bp = vec3( p ).toVar();
  22865. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  22866. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  22867. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  22868. bp.mulAssign( 1.8 );
  22869. z.mulAssign( 1.5 );
  22870. p.mulAssign( 1.2 );
  22871. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  22872. rz.addAssign( t.div( z ) );
  22873. bp.addAssign( 0.14 );
  22874. } );
  22875. return rz;
  22876. } ).setLayout( {
  22877. name: 'triNoise3D',
  22878. type: 'float',
  22879. inputs: [
  22880. { name: 'position', type: 'vec3' },
  22881. { name: 'speed', type: 'float' },
  22882. { name: 'time', type: 'float' }
  22883. ]
  22884. } );
  22885. /**
  22886. * This class allows to define multiple overloaded versions
  22887. * of the same function. Depending on the parameters of the function
  22888. * call, the node picks the best-fit overloaded version.
  22889. *
  22890. * @augments Node
  22891. */
  22892. class FunctionOverloadingNode extends Node {
  22893. static get type() {
  22894. return 'FunctionOverloadingNode';
  22895. }
  22896. /**
  22897. * Constructs a new function overloading node.
  22898. *
  22899. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22900. * @param {...Node} parametersNodes - A list of parameter nodes.
  22901. */
  22902. constructor( functionNodes = [], ...parametersNodes ) {
  22903. super();
  22904. /**
  22905. * Array of `Fn` function definitions.
  22906. *
  22907. * @type {Array<Function>}
  22908. */
  22909. this.functionNodes = functionNodes;
  22910. /**
  22911. * A list of parameter nodes.
  22912. *
  22913. * @type {Array<Node>}
  22914. */
  22915. this.parametersNodes = parametersNodes;
  22916. /**
  22917. * The selected overloaded function call.
  22918. *
  22919. * @private
  22920. * @type {ShaderCallNodeInternal}
  22921. */
  22922. this._candidateFnCall = null;
  22923. /**
  22924. * This node is marked as global.
  22925. *
  22926. * @type {boolean}
  22927. * @default true
  22928. */
  22929. this.global = true;
  22930. }
  22931. /**
  22932. * This method is overwritten since the node type is inferred from
  22933. * the function's return type.
  22934. *
  22935. * @param {NodeBuilder} builder - The current node builder.
  22936. * @return {string} The node type.
  22937. */
  22938. getNodeType() {
  22939. return this.functionNodes[ 0 ].shaderNode.layout.type;
  22940. }
  22941. setup( builder ) {
  22942. const params = this.parametersNodes;
  22943. let candidateFnCall = this._candidateFnCall;
  22944. if ( candidateFnCall === null ) {
  22945. let candidateFn = null;
  22946. let candidateScore = -1;
  22947. for ( const functionNode of this.functionNodes ) {
  22948. const shaderNode = functionNode.shaderNode;
  22949. const layout = shaderNode.layout;
  22950. if ( layout === null ) {
  22951. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  22952. }
  22953. const inputs = layout.inputs;
  22954. if ( params.length === inputs.length ) {
  22955. let score = 0;
  22956. for ( let i = 0; i < params.length; i ++ ) {
  22957. const param = params[ i ];
  22958. const input = inputs[ i ];
  22959. if ( param.getNodeType( builder ) === input.type ) {
  22960. score ++;
  22961. } else {
  22962. score = 0;
  22963. }
  22964. }
  22965. if ( score > candidateScore ) {
  22966. candidateFn = functionNode;
  22967. candidateScore = score;
  22968. }
  22969. }
  22970. }
  22971. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  22972. }
  22973. return candidateFnCall;
  22974. }
  22975. }
  22976. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  22977. /**
  22978. * TSL function for creating a function overloading node.
  22979. *
  22980. * @tsl
  22981. * @function
  22982. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22983. * @returns {FunctionOverloadingNode}
  22984. */
  22985. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  22986. /**
  22987. * Represents the elapsed time in seconds.
  22988. *
  22989. * @tsl
  22990. * @type {UniformNode<float>}
  22991. */
  22992. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  22993. /**
  22994. * Represents the delta time in seconds.
  22995. *
  22996. * @tsl
  22997. * @type {UniformNode<float>}
  22998. */
  22999. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  23000. /**
  23001. * Represents the current frame ID.
  23002. *
  23003. * @tsl
  23004. * @type {UniformNode<uint>}
  23005. */
  23006. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  23007. /**
  23008. * Generates a sine wave oscillation based on a timer.
  23009. *
  23010. * @tsl
  23011. * @function
  23012. * @param {Node<float>} t - The timer to generate the oscillation with.
  23013. * @return {Node<float>} The oscillation node.
  23014. */
  23015. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  23016. /**
  23017. * Generates a square wave oscillation based on a timer.
  23018. *
  23019. * @tsl
  23020. * @function
  23021. * @param {Node<float>} t - The timer to generate the oscillation with.
  23022. * @return {Node<float>} The oscillation node.
  23023. */
  23024. const oscSquare = ( t = time ) => t.fract().round();
  23025. /**
  23026. * Generates a triangle wave oscillation based on a timer.
  23027. *
  23028. * @tsl
  23029. * @function
  23030. * @param {Node<float>} t - The timer to generate the oscillation with.
  23031. * @return {Node<float>} The oscillation node.
  23032. */
  23033. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  23034. /**
  23035. * Generates a sawtooth wave oscillation based on a timer.
  23036. *
  23037. * @tsl
  23038. * @function
  23039. * @param {Node<float>} t - The timer to generate the oscillation with.
  23040. * @return {Node<float>} The oscillation node.
  23041. */
  23042. const oscSawtooth = ( t = time ) => t.fract();
  23043. /**
  23044. * Rotates the given uv coordinates around a center point
  23045. *
  23046. * @tsl
  23047. * @function
  23048. * @param {Node<vec2>} uv - The uv coordinates.
  23049. * @param {Node<float>} rotation - The rotation defined in radians.
  23050. * @param {Node<vec2>} center - The center of rotation
  23051. * @return {Node<vec2>} The rotated uv coordinates.
  23052. */
  23053. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  23054. return rotate( uv.sub( center ), rotation ).add( center );
  23055. } );
  23056. /**
  23057. * Applies a spherical warping effect to the given uv coordinates.
  23058. *
  23059. * @tsl
  23060. * @function
  23061. * @param {Node<vec2>} uv - The uv coordinates.
  23062. * @param {Node<float>} strength - The strength of the effect.
  23063. * @param {Node<vec2>} center - The center point
  23064. * @return {Node<vec2>} The updated uv coordinates.
  23065. */
  23066. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  23067. const delta = uv.sub( center );
  23068. const delta2 = delta.dot( delta );
  23069. const delta4 = delta2.mul( delta2 );
  23070. const deltaOffset = delta4.mul( strength );
  23071. return uv.add( delta.mul( deltaOffset ) );
  23072. } );
  23073. /**
  23074. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  23075. * oriented always towards the camera.
  23076. *
  23077. * ```js
  23078. * material.vertexNode = billboarding();
  23079. * ```
  23080. *
  23081. * @tsl
  23082. * @function
  23083. * @param {Object} config - The configuration object.
  23084. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  23085. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  23086. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  23087. * @return {Node<vec3>} The updated vertex position in clip space.
  23088. */
  23089. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  23090. let worldMatrix;
  23091. if ( position !== null ) {
  23092. worldMatrix = modelWorldMatrix.toVar();
  23093. worldMatrix[ 3 ][ 0 ] = position.x;
  23094. worldMatrix[ 3 ][ 1 ] = position.y;
  23095. worldMatrix[ 3 ][ 2 ] = position.z;
  23096. } else {
  23097. worldMatrix = modelWorldMatrix;
  23098. }
  23099. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  23100. if ( defined( horizontal ) ) {
  23101. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  23102. modelViewMatrix[ 0 ][ 1 ] = 0;
  23103. modelViewMatrix[ 0 ][ 2 ] = 0;
  23104. }
  23105. if ( defined( vertical ) ) {
  23106. modelViewMatrix[ 1 ][ 0 ] = 0;
  23107. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  23108. modelViewMatrix[ 1 ][ 2 ] = 0;
  23109. }
  23110. modelViewMatrix[ 2 ][ 0 ] = 0;
  23111. modelViewMatrix[ 2 ][ 1 ] = 0;
  23112. modelViewMatrix[ 2 ][ 2 ] = 1;
  23113. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23114. } );
  23115. /**
  23116. * A special version of a screen uv function that involves a depth comparison
  23117. * when computing the final uvs. The function mitigates visual errors when
  23118. * using viewport texture nodes for refraction purposes. Without this function
  23119. * objects in front of a refractive surface might appear on the refractive surface
  23120. * which is incorrect.
  23121. *
  23122. * @tsl
  23123. * @function
  23124. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  23125. * @return {Node<vec2>} The update uv coordinates.
  23126. */
  23127. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  23128. const depth = linearDepth();
  23129. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  23130. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  23131. return finalUV;
  23132. } );
  23133. /**
  23134. * Can be used to compute texture coordinates for animated sprite sheets.
  23135. *
  23136. * ```js
  23137. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  23138. *
  23139. * material.colorNode = texture( spriteSheet, uvNode );
  23140. * ```
  23141. *
  23142. * @augments Node
  23143. */
  23144. class SpriteSheetUVNode extends Node {
  23145. static get type() {
  23146. return 'SpriteSheetUVNode';
  23147. }
  23148. /**
  23149. * Constructs a new sprite sheet uv node.
  23150. *
  23151. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23152. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  23153. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23154. */
  23155. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  23156. super( 'vec2' );
  23157. /**
  23158. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23159. *
  23160. * @type {Node<vec2>}
  23161. */
  23162. this.countNode = countNode;
  23163. /**
  23164. * The uv node.
  23165. *
  23166. * @type {Node<vec2>}
  23167. */
  23168. this.uvNode = uvNode;
  23169. /**
  23170. * The node that defines the current frame/sprite.
  23171. *
  23172. * @type {Node<float>}
  23173. */
  23174. this.frameNode = frameNode;
  23175. }
  23176. setup() {
  23177. const { frameNode, uvNode, countNode } = this;
  23178. const { width, height } = countNode;
  23179. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  23180. const column = frameNum.mod( width );
  23181. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  23182. const scale = countNode.reciprocal();
  23183. const uvFrameOffset = vec2( column, row );
  23184. return uvNode.add( uvFrameOffset ).mul( scale );
  23185. }
  23186. }
  23187. /**
  23188. * TSL function for creating a sprite sheet uv node.
  23189. *
  23190. * @tsl
  23191. * @function
  23192. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23193. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  23194. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23195. * @returns {SpriteSheetUVNode}
  23196. */
  23197. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  23198. /**
  23199. * TSL function for creating a triplanar textures node.
  23200. *
  23201. * Can be used for triplanar texture mapping.
  23202. *
  23203. * ```js
  23204. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  23205. * ```
  23206. *
  23207. * @tsl
  23208. * @function
  23209. * @param {Node} textureXNode - First texture node.
  23210. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23211. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23212. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23213. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23214. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23215. * @returns {Node<vec4>}
  23216. */
  23217. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  23218. // Reference: https://github.com/keijiro/StandardTriplanar
  23219. // Blending factor of triplanar mapping
  23220. let bf = normalNode.abs().normalize();
  23221. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  23222. // Triplanar mapping
  23223. const tx = positionNode.yz.mul( scaleNode );
  23224. const ty = positionNode.zx.mul( scaleNode );
  23225. const tz = positionNode.xy.mul( scaleNode );
  23226. // Base color
  23227. const textureX = textureXNode.value;
  23228. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  23229. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  23230. const cx = texture( textureX, tx ).mul( bf.x );
  23231. const cy = texture( textureY, ty ).mul( bf.y );
  23232. const cz = texture( textureZ, tz ).mul( bf.z );
  23233. return add( cx, cy, cz );
  23234. } );
  23235. /**
  23236. * TSL function for creating a triplanar textures node.
  23237. *
  23238. * @tsl
  23239. * @function
  23240. * @param {Node} textureXNode - First texture node.
  23241. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23242. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23243. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23244. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23245. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23246. * @returns {Node<vec4>}
  23247. */
  23248. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  23249. const _reflectorPlane = new Plane();
  23250. const _normal = new Vector3();
  23251. const _reflectorWorldPosition = new Vector3();
  23252. const _cameraWorldPosition = new Vector3();
  23253. const _rotationMatrix = new Matrix4();
  23254. const _lookAtPosition = new Vector3( 0, 0, -1 );
  23255. const clipPlane = new Vector4();
  23256. const _view = new Vector3();
  23257. const _target = new Vector3();
  23258. const _q = new Vector4();
  23259. const _size$2 = new Vector2();
  23260. const _defaultRT = new RenderTarget();
  23261. const _defaultUV = screenUV.flipX();
  23262. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  23263. let _inReflector = false;
  23264. /**
  23265. * This node can be used to implement mirror-like flat reflective surfaces.
  23266. *
  23267. * ```js
  23268. * const groundReflector = reflector();
  23269. * material.colorNode = groundReflector;
  23270. *
  23271. * const plane = new Mesh( geometry, material );
  23272. * plane.add( groundReflector.target );
  23273. * ```
  23274. *
  23275. * @augments TextureNode
  23276. */
  23277. class ReflectorNode extends TextureNode {
  23278. static get type() {
  23279. return 'ReflectorNode';
  23280. }
  23281. /**
  23282. * Constructs a new reflector node.
  23283. *
  23284. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23285. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23286. * @param {number} [parameters.resolution=1] - The resolution scale.
  23287. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23288. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23289. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23290. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23291. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23292. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23293. */
  23294. constructor( parameters = {} ) {
  23295. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  23296. /**
  23297. * A reference to the internal reflector base node which holds the actual implementation.
  23298. *
  23299. * @private
  23300. * @type {ReflectorBaseNode}
  23301. * @default ReflectorBaseNode
  23302. */
  23303. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  23304. /**
  23305. * A reference to the internal depth node.
  23306. *
  23307. * @private
  23308. * @type {?Node}
  23309. * @default null
  23310. */
  23311. this._depthNode = null;
  23312. this.setUpdateMatrix( false );
  23313. }
  23314. /**
  23315. * A reference to the internal reflector node.
  23316. *
  23317. * @type {ReflectorBaseNode}
  23318. */
  23319. get reflector() {
  23320. return this._reflectorBaseNode;
  23321. }
  23322. /**
  23323. * A reference to 3D object the reflector is linked to.
  23324. *
  23325. * @type {Object3D}
  23326. */
  23327. get target() {
  23328. return this._reflectorBaseNode.target;
  23329. }
  23330. /**
  23331. * Returns a node representing the mirror's depth. That can be used
  23332. * to implement more advanced reflection effects like distance attenuation.
  23333. *
  23334. * @return {Node} The depth node.
  23335. */
  23336. getDepthNode() {
  23337. if ( this._depthNode === null ) {
  23338. if ( this._reflectorBaseNode.depth !== true ) {
  23339. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  23340. }
  23341. this._depthNode = nodeObject( new ReflectorNode( {
  23342. defaultTexture: _defaultRT.depthTexture,
  23343. reflector: this._reflectorBaseNode
  23344. } ) );
  23345. }
  23346. return this._depthNode;
  23347. }
  23348. setup( builder ) {
  23349. // ignore if used in post-processing
  23350. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  23351. return super.setup( builder );
  23352. }
  23353. clone() {
  23354. const newNode = new this.constructor( this.reflectorNode );
  23355. newNode.uvNode = this.uvNode;
  23356. newNode.levelNode = this.levelNode;
  23357. newNode.biasNode = this.biasNode;
  23358. newNode.sampler = this.sampler;
  23359. newNode.depthNode = this.depthNode;
  23360. newNode.compareNode = this.compareNode;
  23361. newNode.gradNode = this.gradNode;
  23362. newNode._reflectorBaseNode = this._reflectorBaseNode;
  23363. return newNode;
  23364. }
  23365. /**
  23366. * Frees internal resources. Should be called when the node is no longer in use.
  23367. */
  23368. dispose() {
  23369. super.dispose();
  23370. this._reflectorBaseNode.dispose();
  23371. }
  23372. }
  23373. /**
  23374. * Holds the actual implementation of the reflector.
  23375. *
  23376. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  23377. * in `ReflectorNode`, see #29619.
  23378. *
  23379. * @private
  23380. * @augments Node
  23381. */
  23382. class ReflectorBaseNode extends Node {
  23383. static get type() {
  23384. return 'ReflectorBaseNode';
  23385. }
  23386. /**
  23387. * Constructs a new reflector base node.
  23388. *
  23389. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  23390. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23391. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23392. * @param {number} [parameters.resolution=1] - The resolution scale.
  23393. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23394. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23395. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23396. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23397. */
  23398. constructor( textureNode, parameters = {} ) {
  23399. super();
  23400. const {
  23401. target = new Object3D(),
  23402. resolution = 1,
  23403. generateMipmaps = false,
  23404. bounces = true,
  23405. depth = false,
  23406. samples = 0
  23407. } = parameters;
  23408. /**
  23409. * Represents the rendered reflections as a texture node.
  23410. *
  23411. * @type {TextureNode}
  23412. */
  23413. this.textureNode = textureNode;
  23414. /**
  23415. * The 3D object the reflector is linked to.
  23416. *
  23417. * @type {Object3D}
  23418. * @default {new Object3D()}
  23419. */
  23420. this.target = target;
  23421. /**
  23422. * The resolution scale.
  23423. *
  23424. * @type {number}
  23425. * @default {1}
  23426. */
  23427. this.resolution = resolution;
  23428. /**
  23429. * Whether mipmaps should be generated or not.
  23430. *
  23431. * @type {boolean}
  23432. * @default {false}
  23433. */
  23434. this.generateMipmaps = generateMipmaps;
  23435. /**
  23436. * Whether reflectors can render other reflector nodes or not.
  23437. *
  23438. * @type {boolean}
  23439. * @default {true}
  23440. */
  23441. this.bounces = bounces;
  23442. /**
  23443. * Whether depth data should be generated or not.
  23444. *
  23445. * @type {boolean}
  23446. * @default {false}
  23447. */
  23448. this.depth = depth;
  23449. /**
  23450. * The number of anti-aliasing samples for the render-target
  23451. *
  23452. * @type {number}
  23453. * @default {0}
  23454. */
  23455. this.samples = samples;
  23456. /**
  23457. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  23458. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  23459. *
  23460. * @type {string}
  23461. * @default 'render'
  23462. */
  23463. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  23464. /**
  23465. * Weak map for managing virtual cameras.
  23466. *
  23467. * @type {WeakMap<Camera, Camera>}
  23468. */
  23469. this.virtualCameras = new WeakMap();
  23470. /**
  23471. * Weak map for managing render targets.
  23472. *
  23473. * @type {Map<Camera, RenderTarget>}
  23474. */
  23475. this.renderTargets = new Map();
  23476. /**
  23477. * Force render even if reflector is facing away from camera.
  23478. *
  23479. * @type {boolean}
  23480. * @default {false}
  23481. */
  23482. this.forceUpdate = false;
  23483. /**
  23484. * Whether the reflector has been rendered or not.
  23485. *
  23486. * When the reflector is facing away from the camera,
  23487. * this flag is set to `false` and the texture will be empty(black).
  23488. *
  23489. * @type {boolean}
  23490. * @default {false}
  23491. */
  23492. this.hasOutput = false;
  23493. }
  23494. /**
  23495. * Updates the resolution of the internal render target.
  23496. *
  23497. * @private
  23498. * @param {RenderTarget} renderTarget - The render target to resize.
  23499. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  23500. */
  23501. _updateResolution( renderTarget, renderer ) {
  23502. const resolution = this.resolution;
  23503. renderer.getDrawingBufferSize( _size$2 );
  23504. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  23505. }
  23506. setup( builder ) {
  23507. this._updateResolution( _defaultRT, builder.renderer );
  23508. return super.setup( builder );
  23509. }
  23510. /**
  23511. * Frees internal resources. Should be called when the node is no longer in use.
  23512. */
  23513. dispose() {
  23514. super.dispose();
  23515. for ( const renderTarget of this.renderTargets.values() ) {
  23516. renderTarget.dispose();
  23517. }
  23518. }
  23519. /**
  23520. * Returns a virtual camera for the given camera. The virtual camera is used to
  23521. * render the scene from the reflector's view so correct reflections can be produced.
  23522. *
  23523. * @param {Camera} camera - The scene's camera.
  23524. * @return {Camera} The corresponding virtual camera.
  23525. */
  23526. getVirtualCamera( camera ) {
  23527. let virtualCamera = this.virtualCameras.get( camera );
  23528. if ( virtualCamera === undefined ) {
  23529. virtualCamera = camera.clone();
  23530. this.virtualCameras.set( camera, virtualCamera );
  23531. }
  23532. return virtualCamera;
  23533. }
  23534. /**
  23535. * Returns a render target for the given camera. The reflections are rendered
  23536. * into this render target.
  23537. *
  23538. * @param {Camera} camera - The scene's camera.
  23539. * @return {RenderTarget} The render target.
  23540. */
  23541. getRenderTarget( camera ) {
  23542. let renderTarget = this.renderTargets.get( camera );
  23543. if ( renderTarget === undefined ) {
  23544. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  23545. if ( this.generateMipmaps === true ) {
  23546. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  23547. renderTarget.texture.generateMipmaps = true;
  23548. }
  23549. if ( this.depth === true ) {
  23550. renderTarget.depthTexture = new DepthTexture();
  23551. }
  23552. this.renderTargets.set( camera, renderTarget );
  23553. }
  23554. return renderTarget;
  23555. }
  23556. updateBefore( frame ) {
  23557. if ( this.bounces === false && _inReflector ) return false;
  23558. _inReflector = true;
  23559. const { scene, camera, renderer, material } = frame;
  23560. const { target } = this;
  23561. const virtualCamera = this.getVirtualCamera( camera );
  23562. const renderTarget = this.getRenderTarget( virtualCamera );
  23563. renderer.getDrawingBufferSize( _size$2 );
  23564. this._updateResolution( renderTarget, renderer );
  23565. //
  23566. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  23567. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  23568. _rotationMatrix.extractRotation( target.matrixWorld );
  23569. _normal.set( 0, 0, 1 );
  23570. _normal.applyMatrix4( _rotationMatrix );
  23571. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  23572. // Avoid rendering when reflector is facing away unless forcing an update
  23573. const isFacingAway = _view.dot( _normal ) > 0;
  23574. let needsClear = false;
  23575. if ( isFacingAway === true && this.forceUpdate === false ) {
  23576. if ( this.hasOutput === false ) {
  23577. _inReflector = false;
  23578. return;
  23579. }
  23580. needsClear = true;
  23581. }
  23582. _view.reflect( _normal ).negate();
  23583. _view.add( _reflectorWorldPosition );
  23584. _rotationMatrix.extractRotation( camera.matrixWorld );
  23585. _lookAtPosition.set( 0, 0, -1 );
  23586. _lookAtPosition.applyMatrix4( _rotationMatrix );
  23587. _lookAtPosition.add( _cameraWorldPosition );
  23588. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  23589. _target.reflect( _normal ).negate();
  23590. _target.add( _reflectorWorldPosition );
  23591. //
  23592. virtualCamera.coordinateSystem = camera.coordinateSystem;
  23593. virtualCamera.position.copy( _view );
  23594. virtualCamera.up.set( 0, 1, 0 );
  23595. virtualCamera.up.applyMatrix4( _rotationMatrix );
  23596. virtualCamera.up.reflect( _normal );
  23597. virtualCamera.lookAt( _target );
  23598. virtualCamera.near = camera.near;
  23599. virtualCamera.far = camera.far;
  23600. virtualCamera.updateMatrixWorld();
  23601. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  23602. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  23603. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  23604. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  23605. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  23606. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  23607. const projectionMatrix = virtualCamera.projectionMatrix;
  23608. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  23609. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  23610. _q.z = -1;
  23611. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  23612. // Calculate the scaled plane vector
  23613. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  23614. const clipBias = 0;
  23615. // Replacing the third row of the projection matrix
  23616. projectionMatrix.elements[ 2 ] = clipPlane.x;
  23617. projectionMatrix.elements[ 6 ] = clipPlane.y;
  23618. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  23619. projectionMatrix.elements[ 14 ] = clipPlane.w;
  23620. //
  23621. this.textureNode.value = renderTarget.texture;
  23622. if ( this.depth === true ) {
  23623. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  23624. }
  23625. material.visible = false;
  23626. const currentRenderTarget = renderer.getRenderTarget();
  23627. const currentMRT = renderer.getMRT();
  23628. const currentAutoClear = renderer.autoClear;
  23629. renderer.setMRT( null );
  23630. renderer.setRenderTarget( renderTarget );
  23631. renderer.autoClear = true;
  23632. if ( needsClear ) {
  23633. renderer.clear();
  23634. this.hasOutput = false;
  23635. } else {
  23636. renderer.render( scene, virtualCamera );
  23637. this.hasOutput = true;
  23638. }
  23639. renderer.setMRT( currentMRT );
  23640. renderer.setRenderTarget( currentRenderTarget );
  23641. renderer.autoClear = currentAutoClear;
  23642. material.visible = true;
  23643. _inReflector = false;
  23644. this.forceUpdate = false;
  23645. }
  23646. }
  23647. /**
  23648. * TSL function for creating a reflector node.
  23649. *
  23650. * @tsl
  23651. * @function
  23652. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23653. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23654. * @param {number} [parameters.resolution=1] - The resolution scale.
  23655. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23656. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23657. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23658. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23659. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23660. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23661. * @returns {ReflectorNode}
  23662. */
  23663. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  23664. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  23665. /**
  23666. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  23667. *
  23668. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  23669. *
  23670. * @private
  23671. * @augments BufferGeometry
  23672. */
  23673. class QuadGeometry extends BufferGeometry {
  23674. /**
  23675. * Constructs a new quad geometry.
  23676. *
  23677. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  23678. */
  23679. constructor( flipY = false ) {
  23680. super();
  23681. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  23682. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  23683. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  23684. }
  23685. }
  23686. const _geometry = /*@__PURE__*/ new QuadGeometry();
  23687. /**
  23688. * This module is a helper for passes which need to render a full
  23689. * screen effect which is quite common in context of post processing.
  23690. *
  23691. * The intended usage is to reuse a single quad mesh for rendering
  23692. * subsequent passes by just reassigning the `material` reference.
  23693. *
  23694. * Note: This module can only be used with `WebGPURenderer`.
  23695. *
  23696. * @augments Mesh
  23697. */
  23698. class QuadMesh extends Mesh {
  23699. /**
  23700. * Constructs a new quad mesh.
  23701. *
  23702. * @param {?Material} [material=null] - The material to render the quad mesh with.
  23703. */
  23704. constructor( material = null ) {
  23705. super( _geometry, material );
  23706. /**
  23707. * The camera to render the quad mesh with.
  23708. *
  23709. * @type {OrthographicCamera}
  23710. * @readonly
  23711. */
  23712. this.camera = _camera;
  23713. /**
  23714. * This flag can be used for type testing.
  23715. *
  23716. * @type {boolean}
  23717. * @readonly
  23718. * @default true
  23719. */
  23720. this.isQuadMesh = true;
  23721. }
  23722. /**
  23723. * Async version of `render()`.
  23724. *
  23725. * @async
  23726. * @param {Renderer} renderer - The renderer.
  23727. * @return {Promise} A Promise that resolves when the render has been finished.
  23728. */
  23729. async renderAsync( renderer ) {
  23730. return renderer.renderAsync( this, _camera );
  23731. }
  23732. /**
  23733. * Renders the quad mesh
  23734. *
  23735. * @param {Renderer} renderer - The renderer.
  23736. */
  23737. render( renderer ) {
  23738. renderer.render( this, _camera );
  23739. }
  23740. }
  23741. const _size$1 = /*@__PURE__*/ new Vector2();
  23742. /**
  23743. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  23744. * This module is especially relevant in context of post processing where certain nodes require
  23745. * texture input for their effects. With the helper function `convertToTexture()` which is based
  23746. * on this module, the node system can automatically ensure texture input if required.
  23747. *
  23748. * @augments TextureNode
  23749. */
  23750. class RTTNode extends TextureNode {
  23751. static get type() {
  23752. return 'RTTNode';
  23753. }
  23754. /**
  23755. * Constructs a new RTT node.
  23756. *
  23757. * @param {Node} node - The node to render a texture with.
  23758. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23759. * @param {?number} [height=null] - The height of the internal render target.
  23760. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23761. */
  23762. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  23763. const renderTarget = new RenderTarget( width, height, options );
  23764. super( renderTarget.texture, uv$1() );
  23765. /**
  23766. * This flag can be used for type testing.
  23767. *
  23768. * @type {boolean}
  23769. * @readonly
  23770. * @default true
  23771. */
  23772. this.isRTTNode = true;
  23773. /**
  23774. * The node to render a texture with.
  23775. *
  23776. * @type {Node}
  23777. */
  23778. this.node = node;
  23779. /**
  23780. * The width of the internal render target.
  23781. * If not width is applied, the render target is automatically resized.
  23782. *
  23783. * @type {?number}
  23784. * @default null
  23785. */
  23786. this.width = width;
  23787. /**
  23788. * The height of the internal render target.
  23789. *
  23790. * @type {?number}
  23791. * @default null
  23792. */
  23793. this.height = height;
  23794. /**
  23795. * The pixel ratio
  23796. *
  23797. * @type {number}
  23798. * @default 1
  23799. */
  23800. this.pixelRatio = 1;
  23801. /**
  23802. * The render target
  23803. *
  23804. * @type {RenderTarget}
  23805. */
  23806. this.renderTarget = renderTarget;
  23807. /**
  23808. * Whether the texture requires an update or not.
  23809. *
  23810. * @type {boolean}
  23811. * @default true
  23812. */
  23813. this.textureNeedsUpdate = true;
  23814. /**
  23815. * Whether the texture should automatically be updated or not.
  23816. *
  23817. * @type {boolean}
  23818. * @default true
  23819. */
  23820. this.autoUpdate = true;
  23821. /**
  23822. * The node which is used with the quad mesh for RTT.
  23823. *
  23824. * @private
  23825. * @type {Node}
  23826. * @default null
  23827. */
  23828. this._rttNode = null;
  23829. /**
  23830. * The internal quad mesh for RTT.
  23831. *
  23832. * @private
  23833. * @type {QuadMesh}
  23834. */
  23835. this._quadMesh = new QuadMesh( new NodeMaterial() );
  23836. /**
  23837. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  23838. * the texture once per render in its {@link RTTNode#updateBefore} method.
  23839. *
  23840. * @type {string}
  23841. * @default 'render'
  23842. */
  23843. this.updateBeforeType = NodeUpdateType.RENDER;
  23844. }
  23845. /**
  23846. * Whether the internal render target should automatically be resized or not.
  23847. *
  23848. * @type {boolean}
  23849. * @readonly
  23850. * @default true
  23851. */
  23852. get autoResize() {
  23853. return this.width === null;
  23854. }
  23855. setup( builder ) {
  23856. this._rttNode = this.node.context( builder.getSharedContext() );
  23857. this._quadMesh.material.name = 'RTT';
  23858. this._quadMesh.material.needsUpdate = true;
  23859. return super.setup( builder );
  23860. }
  23861. /**
  23862. * Sets the size of the internal render target
  23863. *
  23864. * @param {number} width - The width to set.
  23865. * @param {number} height - The width to set.
  23866. */
  23867. setSize( width, height ) {
  23868. this.width = width;
  23869. this.height = height;
  23870. const effectiveWidth = width * this.pixelRatio;
  23871. const effectiveHeight = height * this.pixelRatio;
  23872. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23873. this.textureNeedsUpdate = true;
  23874. }
  23875. /**
  23876. * Sets the pixel ratio. This will also resize the render target.
  23877. *
  23878. * @param {number} pixelRatio - The pixel ratio to set.
  23879. */
  23880. setPixelRatio( pixelRatio ) {
  23881. this.pixelRatio = pixelRatio;
  23882. this.setSize( this.width, this.height );
  23883. }
  23884. updateBefore( { renderer } ) {
  23885. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  23886. this.textureNeedsUpdate = false;
  23887. //
  23888. if ( this.autoResize === true ) {
  23889. const pixelRatio = renderer.getPixelRatio();
  23890. const size = renderer.getSize( _size$1 );
  23891. const effectiveWidth = size.width * pixelRatio;
  23892. const effectiveHeight = size.height * pixelRatio;
  23893. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  23894. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23895. this.textureNeedsUpdate = true;
  23896. }
  23897. }
  23898. //
  23899. this._quadMesh.material.fragmentNode = this._rttNode;
  23900. //
  23901. const currentRenderTarget = renderer.getRenderTarget();
  23902. renderer.setRenderTarget( this.renderTarget );
  23903. this._quadMesh.render( renderer );
  23904. renderer.setRenderTarget( currentRenderTarget );
  23905. }
  23906. clone() {
  23907. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  23908. newNode.sampler = this.sampler;
  23909. newNode.referenceNode = this;
  23910. return newNode;
  23911. }
  23912. }
  23913. /**
  23914. * TSL function for creating a RTT node.
  23915. *
  23916. * @tsl
  23917. * @function
  23918. * @param {Node} node - The node to render a texture with.
  23919. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23920. * @param {?number} [height=null] - The height of the internal render target.
  23921. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23922. * @returns {RTTNode}
  23923. */
  23924. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  23925. /**
  23926. * TSL function for converting nodes to textures nodes.
  23927. *
  23928. * @tsl
  23929. * @function
  23930. * @param {Node} node - The node to render a texture with.
  23931. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23932. * @param {?number} [height=null] - The height of the internal render target.
  23933. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23934. * @returns {RTTNode}
  23935. */
  23936. const convertToTexture = ( node, ...params ) => {
  23937. if ( node.isSampleNode || node.isTextureNode ) return node;
  23938. if ( node.isPassNode ) return node.getTextureNode();
  23939. return rtt( node, ...params );
  23940. };
  23941. /**
  23942. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  23943. * depth value and the camera's inverse projection matrix.
  23944. *
  23945. * @tsl
  23946. * @function
  23947. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  23948. * @param {Node<float>} depth - The fragment's depth value.
  23949. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23950. * @return {Node<vec3>} The fragments position in view space.
  23951. */
  23952. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  23953. let clipSpacePosition;
  23954. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  23955. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  23956. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  23957. } else {
  23958. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  23959. }
  23960. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  23961. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  23962. } );
  23963. /**
  23964. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  23965. * and the camera's projection matrix
  23966. *
  23967. * @tsl
  23968. * @function
  23969. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  23970. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  23971. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  23972. */
  23973. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  23974. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  23975. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  23976. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  23977. } );
  23978. /**
  23979. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  23980. * target is available or if flat surface normals are required.
  23981. *
  23982. * @tsl
  23983. * @function
  23984. * @param {Node<vec2>} uv - The texture coordinate.
  23985. * @param {DepthTexture} depthTexture - The depth texture.
  23986. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23987. * @return {Node<vec3>} The computed normal vector.
  23988. */
  23989. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  23990. const size = textureSize( textureLoad( depthTexture ) );
  23991. const p = ivec2( uv.mul( size ) ).toVar();
  23992. const c0 = textureLoad( depthTexture, p ).toVar();
  23993. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  23994. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  23995. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  23996. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  23997. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  23998. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  23999. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  24000. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  24001. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  24002. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  24003. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  24004. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  24005. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  24006. 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 ) ) );
  24007. 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 ) ) );
  24008. return normalize( cross( dpdx, dpdy ) );
  24009. } );
  24010. /**
  24011. * Class representing a node that samples a value using a provided callback function.
  24012. *
  24013. * @extends Node
  24014. */
  24015. class SampleNode extends Node {
  24016. /**
  24017. * Returns the type of the node.
  24018. *
  24019. * @type {string}
  24020. * @readonly
  24021. * @static
  24022. */
  24023. static get type() {
  24024. return 'SampleNode';
  24025. }
  24026. /**
  24027. * Creates an instance of SampleNode.
  24028. *
  24029. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24030. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  24031. */
  24032. constructor( callback, uvNode = null ) {
  24033. super();
  24034. this.callback = callback;
  24035. /**
  24036. * Represents the texture coordinates.
  24037. *
  24038. * @type {?Node<vec2|vec3>}
  24039. * @default null
  24040. */
  24041. this.uvNode = uvNode;
  24042. /**
  24043. * This flag can be used for type testing.
  24044. *
  24045. * @type {boolean}
  24046. * @readonly
  24047. * @default true
  24048. */
  24049. this.isSampleNode = true;
  24050. }
  24051. /**
  24052. * Sets up the node by sampling with the default UV accessor.
  24053. *
  24054. * @returns {Node} The result of the callback function when called with the UV node.
  24055. */
  24056. setup() {
  24057. return this.sample( uv$1() );
  24058. }
  24059. /**
  24060. * Calls the callback function with the provided UV node.
  24061. *
  24062. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  24063. * @returns {Node} The result of the callback function.
  24064. */
  24065. sample( uv ) {
  24066. return this.callback( uv );
  24067. }
  24068. }
  24069. /**
  24070. * Helper function to create a SampleNode wrapped as a node object.
  24071. *
  24072. * @function
  24073. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24074. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  24075. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  24076. */
  24077. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  24078. /**
  24079. * EventNode is a node that executes a callback during specific update phases.
  24080. *
  24081. * @augments Node
  24082. */
  24083. class EventNode extends Node {
  24084. static get type() {
  24085. return 'EventNode';
  24086. }
  24087. /**
  24088. * Creates an EventNode.
  24089. *
  24090. * @param {string} eventType - The type of event
  24091. * @param {Function} callback - The callback to execute on update.
  24092. */
  24093. constructor( eventType, callback ) {
  24094. super( 'void' );
  24095. this.eventType = eventType;
  24096. this.callback = callback;
  24097. if ( eventType === EventNode.OBJECT ) {
  24098. this.updateType = NodeUpdateType.OBJECT;
  24099. } else if ( eventType === EventNode.MATERIAL ) {
  24100. this.updateType = NodeUpdateType.RENDER;
  24101. }
  24102. }
  24103. update( frame ) {
  24104. this.callback( frame );
  24105. }
  24106. }
  24107. EventNode.OBJECT = 'object';
  24108. EventNode.MATERIAL = 'material';
  24109. /**
  24110. * Helper to create an EventNode and add it to the stack.
  24111. *
  24112. * @param {string} type - The event type.
  24113. * @param {Function} callback - The callback function.
  24114. * @returns {EventNode}
  24115. */
  24116. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  24117. /**
  24118. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  24119. *
  24120. * 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.
  24121. *
  24122. * @param {Function} callback - The callback function.
  24123. * @returns {EventNode}
  24124. */
  24125. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  24126. /**
  24127. * Creates an event that triggers a function when the first object that uses the material is rendered.
  24128. *
  24129. * 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.
  24130. *
  24131. * @param {Function} callback - The callback function.
  24132. * @returns {EventNode}
  24133. */
  24134. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  24135. /**
  24136. * This special type of instanced buffer attribute is intended for compute shaders.
  24137. * In earlier three.js versions it was only possible to update attribute data
  24138. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24139. * new material system and renderer it is now possible to use compute shaders
  24140. * to compute the data for an attribute more efficiently on the GPU.
  24141. *
  24142. * The idea is to create an instance of this class and provide it as an input
  24143. * to {@link StorageBufferNode}.
  24144. *
  24145. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24146. *
  24147. * @augments InstancedBufferAttribute
  24148. */
  24149. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24150. /**
  24151. * Constructs a new storage instanced buffer attribute.
  24152. *
  24153. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24154. * The subsequent parameters are then obsolete.
  24155. * @param {number} itemSize - The item size.
  24156. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24157. */
  24158. constructor( count, itemSize, typeClass = Float32Array ) {
  24159. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24160. super( array, itemSize );
  24161. /**
  24162. * This flag can be used for type testing.
  24163. *
  24164. * @type {boolean}
  24165. * @readonly
  24166. * @default true
  24167. */
  24168. this.isStorageInstancedBufferAttribute = true;
  24169. }
  24170. }
  24171. /**
  24172. * This special type of buffer attribute is intended for compute shaders.
  24173. * In earlier three.js versions it was only possible to update attribute data
  24174. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24175. * new material system and renderer it is now possible to use compute shaders
  24176. * to compute the data for an attribute more efficiently on the GPU.
  24177. *
  24178. * The idea is to create an instance of this class and provide it as an input
  24179. * to {@link StorageBufferNode}.
  24180. *
  24181. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24182. *
  24183. * @augments BufferAttribute
  24184. */
  24185. class StorageBufferAttribute extends BufferAttribute {
  24186. /**
  24187. * Constructs a new storage buffer attribute.
  24188. *
  24189. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24190. * The subsequent parameters are then obsolete.
  24191. * @param {number} itemSize - The item size.
  24192. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24193. */
  24194. constructor( count, itemSize, typeClass = Float32Array ) {
  24195. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24196. super( array, itemSize );
  24197. /**
  24198. * This flag can be used for type testing.
  24199. *
  24200. * @type {boolean}
  24201. * @readonly
  24202. * @default true
  24203. */
  24204. this.isStorageBufferAttribute = true;
  24205. }
  24206. }
  24207. /**
  24208. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  24209. *
  24210. * @tsl
  24211. * @function
  24212. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24213. * @param {string|Struct} [type='float'] - The data type.
  24214. * @returns {StorageBufferNode}
  24215. */
  24216. const attributeArray = ( count, type = 'float' ) => {
  24217. let itemSize, typedArray;
  24218. if ( type.isStruct === true ) {
  24219. itemSize = type.layout.getLength();
  24220. typedArray = getTypedArrayFromType( 'float' );
  24221. } else {
  24222. itemSize = getLengthFromType( type );
  24223. typedArray = getTypedArrayFromType( type );
  24224. }
  24225. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  24226. const node = storage( buffer, type, count );
  24227. return node;
  24228. };
  24229. /**
  24230. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  24231. *
  24232. * @tsl
  24233. * @function
  24234. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24235. * @param {string|Struct} [type='float'] - The data type.
  24236. * @returns {StorageBufferNode}
  24237. */
  24238. const instancedArray = ( count, type = 'float' ) => {
  24239. let itemSize, typedArray;
  24240. if ( type.isStruct === true ) {
  24241. itemSize = type.layout.getLength();
  24242. typedArray = getTypedArrayFromType( 'float' );
  24243. } else {
  24244. itemSize = getLengthFromType( type );
  24245. typedArray = getTypedArrayFromType( type );
  24246. }
  24247. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  24248. const node = storage( buffer, type, count );
  24249. return node;
  24250. };
  24251. /**
  24252. * A node for representing the uv coordinates of points.
  24253. *
  24254. * Can only be used with a WebGL backend. In WebGPU, point
  24255. * primitives always have the size of one pixel and can thus
  24256. * can't be used as sprite-like objects that display textures.
  24257. *
  24258. * @augments Node
  24259. */
  24260. class PointUVNode extends Node {
  24261. static get type() {
  24262. return 'PointUVNode';
  24263. }
  24264. /**
  24265. * Constructs a new point uv node.
  24266. */
  24267. constructor() {
  24268. super( 'vec2' );
  24269. /**
  24270. * This flag can be used for type testing.
  24271. *
  24272. * @type {boolean}
  24273. * @readonly
  24274. * @default true
  24275. */
  24276. this.isPointUVNode = true;
  24277. }
  24278. generate( /*builder*/ ) {
  24279. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  24280. }
  24281. }
  24282. /**
  24283. * TSL object that represents the uv coordinates of points.
  24284. *
  24285. * @tsl
  24286. * @type {PointUVNode}
  24287. */
  24288. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  24289. const _e1 = /*@__PURE__*/ new Euler();
  24290. const _m1 = /*@__PURE__*/ new Matrix4();
  24291. /**
  24292. * This module allows access to a collection of scene properties. The following predefined TSL objects
  24293. * are available for easier use:
  24294. *
  24295. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  24296. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  24297. * - `backgroundRotation`: A node that represents the scene's background rotation.
  24298. *
  24299. * @augments Node
  24300. */
  24301. class SceneNode extends Node {
  24302. static get type() {
  24303. return 'SceneNode';
  24304. }
  24305. /**
  24306. * Constructs a new scene node.
  24307. *
  24308. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  24309. * @param {?Scene} [scene=null] - A reference to the scene.
  24310. */
  24311. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  24312. super();
  24313. /**
  24314. * The scope defines the type of scene property that is accessed.
  24315. *
  24316. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  24317. */
  24318. this.scope = scope;
  24319. /**
  24320. * A reference to the scene that is going to be accessed.
  24321. *
  24322. * @type {?Scene}
  24323. * @default null
  24324. */
  24325. this.scene = scene;
  24326. }
  24327. /**
  24328. * Depending on the scope, the method returns a different type of node that represents
  24329. * the respective scene property.
  24330. *
  24331. * @param {NodeBuilder} builder - The current node builder.
  24332. * @return {Node} The output node.
  24333. */
  24334. setup( builder ) {
  24335. const scope = this.scope;
  24336. const scene = this.scene !== null ? this.scene : builder.scene;
  24337. let output;
  24338. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  24339. output = reference( 'backgroundBlurriness', 'float', scene );
  24340. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  24341. output = reference( 'backgroundIntensity', 'float', scene );
  24342. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  24343. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24344. const background = scene.background;
  24345. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  24346. _e1.copy( scene.backgroundRotation );
  24347. // accommodate left-handed frame
  24348. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  24349. _m1.makeRotationFromEuler( _e1 );
  24350. } else {
  24351. _m1.identity();
  24352. }
  24353. return _m1;
  24354. } );
  24355. } else {
  24356. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  24357. }
  24358. return output;
  24359. }
  24360. }
  24361. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  24362. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  24363. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  24364. /**
  24365. * TSL object that represents the scene's background blurriness.
  24366. *
  24367. * @tsl
  24368. * @type {SceneNode}
  24369. */
  24370. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  24371. /**
  24372. * TSL object that represents the scene's background intensity.
  24373. *
  24374. * @tsl
  24375. * @type {SceneNode}
  24376. */
  24377. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  24378. /**
  24379. * TSL object that represents the scene's background rotation.
  24380. *
  24381. * @tsl
  24382. * @type {SceneNode}
  24383. */
  24384. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  24385. /**
  24386. * This special version of a texture node can be used to
  24387. * write data into a storage texture with a compute shader.
  24388. *
  24389. * ```js
  24390. * const storageTexture = new THREE.StorageTexture( width, height );
  24391. *
  24392. * const computeTexture = Fn( ( { storageTexture } ) => {
  24393. *
  24394. * const posX = instanceIndex.mod( width );
  24395. * const posY = instanceIndex.div( width );
  24396. * const indexUV = uvec2( posX, posY );
  24397. *
  24398. * // generate RGB values
  24399. *
  24400. * const r = 1;
  24401. * const g = 1;
  24402. * const b = 1;
  24403. *
  24404. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  24405. *
  24406. * } );
  24407. *
  24408. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  24409. * renderer.computeAsync( computeNode );
  24410. * ```
  24411. *
  24412. * This node can only be used with a WebGPU backend.
  24413. *
  24414. * @augments TextureNode
  24415. */
  24416. class StorageTextureNode extends TextureNode {
  24417. static get type() {
  24418. return 'StorageTextureNode';
  24419. }
  24420. /**
  24421. * Constructs a new storage texture node.
  24422. *
  24423. * @param {StorageTexture} value - The storage texture.
  24424. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24425. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24426. */
  24427. constructor( value, uvNode, storeNode = null ) {
  24428. super( value, uvNode );
  24429. /**
  24430. * The value node that should be stored in the texture.
  24431. *
  24432. * @type {?Node}
  24433. * @default null
  24434. */
  24435. this.storeNode = storeNode;
  24436. /**
  24437. * This flag can be used for type testing.
  24438. *
  24439. * @type {boolean}
  24440. * @readonly
  24441. * @default true
  24442. */
  24443. this.isStorageTextureNode = true;
  24444. /**
  24445. * The access type of the texture node.
  24446. *
  24447. * @type {string}
  24448. * @default 'writeOnly'
  24449. */
  24450. this.access = NodeAccess.WRITE_ONLY;
  24451. }
  24452. /**
  24453. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  24454. *
  24455. * @param {NodeBuilder} builder - The current node builder.
  24456. * @return {string} The input type.
  24457. */
  24458. getInputType( /*builder*/ ) {
  24459. return 'storageTexture';
  24460. }
  24461. setup( builder ) {
  24462. super.setup( builder );
  24463. const properties = builder.getNodeProperties( this );
  24464. properties.storeNode = this.storeNode;
  24465. return properties;
  24466. }
  24467. /**
  24468. * Defines the node access.
  24469. *
  24470. * @param {string} value - The node access.
  24471. * @return {StorageTextureNode} A reference to this node.
  24472. */
  24473. setAccess( value ) {
  24474. this.access = value;
  24475. return this;
  24476. }
  24477. /**
  24478. * Generates the code snippet of the storage node. If no `storeNode`
  24479. * is defined, the texture node is generated as normal texture.
  24480. *
  24481. * @param {NodeBuilder} builder - The current node builder.
  24482. * @param {string} output - The current output.
  24483. * @return {string} The generated code snippet.
  24484. */
  24485. generate( builder, output ) {
  24486. let snippet;
  24487. if ( this.storeNode !== null ) {
  24488. snippet = this.generateStore( builder );
  24489. } else {
  24490. snippet = super.generate( builder, output );
  24491. }
  24492. return snippet;
  24493. }
  24494. /**
  24495. * Convenience method for configuring a read/write node access.
  24496. *
  24497. * @return {StorageTextureNode} A reference to this node.
  24498. */
  24499. toReadWrite() {
  24500. return this.setAccess( NodeAccess.READ_WRITE );
  24501. }
  24502. /**
  24503. * Convenience method for configuring a read-only node access.
  24504. *
  24505. * @return {StorageTextureNode} A reference to this node.
  24506. */
  24507. toReadOnly() {
  24508. return this.setAccess( NodeAccess.READ_ONLY );
  24509. }
  24510. /**
  24511. * Convenience method for configuring a write-only node access.
  24512. *
  24513. * @return {StorageTextureNode} A reference to this node.
  24514. */
  24515. toWriteOnly() {
  24516. return this.setAccess( NodeAccess.WRITE_ONLY );
  24517. }
  24518. /**
  24519. * Generates the code snippet of the storage texture node.
  24520. *
  24521. * @param {NodeBuilder} builder - The current node builder.
  24522. */
  24523. generateStore( builder ) {
  24524. const properties = builder.getNodeProperties( this );
  24525. const { uvNode, storeNode, depthNode } = properties;
  24526. const textureProperty = super.generate( builder, 'property' );
  24527. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  24528. const storeSnippet = storeNode.build( builder, 'vec4' );
  24529. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24530. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  24531. builder.addLineFlowCode( snippet, this );
  24532. }
  24533. clone() {
  24534. const newNode = super.clone();
  24535. newNode.storeNode = this.storeNode;
  24536. return newNode;
  24537. }
  24538. }
  24539. /**
  24540. * TSL function for creating a storage texture node.
  24541. *
  24542. * @tsl
  24543. * @function
  24544. * @param {StorageTexture} value - The storage texture.
  24545. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  24546. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24547. * @returns {StorageTextureNode}
  24548. */
  24549. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  24550. /**
  24551. * TODO: Explain difference to `storageTexture()`.
  24552. *
  24553. * @tsl
  24554. * @function
  24555. * @param {StorageTexture} value - The storage texture.
  24556. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24557. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24558. * @returns {StorageTextureNode}
  24559. */
  24560. const textureStore = ( value, uvNode, storeNode ) => {
  24561. const node = storageTexture( value, uvNode, storeNode );
  24562. if ( storeNode !== null ) node.toStack();
  24563. return node;
  24564. };
  24565. const normal = Fn( ( { texture, uv } ) => {
  24566. const epsilon = 0.0001;
  24567. const ret = vec3().toVar();
  24568. If( uv.x.lessThan( epsilon ), () => {
  24569. ret.assign( vec3( 1, 0, 0 ) );
  24570. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  24571. ret.assign( vec3( 0, 1, 0 ) );
  24572. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  24573. ret.assign( vec3( 0, 0, 1 ) );
  24574. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  24575. ret.assign( vec3( -1, 0, 0 ) );
  24576. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  24577. ret.assign( vec3( 0, -1, 0 ) );
  24578. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  24579. ret.assign( vec3( 0, 0, -1 ) );
  24580. } ).Else( () => {
  24581. const step = 0.01;
  24582. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  24583. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  24584. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  24585. ret.assign( vec3( x, y, z ) );
  24586. } );
  24587. return ret.normalize();
  24588. } );
  24589. /**
  24590. * This type of uniform node represents a 3D texture.
  24591. *
  24592. * @augments TextureNode
  24593. */
  24594. class Texture3DNode extends TextureNode {
  24595. static get type() {
  24596. return 'Texture3DNode';
  24597. }
  24598. /**
  24599. * Constructs a new 3D texture node.
  24600. *
  24601. * @param {Data3DTexture} value - The 3D texture.
  24602. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24603. * @param {?Node<int>} [levelNode=null] - The level node.
  24604. */
  24605. constructor( value, uvNode = null, levelNode = null ) {
  24606. super( value, uvNode, levelNode );
  24607. /**
  24608. * This flag can be used for type testing.
  24609. *
  24610. * @type {boolean}
  24611. * @readonly
  24612. * @default true
  24613. */
  24614. this.isTexture3DNode = true;
  24615. }
  24616. /**
  24617. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  24618. *
  24619. * @param {NodeBuilder} builder - The current node builder.
  24620. * @return {string} The input type.
  24621. */
  24622. getInputType( /*builder*/ ) {
  24623. return 'texture3D';
  24624. }
  24625. /**
  24626. * Returns a default uv node which is in context of 3D textures a three-dimensional
  24627. * uv node.
  24628. *
  24629. * @return {Node<vec3>} The default uv node.
  24630. */
  24631. getDefaultUV() {
  24632. return vec3( 0.5, 0.5, 0.5 );
  24633. }
  24634. /**
  24635. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  24636. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  24637. *
  24638. * @param {boolean} value - The update toggle.
  24639. */
  24640. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  24641. /**
  24642. * Overwrites the default implementation to return the unmodified uv node.
  24643. *
  24644. * @param {NodeBuilder} builder - The current node builder.
  24645. * @param {Node} uvNode - The uv node to setup.
  24646. * @return {Node} The unmodified uv node.
  24647. */
  24648. setupUV( builder, uvNode ) {
  24649. const texture = this.value;
  24650. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  24651. if ( this.sampler ) {
  24652. uvNode = uvNode.flipY();
  24653. } else {
  24654. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24655. }
  24656. }
  24657. return uvNode;
  24658. }
  24659. /**
  24660. * Generates the uv code snippet.
  24661. *
  24662. * @param {NodeBuilder} builder - The current node builder.
  24663. * @param {Node} uvNode - The uv node to generate code for.
  24664. * @return {string} The generated code snippet.
  24665. */
  24666. generateUV( builder, uvNode ) {
  24667. return uvNode.build( builder, 'vec3' );
  24668. }
  24669. /**
  24670. * TODO.
  24671. *
  24672. * @param {Node<vec3>} uvNode - The uv node .
  24673. * @return {Node<vec3>} TODO.
  24674. */
  24675. normal( uvNode ) {
  24676. return normal( { texture: this, uv: uvNode } );
  24677. }
  24678. }
  24679. /**
  24680. * TSL function for creating a 3D texture node.
  24681. *
  24682. * @tsl
  24683. * @function
  24684. * @param {Data3DTexture} value - The 3D texture.
  24685. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24686. * @param {?Node<int>} [levelNode=null] - The level node.
  24687. * @returns {Texture3DNode}
  24688. */
  24689. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  24690. /**
  24691. * A special type of reference node that allows to link values in
  24692. * `userData` fields to node objects.
  24693. * ```js
  24694. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  24695. *
  24696. * const material = new THREE.SpriteNodeMaterial();
  24697. * material.rotationNode = userData( 'rotation', 'float' );
  24698. * ```
  24699. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  24700. * will automatically be updated when the `rotation` user data field changes.
  24701. *
  24702. * @augments ReferenceNode
  24703. */
  24704. class UserDataNode extends ReferenceNode {
  24705. static get type() {
  24706. return 'UserDataNode';
  24707. }
  24708. /**
  24709. * Constructs a new user data node.
  24710. *
  24711. * @param {string} property - The property name that should be referenced by the node.
  24712. * @param {string} inputType - The node data type of the reference.
  24713. * @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.
  24714. */
  24715. constructor( property, inputType, userData = null ) {
  24716. super( property, inputType, userData );
  24717. /**
  24718. * A reference to the `userData` object. If not provided, the `userData`
  24719. * property of the 3D object that uses the node material is evaluated.
  24720. *
  24721. * @type {?Object}
  24722. * @default null
  24723. */
  24724. this.userData = userData;
  24725. }
  24726. /**
  24727. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  24728. * `userData` field.
  24729. *
  24730. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  24731. * @return {Object} A reference to the `userData` field.
  24732. */
  24733. updateReference( state ) {
  24734. this.reference = this.userData !== null ? this.userData : state.object.userData;
  24735. return this.reference;
  24736. }
  24737. }
  24738. /**
  24739. * TSL function for creating a user data node.
  24740. *
  24741. * @tsl
  24742. * @function
  24743. * @param {string} name - The property name that should be referenced by the node.
  24744. * @param {string} inputType - The node data type of the reference.
  24745. * @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.
  24746. * @returns {UserDataNode}
  24747. */
  24748. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  24749. const _objectData = new WeakMap();
  24750. /**
  24751. * A node for representing motion or velocity vectors. Foundation
  24752. * for advanced post processing effects like motion blur or TRAA.
  24753. *
  24754. * The node keeps track of the model, view and projection matrices
  24755. * of the previous frame and uses them to compute offsets in NDC space.
  24756. * These offsets represent the final velocity.
  24757. *
  24758. * @augments TempNode
  24759. */
  24760. class VelocityNode extends TempNode {
  24761. static get type() {
  24762. return 'VelocityNode';
  24763. }
  24764. /**
  24765. * Constructs a new vertex color node.
  24766. */
  24767. constructor() {
  24768. super( 'vec2' );
  24769. /**
  24770. * The current projection matrix.
  24771. *
  24772. * @type {?Matrix4}
  24773. * @default null
  24774. */
  24775. this.projectionMatrix = null;
  24776. /**
  24777. * Overwritten since velocity nodes are updated per object.
  24778. *
  24779. * @type {string}
  24780. * @default 'object'
  24781. */
  24782. this.updateType = NodeUpdateType.OBJECT;
  24783. /**
  24784. * Overwritten since velocity nodes save data after the update.
  24785. *
  24786. * @type {string}
  24787. * @default 'object'
  24788. */
  24789. this.updateAfterType = NodeUpdateType.OBJECT;
  24790. /**
  24791. * Uniform node representing the previous model matrix in world space.
  24792. *
  24793. * @type {UniformNode<mat4>}
  24794. * @default null
  24795. */
  24796. this.previousModelWorldMatrix = uniform( new Matrix4() );
  24797. /**
  24798. * Uniform node representing the previous projection matrix.
  24799. *
  24800. * @type {UniformNode<mat4>}
  24801. * @default null
  24802. */
  24803. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  24804. /**
  24805. * Uniform node representing the previous view matrix.
  24806. *
  24807. * @type {UniformNode<mat4>}
  24808. * @default null
  24809. */
  24810. this.previousCameraViewMatrix = uniform( new Matrix4() );
  24811. }
  24812. /**
  24813. * Sets the given projection matrix.
  24814. *
  24815. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  24816. */
  24817. setProjectionMatrix( projectionMatrix ) {
  24818. this.projectionMatrix = projectionMatrix;
  24819. }
  24820. /**
  24821. * Updates velocity specific uniforms.
  24822. *
  24823. * @param {NodeFrame} frame - A reference to the current node frame.
  24824. */
  24825. update( { frameId, camera, object } ) {
  24826. const previousModelMatrix = getPreviousMatrix( object );
  24827. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  24828. //
  24829. const cameraData = getData( camera );
  24830. if ( cameraData.frameId !== frameId ) {
  24831. cameraData.frameId = frameId;
  24832. if ( cameraData.previousProjectionMatrix === undefined ) {
  24833. cameraData.previousProjectionMatrix = new Matrix4();
  24834. cameraData.previousCameraViewMatrix = new Matrix4();
  24835. cameraData.currentProjectionMatrix = new Matrix4();
  24836. cameraData.currentCameraViewMatrix = new Matrix4();
  24837. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24838. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  24839. } else {
  24840. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  24841. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  24842. }
  24843. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24844. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  24845. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  24846. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  24847. }
  24848. }
  24849. /**
  24850. * Overwritten to updated velocity specific uniforms.
  24851. *
  24852. * @param {NodeFrame} frame - A reference to the current node frame.
  24853. */
  24854. updateAfter( { object } ) {
  24855. getPreviousMatrix( object ).copy( object.matrixWorld );
  24856. }
  24857. /**
  24858. * Implements the velocity computation based on the previous and current vertex data.
  24859. *
  24860. * @param {NodeBuilder} builder - A reference to the current node builder.
  24861. * @return {Node<vec2>} The motion vector.
  24862. */
  24863. setup( /*builder*/ ) {
  24864. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  24865. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  24866. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24867. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  24868. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  24869. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  24870. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  24871. return velocity;
  24872. }
  24873. }
  24874. function getData( object ) {
  24875. let objectData = _objectData.get( object );
  24876. if ( objectData === undefined ) {
  24877. objectData = {};
  24878. _objectData.set( object, objectData );
  24879. }
  24880. return objectData;
  24881. }
  24882. function getPreviousMatrix( object, index = 0 ) {
  24883. const objectData = getData( object );
  24884. let matrix = objectData[ index ];
  24885. if ( matrix === undefined ) {
  24886. objectData[ index ] = matrix = new Matrix4();
  24887. objectData[ index ].copy( object.matrixWorld );
  24888. }
  24889. return matrix;
  24890. }
  24891. /**
  24892. * TSL object that represents the velocity of a render pass.
  24893. *
  24894. * @tsl
  24895. * @type {VelocityNode}
  24896. */
  24897. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  24898. /**
  24899. * Computes a grayscale value for the given RGB color value.
  24900. *
  24901. * @tsl
  24902. * @function
  24903. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  24904. * @return {Node<vec3>} The grayscale color.
  24905. */
  24906. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24907. return luminance( color.rgb );
  24908. } );
  24909. /**
  24910. * Super-saturates or desaturates the given RGB color.
  24911. *
  24912. * @tsl
  24913. * @function
  24914. * @param {Node<vec3>} color - The input color.
  24915. * @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.
  24916. * @return {Node<vec3>} The saturated color.
  24917. */
  24918. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24919. return adjustment.mix( luminance( color.rgb ), color.rgb );
  24920. } );
  24921. /**
  24922. * Selectively enhance the intensity of less saturated RGB colors. Can result
  24923. * in a more natural and visually appealing image with enhanced color depth
  24924. * compared to {@link ColorAdjustment#saturation}.
  24925. *
  24926. * @tsl
  24927. * @function
  24928. * @param {Node<vec3>} color - The input color.
  24929. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  24930. * @return {Node<vec3>} The updated color.
  24931. */
  24932. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24933. const average = add( color.r, color.g, color.b ).div( 3.0 );
  24934. const mx = color.r.max( color.g.max( color.b ) );
  24935. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  24936. return mix( color.rgb, mx, amt );
  24937. } );
  24938. /**
  24939. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  24940. *
  24941. * @tsl
  24942. * @function
  24943. * @param {Node<vec3>} color - The input color.
  24944. * @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.
  24945. * @return {Node<vec3>} The updated color.
  24946. */
  24947. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24948. const k = vec3( 0.57735, 0.57735, 0.57735 );
  24949. const cosAngle = adjustment.cos();
  24950. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  24951. } );
  24952. /**
  24953. * Computes the luminance for the given RGB color value.
  24954. *
  24955. * @tsl
  24956. * @function
  24957. * @param {Node<vec3>} color - The color value to compute the luminance for.
  24958. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  24959. * @return {Node<vec3>} The luminance.
  24960. */
  24961. const luminance = (
  24962. color,
  24963. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  24964. ) => dot( color, luminanceCoefficients );
  24965. /**
  24966. * Color Decision List (CDL) v1.2
  24967. *
  24968. * Compact representation of color grading information, defined by slope, offset, power, and
  24969. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  24970. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  24971. *
  24972. * @tsl
  24973. * @function
  24974. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  24975. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  24976. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  24977. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  24978. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  24979. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  24980. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  24981. *
  24982. * References:
  24983. * - ASC CDL v1.2
  24984. * - {@link https://blender.stackexchange.com/a/55239/43930}
  24985. * - {@link https://docs.acescentral.com/specifications/acescc/}
  24986. */
  24987. const cdl = /*@__PURE__*/ Fn( ( [
  24988. color,
  24989. slope = vec3( 1 ),
  24990. offset = vec3( 0 ),
  24991. power = vec3( 1 ),
  24992. saturation = float( 1 ),
  24993. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  24994. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  24995. ] ) => {
  24996. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  24997. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  24998. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  24999. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  25000. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  25001. const pv = v.pow( power ).toVar();
  25002. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  25003. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  25004. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  25005. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  25006. return vec4( v.rgb, color.a );
  25007. } );
  25008. /**
  25009. * Represents a posterize effect which reduces the number of colors
  25010. * in an image, resulting in a more blocky and stylized appearance.
  25011. *
  25012. * @augments TempNode
  25013. */
  25014. class PosterizeNode extends TempNode {
  25015. static get type() {
  25016. return 'PosterizeNode';
  25017. }
  25018. /**
  25019. * Constructs a new posterize node.
  25020. *
  25021. * @param {Node} sourceNode - The input color.
  25022. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25023. */
  25024. constructor( sourceNode, stepsNode ) {
  25025. super();
  25026. /**
  25027. * The input color.
  25028. *
  25029. * @type {Node}
  25030. */
  25031. this.sourceNode = sourceNode;
  25032. /**
  25033. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25034. *
  25035. * @type {Node}
  25036. */
  25037. this.stepsNode = stepsNode;
  25038. }
  25039. setup() {
  25040. const { sourceNode, stepsNode } = this;
  25041. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  25042. }
  25043. }
  25044. /**
  25045. * TSL function for creating a posterize node.
  25046. *
  25047. * @tsl
  25048. * @function
  25049. * @param {Node} sourceNode - The input color.
  25050. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25051. * @returns {PosterizeNode}
  25052. */
  25053. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  25054. const _size = /*@__PURE__*/ new Vector2();
  25055. /**
  25056. * Represents the texture of a pass node.
  25057. *
  25058. * @augments TextureNode
  25059. */
  25060. class PassTextureNode extends TextureNode {
  25061. static get type() {
  25062. return 'PassTextureNode';
  25063. }
  25064. /**
  25065. * Constructs a new pass texture node.
  25066. *
  25067. * @param {PassNode} passNode - The pass node.
  25068. * @param {Texture} texture - The output texture.
  25069. */
  25070. constructor( passNode, texture ) {
  25071. super( texture );
  25072. /**
  25073. * A reference to the pass node.
  25074. *
  25075. * @type {PassNode}
  25076. */
  25077. this.passNode = passNode;
  25078. this.setUpdateMatrix( false );
  25079. }
  25080. setup( builder ) {
  25081. this.passNode.build( builder );
  25082. return super.setup( builder );
  25083. }
  25084. clone() {
  25085. return new this.constructor( this.passNode, this.value );
  25086. }
  25087. }
  25088. /**
  25089. * An extension of `PassTextureNode` which allows to manage more than one
  25090. * internal texture. Relevant for the `getPreviousTexture()` related API.
  25091. *
  25092. * @augments PassTextureNode
  25093. */
  25094. class PassMultipleTextureNode extends PassTextureNode {
  25095. static get type() {
  25096. return 'PassMultipleTextureNode';
  25097. }
  25098. /**
  25099. * Constructs a new pass texture node.
  25100. *
  25101. * @param {PassNode} passNode - The pass node.
  25102. * @param {string} textureName - The output texture name.
  25103. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  25104. */
  25105. constructor( passNode, textureName, previousTexture = false ) {
  25106. // null is passed to the super call since this class does not
  25107. // use an external texture for rendering pass data into. Instead
  25108. // the texture is managed by the pass node itself
  25109. super( passNode, null );
  25110. /**
  25111. * The output texture name.
  25112. *
  25113. * @type {string}
  25114. */
  25115. this.textureName = textureName;
  25116. /**
  25117. * Whether previous frame data should be used or not.
  25118. *
  25119. * @type {boolean}
  25120. */
  25121. this.previousTexture = previousTexture;
  25122. }
  25123. /**
  25124. * Updates the texture reference of this node.
  25125. */
  25126. updateTexture() {
  25127. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  25128. }
  25129. setup( builder ) {
  25130. this.updateTexture();
  25131. return super.setup( builder );
  25132. }
  25133. clone() {
  25134. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  25135. newNode.uvNode = this.uvNode;
  25136. newNode.levelNode = this.levelNode;
  25137. newNode.biasNode = this.biasNode;
  25138. newNode.sampler = this.sampler;
  25139. newNode.depthNode = this.depthNode;
  25140. newNode.compareNode = this.compareNode;
  25141. newNode.gradNode = this.gradNode;
  25142. return newNode;
  25143. }
  25144. }
  25145. /**
  25146. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  25147. * This pass produces a render for the given scene and camera and can provide multiple outputs
  25148. * via MRT for further processing.
  25149. *
  25150. * ```js
  25151. * const postProcessing = new PostProcessing( renderer );
  25152. *
  25153. * const scenePass = pass( scene, camera );
  25154. *
  25155. * postProcessing.outputNode = scenePass;
  25156. * ```
  25157. *
  25158. * @augments TempNode
  25159. */
  25160. class PassNode extends TempNode {
  25161. static get type() {
  25162. return 'PassNode';
  25163. }
  25164. /**
  25165. * Constructs a new pass node.
  25166. *
  25167. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  25168. * @param {Scene} scene - A reference to the scene.
  25169. * @param {Camera} camera - A reference to the camera.
  25170. * @param {Object} options - Options for the internal render target.
  25171. */
  25172. constructor( scope, scene, camera, options = {} ) {
  25173. super( 'vec4' );
  25174. /**
  25175. * The scope of the pass. The scope determines whether the node outputs color or depth.
  25176. *
  25177. * @type {('color'|'depth')}
  25178. */
  25179. this.scope = scope;
  25180. /**
  25181. * A reference to the scene.
  25182. *
  25183. * @type {Scene}
  25184. */
  25185. this.scene = scene;
  25186. /**
  25187. * A reference to the camera.
  25188. *
  25189. * @type {Camera}
  25190. */
  25191. this.camera = camera;
  25192. /**
  25193. * Options for the internal render target.
  25194. *
  25195. * @type {Object}
  25196. */
  25197. this.options = options;
  25198. /**
  25199. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  25200. *
  25201. * @private
  25202. * @type {number}
  25203. * @default 1
  25204. */
  25205. this._pixelRatio = 1;
  25206. /**
  25207. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  25208. * @private
  25209. * @type {number}
  25210. * @default 1
  25211. */
  25212. this._width = 1;
  25213. /**
  25214. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  25215. * @private
  25216. * @type {number}
  25217. * @default 1
  25218. */
  25219. this._height = 1;
  25220. const depthTexture = new DepthTexture();
  25221. depthTexture.isRenderTargetTexture = true;
  25222. //depthTexture.type = FloatType;
  25223. depthTexture.name = 'depth';
  25224. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  25225. renderTarget.texture.name = 'output';
  25226. renderTarget.depthTexture = depthTexture;
  25227. /**
  25228. * The pass's render target.
  25229. *
  25230. * @type {RenderTarget}
  25231. */
  25232. this.renderTarget = renderTarget;
  25233. /**
  25234. * A dictionary holding the internal result textures.
  25235. *
  25236. * @private
  25237. * @type {Object<string, Texture>}
  25238. */
  25239. this._textures = {
  25240. output: renderTarget.texture,
  25241. depth: depthTexture
  25242. };
  25243. /**
  25244. * A dictionary holding the internal texture nodes.
  25245. *
  25246. * @private
  25247. * @type {Object<string, TextureNode>}
  25248. */
  25249. this._textureNodes = {};
  25250. /**
  25251. * A dictionary holding the internal depth nodes.
  25252. *
  25253. * @private
  25254. * @type {Object}
  25255. */
  25256. this._linearDepthNodes = {};
  25257. /**
  25258. * A dictionary holding the internal viewZ nodes.
  25259. *
  25260. * @private
  25261. * @type {Object}
  25262. */
  25263. this._viewZNodes = {};
  25264. /**
  25265. * A dictionary holding the texture data of the previous frame.
  25266. * Used for computing velocity/motion vectors.
  25267. *
  25268. * @private
  25269. * @type {Object<string, Texture>}
  25270. */
  25271. this._previousTextures = {};
  25272. /**
  25273. * A dictionary holding the texture nodes of the previous frame.
  25274. * Used for computing velocity/motion vectors.
  25275. *
  25276. * @private
  25277. * @type {Object<string, TextureNode>}
  25278. */
  25279. this._previousTextureNodes = {};
  25280. /**
  25281. * The `near` property of the camera as a uniform.
  25282. *
  25283. * @private
  25284. * @type {UniformNode}
  25285. */
  25286. this._cameraNear = uniform( 0 );
  25287. /**
  25288. * The `far` property of the camera as a uniform.
  25289. *
  25290. * @private
  25291. * @type {UniformNode}
  25292. */
  25293. this._cameraFar = uniform( 0 );
  25294. /**
  25295. * A MRT node configuring the MRT settings.
  25296. *
  25297. * @private
  25298. * @type {?MRTNode}
  25299. * @default null
  25300. */
  25301. this._mrt = null;
  25302. /**
  25303. * Layer object for configuring the camera that is used
  25304. * to produce the pass.
  25305. *
  25306. * @private
  25307. * @type {?Layers}
  25308. * @default null
  25309. */
  25310. this._layers = null;
  25311. /**
  25312. * Scales the resolution of the internal render target.
  25313. *
  25314. * @private
  25315. * @type {number}
  25316. * @default 1
  25317. */
  25318. this._resolution = 1;
  25319. /**
  25320. * Custom viewport definition.
  25321. *
  25322. * @private
  25323. * @type {?Vector4}
  25324. * @default null
  25325. */
  25326. this._viewport = null;
  25327. /**
  25328. * Custom scissor definition.
  25329. *
  25330. * @private
  25331. * @type {?Vector4}
  25332. * @default null
  25333. */
  25334. this._scissor = null;
  25335. /**
  25336. * This flag can be used for type testing.
  25337. *
  25338. * @type {boolean}
  25339. * @readonly
  25340. * @default true
  25341. */
  25342. this.isPassNode = true;
  25343. /**
  25344. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  25345. * scene once per frame in its {@link PassNode#updateBefore} method.
  25346. *
  25347. * @type {string}
  25348. * @default 'frame'
  25349. */
  25350. this.updateBeforeType = NodeUpdateType.FRAME;
  25351. /**
  25352. * This flag is used for global cache.
  25353. *
  25354. * @type {boolean}
  25355. * @default true
  25356. */
  25357. this.global = true;
  25358. }
  25359. /**
  25360. * Sets the resolution for the pass.
  25361. * The resolution is a factor that is multiplied with the renderer's width and height.
  25362. *
  25363. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  25364. * @return {PassNode} A reference to this pass.
  25365. */
  25366. setResolution( resolution ) {
  25367. this._resolution = resolution;
  25368. return this;
  25369. }
  25370. /**
  25371. * Gets the current resolution of the pass.
  25372. *
  25373. * @return {number} The current resolution. A value of `1` means full resolution.
  25374. */
  25375. getResolution() {
  25376. return this._resolution;
  25377. }
  25378. /**
  25379. * Sets the layer configuration that should be used when rendering the pass.
  25380. *
  25381. * @param {Layers} layers - The layers object to set.
  25382. * @return {PassNode} A reference to this pass.
  25383. */
  25384. setLayers( layers ) {
  25385. this._layers = layers;
  25386. return this;
  25387. }
  25388. /**
  25389. * Gets the current layer configuration of the pass.
  25390. *
  25391. * @return {?Layers} .
  25392. */
  25393. getLayers() {
  25394. return this._layers;
  25395. }
  25396. /**
  25397. * Sets the given MRT node to setup MRT for this pass.
  25398. *
  25399. * @param {MRTNode} mrt - The MRT object.
  25400. * @return {PassNode} A reference to this pass.
  25401. */
  25402. setMRT( mrt ) {
  25403. this._mrt = mrt;
  25404. return this;
  25405. }
  25406. /**
  25407. * Returns the current MRT node.
  25408. *
  25409. * @return {MRTNode} The current MRT node.
  25410. */
  25411. getMRT() {
  25412. return this._mrt;
  25413. }
  25414. /**
  25415. * Returns the texture for the given output name.
  25416. *
  25417. * @param {string} name - The output name to get the texture for.
  25418. * @return {Texture} The texture.
  25419. */
  25420. getTexture( name ) {
  25421. let texture = this._textures[ name ];
  25422. if ( texture === undefined ) {
  25423. const refTexture = this.renderTarget.texture;
  25424. texture = refTexture.clone();
  25425. texture.name = name;
  25426. this._textures[ name ] = texture;
  25427. this.renderTarget.textures.push( texture );
  25428. }
  25429. return texture;
  25430. }
  25431. /**
  25432. * Returns the texture holding the data of the previous frame for the given output name.
  25433. *
  25434. * @param {string} name - The output name to get the texture for.
  25435. * @return {Texture} The texture holding the data of the previous frame.
  25436. */
  25437. getPreviousTexture( name ) {
  25438. let texture = this._previousTextures[ name ];
  25439. if ( texture === undefined ) {
  25440. texture = this.getTexture( name ).clone();
  25441. this._previousTextures[ name ] = texture;
  25442. }
  25443. return texture;
  25444. }
  25445. /**
  25446. * Switches current and previous textures for the given output name.
  25447. *
  25448. * @param {string} name - The output name.
  25449. */
  25450. toggleTexture( name ) {
  25451. const prevTexture = this._previousTextures[ name ];
  25452. if ( prevTexture !== undefined ) {
  25453. const texture = this._textures[ name ];
  25454. const index = this.renderTarget.textures.indexOf( texture );
  25455. this.renderTarget.textures[ index ] = prevTexture;
  25456. this._textures[ name ] = prevTexture;
  25457. this._previousTextures[ name ] = texture;
  25458. this._textureNodes[ name ].updateTexture();
  25459. this._previousTextureNodes[ name ].updateTexture();
  25460. }
  25461. }
  25462. /**
  25463. * Returns the texture node for the given output name.
  25464. *
  25465. * @param {string} [name='output'] - The output name to get the texture node for.
  25466. * @return {TextureNode} The texture node.
  25467. */
  25468. getTextureNode( name = 'output' ) {
  25469. let textureNode = this._textureNodes[ name ];
  25470. if ( textureNode === undefined ) {
  25471. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  25472. textureNode.updateTexture();
  25473. this._textureNodes[ name ] = textureNode;
  25474. }
  25475. return textureNode;
  25476. }
  25477. /**
  25478. * Returns the previous texture node for the given output name.
  25479. *
  25480. * @param {string} [name='output'] - The output name to get the previous texture node for.
  25481. * @return {TextureNode} The previous texture node.
  25482. */
  25483. getPreviousTextureNode( name = 'output' ) {
  25484. let textureNode = this._previousTextureNodes[ name ];
  25485. if ( textureNode === undefined ) {
  25486. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  25487. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  25488. textureNode.updateTexture();
  25489. this._previousTextureNodes[ name ] = textureNode;
  25490. }
  25491. return textureNode;
  25492. }
  25493. /**
  25494. * Returns a viewZ node of this pass.
  25495. *
  25496. * @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.
  25497. * @return {Node} The viewZ node.
  25498. */
  25499. getViewZNode( name = 'depth' ) {
  25500. let viewZNode = this._viewZNodes[ name ];
  25501. if ( viewZNode === undefined ) {
  25502. const cameraNear = this._cameraNear;
  25503. const cameraFar = this._cameraFar;
  25504. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  25505. }
  25506. return viewZNode;
  25507. }
  25508. /**
  25509. * Returns a linear depth node of this pass.
  25510. *
  25511. * @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.
  25512. * @return {Node} The linear depth node.
  25513. */
  25514. getLinearDepthNode( name = 'depth' ) {
  25515. let linearDepthNode = this._linearDepthNodes[ name ];
  25516. if ( linearDepthNode === undefined ) {
  25517. const cameraNear = this._cameraNear;
  25518. const cameraFar = this._cameraFar;
  25519. const viewZNode = this.getViewZNode( name );
  25520. // TODO: just if ( builder.camera.isPerspectiveCamera )
  25521. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  25522. }
  25523. return linearDepthNode;
  25524. }
  25525. /**
  25526. * Precompiles the pass.
  25527. *
  25528. * Note that this method must be called after the pass configuartion is complete.
  25529. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  25530. *
  25531. * @async
  25532. * @param {Renderer} renderer - The renderer.
  25533. * @return {Promise} A Promise that resolves when the compile has been finished.
  25534. * @see {@link Renderer#compileAsync}
  25535. */
  25536. async compileAsync( renderer ) {
  25537. const currentRenderTarget = renderer.getRenderTarget();
  25538. const currentMRT = renderer.getMRT();
  25539. renderer.setRenderTarget( this.renderTarget );
  25540. renderer.setMRT( this._mrt );
  25541. await renderer.compileAsync( this.scene, this.camera );
  25542. renderer.setRenderTarget( currentRenderTarget );
  25543. renderer.setMRT( currentMRT );
  25544. }
  25545. setup( { renderer } ) {
  25546. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  25547. this.renderTarget.texture.type = renderer.getColorBufferType();
  25548. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  25549. }
  25550. updateBefore( frame ) {
  25551. const { renderer } = frame;
  25552. const { scene } = this;
  25553. let camera;
  25554. let pixelRatio;
  25555. const outputRenderTarget = renderer.getOutputRenderTarget();
  25556. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  25557. pixelRatio = 1;
  25558. camera = renderer.xr.getCamera();
  25559. renderer.xr.updateCamera( camera );
  25560. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  25561. } else {
  25562. camera = this.camera;
  25563. pixelRatio = renderer.getPixelRatio();
  25564. renderer.getSize( _size );
  25565. }
  25566. this._pixelRatio = pixelRatio;
  25567. this.setSize( _size.width, _size.height );
  25568. const currentRenderTarget = renderer.getRenderTarget();
  25569. const currentMRT = renderer.getMRT();
  25570. const currentMask = camera.layers.mask;
  25571. this._cameraNear.value = camera.near;
  25572. this._cameraFar.value = camera.far;
  25573. if ( this._layers !== null ) {
  25574. camera.layers.mask = this._layers.mask;
  25575. }
  25576. for ( const name in this._previousTextures ) {
  25577. this.toggleTexture( name );
  25578. }
  25579. renderer.setRenderTarget( this.renderTarget );
  25580. renderer.setMRT( this._mrt );
  25581. renderer.render( scene, camera );
  25582. renderer.setRenderTarget( currentRenderTarget );
  25583. renderer.setMRT( currentMRT );
  25584. camera.layers.mask = currentMask;
  25585. }
  25586. /**
  25587. * Sets the size of the pass's render target. Honors the pixel ratio.
  25588. *
  25589. * @param {number} width - The width to set.
  25590. * @param {number} height - The height to set.
  25591. */
  25592. setSize( width, height ) {
  25593. this._width = width;
  25594. this._height = height;
  25595. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  25596. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  25597. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25598. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  25599. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  25600. }
  25601. /**
  25602. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  25603. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25604. * with `null` as the single argument.
  25605. *
  25606. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  25607. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  25608. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  25609. * @param {number} width - The width of the scissor box in logical pixel unit.
  25610. * @param {number} height - The height of the scissor box in logical pixel unit.
  25611. */
  25612. setScissor( x, y, width, height ) {
  25613. if ( x === null ) {
  25614. this._scissor = null;
  25615. } else {
  25616. if ( this._scissor === null ) this._scissor = new Vector4();
  25617. if ( x.isVector4 ) {
  25618. this._scissor.copy( x );
  25619. } else {
  25620. this._scissor.set( x, y, width, height );
  25621. }
  25622. this._scissor.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25623. }
  25624. }
  25625. /**
  25626. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  25627. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25628. * with `null` as the single argument.
  25629. *
  25630. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25631. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25632. * @param {number} width - The width of the viewport in logical pixel unit.
  25633. * @param {number} height - The height of the viewport in logical pixel unit.
  25634. */
  25635. setViewport( x, y, width, height ) {
  25636. if ( x === null ) {
  25637. this._viewport = null;
  25638. } else {
  25639. if ( this._viewport === null ) this._viewport = new Vector4();
  25640. if ( x.isVector4 ) {
  25641. this._viewport.copy( x );
  25642. } else {
  25643. this._viewport.set( x, y, width, height );
  25644. }
  25645. this._viewport.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25646. }
  25647. }
  25648. /**
  25649. * Sets the pixel ratio the pass's render target and updates the size.
  25650. *
  25651. * @param {number} pixelRatio - The pixel ratio to set.
  25652. */
  25653. setPixelRatio( pixelRatio ) {
  25654. this._pixelRatio = pixelRatio;
  25655. this.setSize( this._width, this._height );
  25656. }
  25657. /**
  25658. * Frees internal resources. Should be called when the node is no longer in use.
  25659. */
  25660. dispose() {
  25661. this.renderTarget.dispose();
  25662. }
  25663. }
  25664. /**
  25665. * @static
  25666. * @type {'color'}
  25667. * @default 'color'
  25668. */
  25669. PassNode.COLOR = 'color';
  25670. /**
  25671. * @static
  25672. * @type {'depth'}
  25673. * @default 'depth'
  25674. */
  25675. PassNode.DEPTH = 'depth';
  25676. /**
  25677. * TSL function for creating a pass node.
  25678. *
  25679. * @tsl
  25680. * @function
  25681. * @param {Scene} scene - A reference to the scene.
  25682. * @param {Camera} camera - A reference to the camera.
  25683. * @param {Object} options - Options for the internal render target.
  25684. * @returns {PassNode}
  25685. */
  25686. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  25687. /**
  25688. * TSL function for creating a pass texture node.
  25689. *
  25690. * @tsl
  25691. * @function
  25692. * @param {PassNode} pass - The pass node.
  25693. * @param {Texture} texture - The output texture.
  25694. * @returns {PassTextureNode}
  25695. */
  25696. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  25697. /**
  25698. * TSL function for creating a depth pass node.
  25699. *
  25700. * @tsl
  25701. * @function
  25702. * @param {Scene} scene - A reference to the scene.
  25703. * @param {Camera} camera - A reference to the camera.
  25704. * @param {Object} options - Options for the internal render target.
  25705. * @returns {PassNode}
  25706. */
  25707. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  25708. /**
  25709. * Represents a render pass for producing a toon outline effect on compatible objects.
  25710. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  25711. * will receive the outline.
  25712. *
  25713. * ```js
  25714. * const postProcessing = new PostProcessing( renderer );
  25715. *
  25716. * const scenePass = toonOutlinePass( scene, camera );
  25717. *
  25718. * postProcessing.outputNode = scenePass;
  25719. * ```
  25720. * @augments PassNode
  25721. */
  25722. class ToonOutlinePassNode extends PassNode {
  25723. static get type() {
  25724. return 'ToonOutlinePassNode';
  25725. }
  25726. /**
  25727. * Constructs a new outline pass node.
  25728. *
  25729. * @param {Scene} scene - A reference to the scene.
  25730. * @param {Camera} camera - A reference to the camera.
  25731. * @param {Node} colorNode - Defines the outline's color.
  25732. * @param {Node} thicknessNode - Defines the outline's thickness.
  25733. * @param {Node} alphaNode - Defines the outline's alpha.
  25734. */
  25735. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  25736. super( PassNode.COLOR, scene, camera );
  25737. /**
  25738. * Defines the outline's color.
  25739. *
  25740. * @type {Node}
  25741. */
  25742. this.colorNode = colorNode;
  25743. /**
  25744. * Defines the outline's thickness.
  25745. *
  25746. * @type {Node}
  25747. */
  25748. this.thicknessNode = thicknessNode;
  25749. /**
  25750. * Defines the outline's alpha.
  25751. *
  25752. * @type {Node}
  25753. */
  25754. this.alphaNode = alphaNode;
  25755. /**
  25756. * An internal material cache.
  25757. *
  25758. * @private
  25759. * @type {WeakMap<Material, NodeMaterial>}
  25760. */
  25761. this._materialCache = new WeakMap();
  25762. }
  25763. updateBefore( frame ) {
  25764. const { renderer } = frame;
  25765. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25766. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  25767. // only render outline for supported materials
  25768. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  25769. if ( material.wireframe === false ) {
  25770. const outlineMaterial = this._getOutlineMaterial( material );
  25771. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  25772. }
  25773. }
  25774. // default
  25775. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  25776. } );
  25777. super.updateBefore( frame );
  25778. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25779. }
  25780. /**
  25781. * Creates the material used for outline rendering.
  25782. *
  25783. * @private
  25784. * @return {NodeMaterial} The outline material.
  25785. */
  25786. _createMaterial() {
  25787. const material = new NodeMaterial();
  25788. material.isMeshToonOutlineMaterial = true;
  25789. material.name = 'Toon_Outline';
  25790. material.side = BackSide;
  25791. // vertex node
  25792. const outlineNormal = normalLocal.negate();
  25793. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  25794. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  25795. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  25796. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  25797. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  25798. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  25799. // color node
  25800. material.colorNode = vec4( this.colorNode, this.alphaNode );
  25801. return material;
  25802. }
  25803. /**
  25804. * For the given toon material, this method returns a corresponding
  25805. * outline material.
  25806. *
  25807. * @private
  25808. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  25809. * @return {NodeMaterial} The outline material.
  25810. */
  25811. _getOutlineMaterial( originalMaterial ) {
  25812. let outlineMaterial = this._materialCache.get( originalMaterial );
  25813. if ( outlineMaterial === undefined ) {
  25814. outlineMaterial = this._createMaterial();
  25815. this._materialCache.set( originalMaterial, outlineMaterial );
  25816. }
  25817. return outlineMaterial;
  25818. }
  25819. }
  25820. /**
  25821. * TSL function for creating a toon outline pass node.
  25822. *
  25823. * @tsl
  25824. * @function
  25825. * @param {Scene} scene - A reference to the scene.
  25826. * @param {Camera} camera - A reference to the camera.
  25827. * @param {Color} color - Defines the outline's color.
  25828. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  25829. * @param {number} [alpha=1] - Defines the outline's alpha.
  25830. * @returns {ToonOutlinePassNode}
  25831. */
  25832. 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 ) ) );
  25833. /**
  25834. * Linear tone mapping, exposure only.
  25835. *
  25836. * @tsl
  25837. * @function
  25838. * @param {Node<vec3>} color - The color that should be tone mapped.
  25839. * @param {Node<float>} exposure - The exposure.
  25840. * @return {Node<vec3>} The tone mapped color.
  25841. */
  25842. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25843. return color.mul( exposure ).clamp();
  25844. } ).setLayout( {
  25845. name: 'linearToneMapping',
  25846. type: 'vec3',
  25847. inputs: [
  25848. { name: 'color', type: 'vec3' },
  25849. { name: 'exposure', type: 'float' }
  25850. ]
  25851. } );
  25852. /**
  25853. * Reinhard tone mapping.
  25854. *
  25855. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  25856. *
  25857. * @tsl
  25858. * @function
  25859. * @param {Node<vec3>} color - The color that should be tone mapped.
  25860. * @param {Node<float>} exposure - The exposure.
  25861. * @return {Node<vec3>} The tone mapped color.
  25862. */
  25863. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25864. color = color.mul( exposure );
  25865. return color.div( color.add( 1.0 ) ).clamp();
  25866. } ).setLayout( {
  25867. name: 'reinhardToneMapping',
  25868. type: 'vec3',
  25869. inputs: [
  25870. { name: 'color', type: 'vec3' },
  25871. { name: 'exposure', type: 'float' }
  25872. ]
  25873. } );
  25874. /**
  25875. * Cineon tone mapping.
  25876. *
  25877. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  25878. *
  25879. * @tsl
  25880. * @function
  25881. * @param {Node<vec3>} color - The color that should be tone mapped.
  25882. * @param {Node<float>} exposure - The exposure.
  25883. * @return {Node<vec3>} The tone mapped color.
  25884. */
  25885. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25886. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  25887. color = color.mul( exposure );
  25888. color = color.sub( 0.004 ).max( 0.0 );
  25889. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  25890. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  25891. return a.div( b ).pow( 2.2 );
  25892. } ).setLayout( {
  25893. name: 'cineonToneMapping',
  25894. type: 'vec3',
  25895. inputs: [
  25896. { name: 'color', type: 'vec3' },
  25897. { name: 'exposure', type: 'float' }
  25898. ]
  25899. } );
  25900. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  25901. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25902. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  25903. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  25904. return a.div( b );
  25905. } );
  25906. /**
  25907. * ACESFilmic tone mapping.
  25908. *
  25909. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  25910. *
  25911. * @tsl
  25912. * @function
  25913. * @param {Node<vec3>} color - The color that should be tone mapped.
  25914. * @param {Node<float>} exposure - The exposure.
  25915. * @return {Node<vec3>} The tone mapped color.
  25916. */
  25917. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25918. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  25919. const ACESInputMat = mat3(
  25920. 0.59719, 0.35458, 0.04823,
  25921. 0.07600, 0.90834, 0.01566,
  25922. 0.02840, 0.13383, 0.83777
  25923. );
  25924. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  25925. const ACESOutputMat = mat3(
  25926. 1.60475, -0.53108, -0.07367,
  25927. -0.10208, 1.10813, -605e-5,
  25928. -327e-5, -0.07276, 1.07602
  25929. );
  25930. color = color.mul( exposure ).div( 0.6 );
  25931. color = ACESInputMat.mul( color );
  25932. // Apply RRT and ODT
  25933. color = RRTAndODTFit( color );
  25934. color = ACESOutputMat.mul( color );
  25935. // Clamp to [0, 1]
  25936. return color.clamp();
  25937. } ).setLayout( {
  25938. name: 'acesFilmicToneMapping',
  25939. type: 'vec3',
  25940. inputs: [
  25941. { name: 'color', type: 'vec3' },
  25942. { name: 'exposure', type: 'float' }
  25943. ]
  25944. } );
  25945. 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 ) );
  25946. 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 ) );
  25947. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25948. const x = vec3( x_immutable ).toVar();
  25949. const x2 = vec3( x.mul( x ) ).toVar();
  25950. const x4 = vec3( x2.mul( x2 ) ).toVar();
  25951. 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 ) ) ) );
  25952. } );
  25953. /**
  25954. * AgX tone mapping.
  25955. *
  25956. * @tsl
  25957. * @function
  25958. * @param {Node<vec3>} color - The color that should be tone mapped.
  25959. * @param {Node<float>} exposure - The exposure.
  25960. * @return {Node<vec3>} The tone mapped color.
  25961. */
  25962. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25963. const colortone = vec3( color ).toVar();
  25964. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  25965. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  25966. const AgxMinEv = float( -12.47393 );
  25967. const AgxMaxEv = float( 4.026069 );
  25968. colortone.mulAssign( exposure );
  25969. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  25970. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  25971. colortone.assign( max$1( colortone, 1e-10 ) );
  25972. colortone.assign( log2( colortone ) );
  25973. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  25974. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25975. colortone.assign( agxDefaultContrastApprox( colortone ) );
  25976. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  25977. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  25978. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  25979. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25980. return colortone;
  25981. } ).setLayout( {
  25982. name: 'agxToneMapping',
  25983. type: 'vec3',
  25984. inputs: [
  25985. { name: 'color', type: 'vec3' },
  25986. { name: 'exposure', type: 'float' }
  25987. ]
  25988. } );
  25989. /**
  25990. * Neutral tone mapping.
  25991. *
  25992. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  25993. *
  25994. * @tsl
  25995. * @function
  25996. * @param {Node<vec3>} color - The color that should be tone mapped.
  25997. * @param {Node<float>} exposure - The exposure.
  25998. * @return {Node<vec3>} The tone mapped color.
  25999. */
  26000. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26001. const StartCompression = float( 0.8 - 0.04 );
  26002. const Desaturation = float( 0.15 );
  26003. color = color.mul( exposure );
  26004. const x = min$1( color.r, min$1( color.g, color.b ) );
  26005. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  26006. color.subAssign( offset );
  26007. const peak = max$1( color.r, max$1( color.g, color.b ) );
  26008. If( peak.lessThan( StartCompression ), () => {
  26009. return color;
  26010. } );
  26011. const d = sub( 1, StartCompression );
  26012. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  26013. color.mulAssign( newPeak.div( peak ) );
  26014. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  26015. return mix( color, vec3( newPeak ), g );
  26016. } ).setLayout( {
  26017. name: 'neutralToneMapping',
  26018. type: 'vec3',
  26019. inputs: [
  26020. { name: 'color', type: 'vec3' },
  26021. { name: 'exposure', type: 'float' }
  26022. ]
  26023. } );
  26024. /**
  26025. * This class represents native code sections. It is the base
  26026. * class for modules like {@link FunctionNode} which allows to implement
  26027. * functions with native shader languages.
  26028. *
  26029. * @augments Node
  26030. */
  26031. class CodeNode extends Node {
  26032. static get type() {
  26033. return 'CodeNode';
  26034. }
  26035. /**
  26036. * Constructs a new code node.
  26037. *
  26038. * @param {string} [code=''] - The native code.
  26039. * @param {Array<Node>} [includes=[]] - An array of includes.
  26040. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26041. */
  26042. constructor( code = '', includes = [], language = '' ) {
  26043. super( 'code' );
  26044. /**
  26045. * This flag can be used for type testing.
  26046. *
  26047. * @type {boolean}
  26048. * @readonly
  26049. * @default true
  26050. */
  26051. this.isCodeNode = true;
  26052. /**
  26053. * This flag is used for global cache.
  26054. *
  26055. * @type {boolean}
  26056. * @default true
  26057. */
  26058. this.global = true;
  26059. /**
  26060. * The native code.
  26061. *
  26062. * @type {string}
  26063. * @default ''
  26064. */
  26065. this.code = code;
  26066. /**
  26067. * An array of includes
  26068. *
  26069. * @type {Array<Node>}
  26070. * @default []
  26071. */
  26072. this.includes = includes;
  26073. /**
  26074. * The used language.
  26075. *
  26076. * @type {('js'|'wgsl'|'glsl')}
  26077. * @default ''
  26078. */
  26079. this.language = language;
  26080. }
  26081. /**
  26082. * Sets the includes of this code node.
  26083. *
  26084. * @param {Array<Node>} includes - The includes to set.
  26085. * @return {CodeNode} A reference to this node.
  26086. */
  26087. setIncludes( includes ) {
  26088. this.includes = includes;
  26089. return this;
  26090. }
  26091. /**
  26092. * Returns the includes of this code node.
  26093. *
  26094. * @param {NodeBuilder} builder - The current node builder.
  26095. * @return {Array<Node>} The includes.
  26096. */
  26097. getIncludes( /*builder*/ ) {
  26098. return this.includes;
  26099. }
  26100. generate( builder ) {
  26101. const includes = this.getIncludes( builder );
  26102. for ( const include of includes ) {
  26103. include.build( builder );
  26104. }
  26105. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  26106. nodeCode.code = this.code;
  26107. return nodeCode.code;
  26108. }
  26109. serialize( data ) {
  26110. super.serialize( data );
  26111. data.code = this.code;
  26112. data.language = this.language;
  26113. }
  26114. deserialize( data ) {
  26115. super.deserialize( data );
  26116. this.code = data.code;
  26117. this.language = data.language;
  26118. }
  26119. }
  26120. /**
  26121. * TSL function for creating a code node.
  26122. *
  26123. * @tsl
  26124. * @function
  26125. * @param {string} [code] - The native code.
  26126. * @param {?Array<Node>} [includes=[]] - An array of includes.
  26127. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26128. * @returns {CodeNode}
  26129. */
  26130. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  26131. /**
  26132. * TSL function for creating a JS code node.
  26133. *
  26134. * @tsl
  26135. * @function
  26136. * @param {string} src - The native code.
  26137. * @param {Array<Node>} includes - An array of includes.
  26138. * @returns {CodeNode}
  26139. */
  26140. const js = ( src, includes ) => code( src, includes, 'js' );
  26141. /**
  26142. * TSL function for creating a WGSL code node.
  26143. *
  26144. * @tsl
  26145. * @function
  26146. * @param {string} src - The native code.
  26147. * @param {Array<Node>} includes - An array of includes.
  26148. * @returns {CodeNode}
  26149. */
  26150. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  26151. /**
  26152. * TSL function for creating a GLSL code node.
  26153. *
  26154. * @tsl
  26155. * @function
  26156. * @param {string} src - The native code.
  26157. * @param {Array<Node>} includes - An array of includes.
  26158. * @returns {CodeNode}
  26159. */
  26160. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  26161. /**
  26162. * This class represents a native shader function. It can be used to implement
  26163. * certain aspects of a node material with native shader code. There are two predefined
  26164. * TSL functions for easier usage.
  26165. *
  26166. * - `wgslFn`: Creates a WGSL function node.
  26167. * - `glslFn`: Creates a GLSL function node.
  26168. *
  26169. * A basic example with one include looks like so:
  26170. *
  26171. * ```js
  26172. * const desaturateWGSLFn = wgslFn( `
  26173. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  26174. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  26175. * return vec3<f32>( dot( lum, color ) );
  26176. * }`
  26177. *);
  26178. * const someWGSLFn = wgslFn( `
  26179. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  26180. * return desaturate( color );
  26181. * }
  26182. * `, [ desaturateWGSLFn ] );
  26183. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  26184. *```
  26185. * @augments CodeNode
  26186. */
  26187. class FunctionNode extends CodeNode {
  26188. static get type() {
  26189. return 'FunctionNode';
  26190. }
  26191. /**
  26192. * Constructs a new function node.
  26193. *
  26194. * @param {string} [code=''] - The native code.
  26195. * @param {Array<Node>} [includes=[]] - An array of includes.
  26196. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26197. */
  26198. constructor( code = '', includes = [], language = '' ) {
  26199. super( code, includes, language );
  26200. }
  26201. /**
  26202. * Returns the type of this function node.
  26203. *
  26204. * @param {NodeBuilder} builder - The current node builder.
  26205. * @return {string} The type.
  26206. */
  26207. getNodeType( builder ) {
  26208. return this.getNodeFunction( builder ).type;
  26209. }
  26210. /**
  26211. * Returns the type of a member of this function node.
  26212. *
  26213. * @param {NodeBuilder} builder - The current node builder.
  26214. * @param {string} name - The name of the member.
  26215. * @return {string} The type of the member.
  26216. */
  26217. getMemberType( builder, name ) {
  26218. const type = this.getNodeType( builder );
  26219. const structType = builder.getStructTypeNode( type );
  26220. return structType.getMemberType( builder, name );
  26221. }
  26222. /**
  26223. * Returns the inputs of this function node.
  26224. *
  26225. * @param {NodeBuilder} builder - The current node builder.
  26226. * @return {Array<NodeFunctionInput>} The inputs.
  26227. */
  26228. getInputs( builder ) {
  26229. return this.getNodeFunction( builder ).inputs;
  26230. }
  26231. /**
  26232. * Returns the node function for this function node.
  26233. *
  26234. * @param {NodeBuilder} builder - The current node builder.
  26235. * @return {NodeFunction} The node function.
  26236. */
  26237. getNodeFunction( builder ) {
  26238. const nodeData = builder.getDataFromNode( this );
  26239. let nodeFunction = nodeData.nodeFunction;
  26240. if ( nodeFunction === undefined ) {
  26241. nodeFunction = builder.parser.parseFunction( this.code );
  26242. nodeData.nodeFunction = nodeFunction;
  26243. }
  26244. return nodeFunction;
  26245. }
  26246. generate( builder, output ) {
  26247. super.generate( builder );
  26248. const nodeFunction = this.getNodeFunction( builder );
  26249. const name = nodeFunction.name;
  26250. const type = nodeFunction.type;
  26251. const nodeCode = builder.getCodeFromNode( this, type );
  26252. if ( name !== '' ) {
  26253. // use a custom property name
  26254. nodeCode.name = name;
  26255. }
  26256. const propertyName = builder.getPropertyName( nodeCode );
  26257. const code = this.getNodeFunction( builder ).getCode( propertyName );
  26258. nodeCode.code = code + '\n';
  26259. if ( output === 'property' ) {
  26260. return propertyName;
  26261. } else {
  26262. return builder.format( `${ propertyName }()`, type, output );
  26263. }
  26264. }
  26265. }
  26266. const nativeFn = ( code, includes = [], language = '' ) => {
  26267. for ( let i = 0; i < includes.length; i ++ ) {
  26268. const include = includes[ i ];
  26269. // TSL Function: glslFn, wgslFn
  26270. if ( typeof include === 'function' ) {
  26271. includes[ i ] = include.functionNode;
  26272. }
  26273. }
  26274. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  26275. const fn = ( ...params ) => functionNode.call( ...params );
  26276. fn.functionNode = functionNode;
  26277. return fn;
  26278. };
  26279. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  26280. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  26281. /**
  26282. * `ScriptableNode` uses this class to manage script inputs and outputs.
  26283. *
  26284. * @augments Node
  26285. */
  26286. class ScriptableValueNode extends Node {
  26287. static get type() {
  26288. return 'ScriptableValueNode';
  26289. }
  26290. /**
  26291. * Constructs a new scriptable node.
  26292. *
  26293. * @param {any} [value=null] - The value.
  26294. */
  26295. constructor( value = null ) {
  26296. super();
  26297. /**
  26298. * A reference to the value.
  26299. *
  26300. * @private
  26301. * @default null
  26302. */
  26303. this._value = value;
  26304. /**
  26305. * Depending on the type of `_value`, this property might cache parsed data.
  26306. *
  26307. * @private
  26308. * @default null
  26309. */
  26310. this._cache = null;
  26311. /**
  26312. * If this node represents an input, this property represents the input type.
  26313. *
  26314. * @type {?string}
  26315. * @default null
  26316. */
  26317. this.inputType = null;
  26318. /**
  26319. * If this node represents an output, this property represents the output type.
  26320. *
  26321. * @type {?string}
  26322. * @default null
  26323. */
  26324. this.outputType = null;
  26325. /**
  26326. * An event dispatcher for managing events.
  26327. *
  26328. * @type {EventDispatcher}
  26329. */
  26330. this.events = new EventDispatcher();
  26331. /**
  26332. * This flag can be used for type testing.
  26333. *
  26334. * @type {boolean}
  26335. * @readonly
  26336. * @default true
  26337. */
  26338. this.isScriptableValueNode = true;
  26339. }
  26340. /**
  26341. * Whether this node represents an output or not.
  26342. *
  26343. * @type {boolean}
  26344. * @readonly
  26345. * @default true
  26346. */
  26347. get isScriptableOutputNode() {
  26348. return this.outputType !== null;
  26349. }
  26350. set value( val ) {
  26351. if ( this._value === val ) return;
  26352. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  26353. URL.revokeObjectURL( this._cache );
  26354. this._cache = null;
  26355. }
  26356. this._value = val;
  26357. this.events.dispatchEvent( { type: 'change' } );
  26358. this.refresh();
  26359. }
  26360. /**
  26361. * The node's value.
  26362. *
  26363. * @type {any}
  26364. */
  26365. get value() {
  26366. return this._value;
  26367. }
  26368. /**
  26369. * Dispatches the `refresh` event.
  26370. */
  26371. refresh() {
  26372. this.events.dispatchEvent( { type: 'refresh' } );
  26373. }
  26374. /**
  26375. * The `value` property usually represents a node or even binary data in form of array buffers.
  26376. * In this case, this method tries to return the actual value behind the complex type.
  26377. *
  26378. * @return {any} The value.
  26379. */
  26380. getValue() {
  26381. const value = this.value;
  26382. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  26383. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  26384. } else if ( value && value.value !== null && value.value !== undefined && (
  26385. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  26386. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  26387. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  26388. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  26389. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  26390. ( this.inputType === 'Color' && value.value.isColor ) ||
  26391. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  26392. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  26393. ) ) {
  26394. return value.value;
  26395. }
  26396. return this._cache || value;
  26397. }
  26398. /**
  26399. * Overwritten since the node type is inferred from the value.
  26400. *
  26401. * @param {NodeBuilder} builder - The current node builder.
  26402. * @return {string} The node type.
  26403. */
  26404. getNodeType( builder ) {
  26405. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  26406. }
  26407. setup() {
  26408. return this.value && this.value.isNode ? this.value : float();
  26409. }
  26410. serialize( data ) {
  26411. super.serialize( data );
  26412. if ( this.value !== null ) {
  26413. if ( this.inputType === 'ArrayBuffer' ) {
  26414. data.value = arrayBufferToBase64( this.value );
  26415. } else {
  26416. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  26417. }
  26418. } else {
  26419. data.value = null;
  26420. }
  26421. data.inputType = this.inputType;
  26422. data.outputType = this.outputType;
  26423. }
  26424. deserialize( data ) {
  26425. super.deserialize( data );
  26426. let value = null;
  26427. if ( data.value !== null ) {
  26428. if ( data.inputType === 'ArrayBuffer' ) {
  26429. value = base64ToArrayBuffer( data.value );
  26430. } else if ( data.inputType === 'Texture' ) {
  26431. value = data.meta.textures[ data.value ];
  26432. } else {
  26433. value = data.meta.nodes[ data.value ] || null;
  26434. }
  26435. }
  26436. this.value = value;
  26437. this.inputType = data.inputType;
  26438. this.outputType = data.outputType;
  26439. }
  26440. }
  26441. /**
  26442. * TSL function for creating a scriptable value node.
  26443. *
  26444. * @tsl
  26445. * @function
  26446. * @param {any} [value] - The value.
  26447. * @returns {ScriptableValueNode}
  26448. */
  26449. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  26450. /**
  26451. * A Map-like data structure for managing resources of scriptable nodes.
  26452. *
  26453. * @augments Map
  26454. */
  26455. class Resources extends Map {
  26456. get( key, callback = null, ...params ) {
  26457. if ( this.has( key ) ) return super.get( key );
  26458. if ( callback !== null ) {
  26459. const value = callback( ...params );
  26460. this.set( key, value );
  26461. return value;
  26462. }
  26463. }
  26464. }
  26465. class Parameters {
  26466. constructor( scriptableNode ) {
  26467. this.scriptableNode = scriptableNode;
  26468. }
  26469. get parameters() {
  26470. return this.scriptableNode.parameters;
  26471. }
  26472. get layout() {
  26473. return this.scriptableNode.getLayout();
  26474. }
  26475. getInputLayout( id ) {
  26476. return this.scriptableNode.getInputLayout( id );
  26477. }
  26478. get( name ) {
  26479. const param = this.parameters[ name ];
  26480. const value = param ? param.getValue() : null;
  26481. return value;
  26482. }
  26483. }
  26484. /**
  26485. * Defines the resources (e.g. namespaces) of scriptable nodes.
  26486. *
  26487. * @type {Resources}
  26488. */
  26489. const ScriptableNodeResources = new Resources();
  26490. /**
  26491. * This type of node allows to implement nodes with custom scripts. The script
  26492. * section is represented as an instance of `CodeNode` written with JavaScript.
  26493. * The script itself must adhere to a specific structure.
  26494. *
  26495. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  26496. * - layout: The layout object defines the script's interface (inputs and outputs).
  26497. *
  26498. * ```js
  26499. * ScriptableNodeResources.set( 'TSL', TSL );
  26500. *
  26501. * const scriptableNode = scriptable( js( `
  26502. * layout = {
  26503. * outputType: 'node',
  26504. * elements: [
  26505. * { name: 'source', inputType: 'node' },
  26506. * ]
  26507. * };
  26508. *
  26509. * const { mul, oscSine } = TSL;
  26510. *
  26511. * function main() {
  26512. * const source = parameters.get( 'source' ) || float();
  26513. * return mul( source, oscSine() ) );
  26514. * }
  26515. *
  26516. * ` ) );
  26517. *
  26518. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  26519. *
  26520. * const material = new THREE.MeshBasicNodeMaterial();
  26521. * material.colorNode = scriptableNode;
  26522. * ```
  26523. *
  26524. * @augments Node
  26525. */
  26526. class ScriptableNode extends Node {
  26527. static get type() {
  26528. return 'ScriptableNode';
  26529. }
  26530. /**
  26531. * Constructs a new scriptable node.
  26532. *
  26533. * @param {?CodeNode} [codeNode=null] - The code node.
  26534. * @param {Object} [parameters={}] - The parameters definition.
  26535. */
  26536. constructor( codeNode = null, parameters = {} ) {
  26537. super();
  26538. /**
  26539. * The code node.
  26540. *
  26541. * @type {?CodeNode}
  26542. * @default null
  26543. */
  26544. this.codeNode = codeNode;
  26545. /**
  26546. * The parameters definition.
  26547. *
  26548. * @type {Object}
  26549. * @default {}
  26550. */
  26551. this.parameters = parameters;
  26552. this._local = new Resources();
  26553. this._output = scriptableValue( null );
  26554. this._outputs = {};
  26555. this._source = this.source;
  26556. this._method = null;
  26557. this._object = null;
  26558. this._value = null;
  26559. this._needsOutputUpdate = true;
  26560. this.onRefresh = this.onRefresh.bind( this );
  26561. /**
  26562. * This flag can be used for type testing.
  26563. *
  26564. * @type {boolean}
  26565. * @readonly
  26566. * @default true
  26567. */
  26568. this.isScriptableNode = true;
  26569. }
  26570. /**
  26571. * The source code of the scriptable node.
  26572. *
  26573. * @type {string}
  26574. */
  26575. get source() {
  26576. return this.codeNode ? this.codeNode.code : '';
  26577. }
  26578. /**
  26579. * Sets the reference of a local script variable.
  26580. *
  26581. * @param {string} name - The variable name.
  26582. * @param {Object} value - The reference to set.
  26583. * @return {Resources} The resource map
  26584. */
  26585. setLocal( name, value ) {
  26586. return this._local.set( name, value );
  26587. }
  26588. /**
  26589. * Gets the value of a local script variable.
  26590. *
  26591. * @param {string} name - The variable name.
  26592. * @return {Object} The value.
  26593. */
  26594. getLocal( name ) {
  26595. return this._local.get( name );
  26596. }
  26597. /**
  26598. * Event listener for the `refresh` event.
  26599. */
  26600. onRefresh() {
  26601. this._refresh();
  26602. }
  26603. /**
  26604. * Returns an input from the layout with the given id/name.
  26605. *
  26606. * @param {string} id - The id/name of the input.
  26607. * @return {Object} The element entry.
  26608. */
  26609. getInputLayout( id ) {
  26610. for ( const element of this.getLayout() ) {
  26611. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  26612. return element;
  26613. }
  26614. }
  26615. }
  26616. /**
  26617. * Returns an output from the layout with the given id/name.
  26618. *
  26619. * @param {string} id - The id/name of the output.
  26620. * @return {Object} The element entry.
  26621. */
  26622. getOutputLayout( id ) {
  26623. for ( const element of this.getLayout() ) {
  26624. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  26625. return element;
  26626. }
  26627. }
  26628. }
  26629. /**
  26630. * Defines a script output for the given name and value.
  26631. *
  26632. * @param {string} name - The name of the output.
  26633. * @param {Node} value - The node value.
  26634. * @return {ScriptableNode} A reference to this node.
  26635. */
  26636. setOutput( name, value ) {
  26637. const outputs = this._outputs;
  26638. if ( outputs[ name ] === undefined ) {
  26639. outputs[ name ] = scriptableValue( value );
  26640. } else {
  26641. outputs[ name ].value = value;
  26642. }
  26643. return this;
  26644. }
  26645. /**
  26646. * Returns a script output for the given name.
  26647. *
  26648. * @param {string} name - The name of the output.
  26649. * @return {ScriptableValueNode} The node value.
  26650. */
  26651. getOutput( name ) {
  26652. return this._outputs[ name ];
  26653. }
  26654. /**
  26655. * Returns a parameter for the given name
  26656. *
  26657. * @param {string} name - The name of the parameter.
  26658. * @return {ScriptableValueNode} The node value.
  26659. */
  26660. getParameter( name ) {
  26661. return this.parameters[ name ];
  26662. }
  26663. /**
  26664. * Sets a value for the given parameter name.
  26665. *
  26666. * @param {string} name - The parameter name.
  26667. * @param {any} value - The parameter value.
  26668. * @return {ScriptableNode} A reference to this node.
  26669. */
  26670. setParameter( name, value ) {
  26671. const parameters = this.parameters;
  26672. if ( value && value.isScriptableNode ) {
  26673. this.deleteParameter( name );
  26674. parameters[ name ] = value;
  26675. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  26676. } else if ( value && value.isScriptableValueNode ) {
  26677. this.deleteParameter( name );
  26678. parameters[ name ] = value;
  26679. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26680. } else if ( parameters[ name ] === undefined ) {
  26681. parameters[ name ] = scriptableValue( value );
  26682. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26683. } else {
  26684. parameters[ name ].value = value;
  26685. }
  26686. return this;
  26687. }
  26688. /**
  26689. * Returns the value of this node which is the value of
  26690. * the default output.
  26691. *
  26692. * @return {Node} The value.
  26693. */
  26694. getValue() {
  26695. return this.getDefaultOutput().getValue();
  26696. }
  26697. /**
  26698. * Deletes a parameter from the script.
  26699. *
  26700. * @param {string} name - The parameter to remove.
  26701. * @return {ScriptableNode} A reference to this node.
  26702. */
  26703. deleteParameter( name ) {
  26704. let valueNode = this.parameters[ name ];
  26705. if ( valueNode ) {
  26706. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26707. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  26708. }
  26709. return this;
  26710. }
  26711. /**
  26712. * Deletes all parameters from the script.
  26713. *
  26714. * @return {ScriptableNode} A reference to this node.
  26715. */
  26716. clearParameters() {
  26717. for ( const name of Object.keys( this.parameters ) ) {
  26718. this.deleteParameter( name );
  26719. }
  26720. this.needsUpdate = true;
  26721. return this;
  26722. }
  26723. /**
  26724. * Calls a function from the script.
  26725. *
  26726. * @param {string} name - The function name.
  26727. * @param {...any} params - A list of parameters.
  26728. * @return {any} The result of the function call.
  26729. */
  26730. call( name, ...params ) {
  26731. const object = this.getObject();
  26732. const method = object[ name ];
  26733. if ( typeof method === 'function' ) {
  26734. return method( ...params );
  26735. }
  26736. }
  26737. /**
  26738. * Asynchronously calls a function from the script.
  26739. *
  26740. * @param {string} name - The function name.
  26741. * @param {...any} params - A list of parameters.
  26742. * @return {Promise<any>} The result of the function call.
  26743. */
  26744. async callAsync( name, ...params ) {
  26745. const object = this.getObject();
  26746. const method = object[ name ];
  26747. if ( typeof method === 'function' ) {
  26748. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  26749. }
  26750. }
  26751. /**
  26752. * Overwritten since the node types is inferred from the script's output.
  26753. *
  26754. * @param {NodeBuilder} builder - The current node builder
  26755. * @return {string} The node type.
  26756. */
  26757. getNodeType( builder ) {
  26758. return this.getDefaultOutputNode().getNodeType( builder );
  26759. }
  26760. /**
  26761. * Refreshes the script node.
  26762. *
  26763. * @param {?string} [output=null] - An optional output.
  26764. */
  26765. refresh( output = null ) {
  26766. if ( output !== null ) {
  26767. this.getOutput( output ).refresh();
  26768. } else {
  26769. this._refresh();
  26770. }
  26771. }
  26772. /**
  26773. * Returns an object representation of the script.
  26774. *
  26775. * @return {Object} The result object.
  26776. */
  26777. getObject() {
  26778. if ( this.needsUpdate ) this.dispose();
  26779. if ( this._object !== null ) return this._object;
  26780. //
  26781. const refresh = () => this.refresh();
  26782. const setOutput = ( id, value ) => this.setOutput( id, value );
  26783. const parameters = new Parameters( this );
  26784. const THREE = ScriptableNodeResources.get( 'THREE' );
  26785. const TSL = ScriptableNodeResources.get( 'TSL' );
  26786. const method = this.getMethod();
  26787. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  26788. this._object = method( ...params );
  26789. const layout = this._object.layout;
  26790. if ( layout ) {
  26791. if ( layout.cache === false ) {
  26792. this._local.clear();
  26793. }
  26794. // default output
  26795. this._output.outputType = layout.outputType || null;
  26796. if ( Array.isArray( layout.elements ) ) {
  26797. for ( const element of layout.elements ) {
  26798. const id = element.id || element.name;
  26799. if ( element.inputType ) {
  26800. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  26801. this.getParameter( id ).inputType = element.inputType;
  26802. }
  26803. if ( element.outputType ) {
  26804. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  26805. this.getOutput( id ).outputType = element.outputType;
  26806. }
  26807. }
  26808. }
  26809. }
  26810. return this._object;
  26811. }
  26812. deserialize( data ) {
  26813. super.deserialize( data );
  26814. for ( const name in this.parameters ) {
  26815. let valueNode = this.parameters[ name ];
  26816. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26817. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  26818. }
  26819. }
  26820. /**
  26821. * Returns the layout of the script.
  26822. *
  26823. * @return {Object} The script's layout.
  26824. */
  26825. getLayout() {
  26826. return this.getObject().layout;
  26827. }
  26828. /**
  26829. * Returns default node output of the script.
  26830. *
  26831. * @return {Node} The default node output.
  26832. */
  26833. getDefaultOutputNode() {
  26834. const output = this.getDefaultOutput().value;
  26835. if ( output && output.isNode ) {
  26836. return output;
  26837. }
  26838. return float();
  26839. }
  26840. /**
  26841. * Returns default output of the script.
  26842. *
  26843. * @return {ScriptableValueNode} The default output.
  26844. */
  26845. getDefaultOutput() {
  26846. return this._exec()._output;
  26847. }
  26848. /**
  26849. * Returns a function created from the node's script.
  26850. *
  26851. * @return {Function} The function representing the node's code.
  26852. */
  26853. getMethod() {
  26854. if ( this.needsUpdate ) this.dispose();
  26855. if ( this._method !== null ) return this._method;
  26856. //
  26857. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  26858. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  26859. const properties = interfaceProps.join( ', ' );
  26860. const declarations = 'var ' + properties + '; var output = {};\n';
  26861. const returns = '\nreturn { ...output, ' + properties + ' };';
  26862. const code = declarations + this.codeNode.code + returns;
  26863. //
  26864. this._method = new Function( ...parametersProps, code );
  26865. return this._method;
  26866. }
  26867. /**
  26868. * Frees all internal resources.
  26869. */
  26870. dispose() {
  26871. if ( this._method === null ) return;
  26872. if ( this._object && typeof this._object.dispose === 'function' ) {
  26873. this._object.dispose();
  26874. }
  26875. this._method = null;
  26876. this._object = null;
  26877. this._source = null;
  26878. this._value = null;
  26879. this._needsOutputUpdate = true;
  26880. this._output.value = null;
  26881. this._outputs = {};
  26882. }
  26883. setup() {
  26884. return this.getDefaultOutputNode();
  26885. }
  26886. getCacheKey( force ) {
  26887. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  26888. for ( const param in this.parameters ) {
  26889. values.push( this.parameters[ param ].getCacheKey( force ) );
  26890. }
  26891. return hashArray( values );
  26892. }
  26893. set needsUpdate( value ) {
  26894. if ( value === true ) this.dispose();
  26895. }
  26896. get needsUpdate() {
  26897. return this.source !== this._source;
  26898. }
  26899. /**
  26900. * Executes the `main` function of the script.
  26901. *
  26902. * @private
  26903. * @return {ScriptableNode} A reference to this node.
  26904. */
  26905. _exec() {
  26906. if ( this.codeNode === null ) return this;
  26907. if ( this._needsOutputUpdate === true ) {
  26908. this._value = this.call( 'main' );
  26909. this._needsOutputUpdate = false;
  26910. }
  26911. this._output.value = this._value;
  26912. return this;
  26913. }
  26914. /**
  26915. * Executes the refresh.
  26916. *
  26917. * @private
  26918. */
  26919. _refresh() {
  26920. this.needsUpdate = true;
  26921. this._exec();
  26922. this._output.refresh();
  26923. }
  26924. }
  26925. /**
  26926. * TSL function for creating a scriptable node.
  26927. *
  26928. * @tsl
  26929. * @function
  26930. * @param {CodeNode} [codeNode] - The code node.
  26931. * @param {?Object} [parameters={}] - The parameters definition.
  26932. * @returns {ScriptableNode}
  26933. */
  26934. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  26935. /**
  26936. * Returns a node that represents the `z` coordinate in view space
  26937. * for the current fragment. It's a different representation of the
  26938. * default depth value.
  26939. *
  26940. * This value can be part of a computation that defines how the fog
  26941. * density increases when moving away from the camera.
  26942. *
  26943. * @param {NodeBuilder} builder - The current node builder.
  26944. * @return {Node} The viewZ node.
  26945. */
  26946. function getViewZNode( builder ) {
  26947. let viewZ;
  26948. const getViewZ = builder.context.getViewZ;
  26949. if ( getViewZ !== undefined ) {
  26950. viewZ = getViewZ( this );
  26951. }
  26952. return ( viewZ || positionView.z ).negate();
  26953. }
  26954. /**
  26955. * Constructs a new range factor node.
  26956. *
  26957. * @tsl
  26958. * @function
  26959. * @param {Node} near - Defines the near value.
  26960. * @param {Node} far - Defines the far value.
  26961. */
  26962. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  26963. const viewZ = getViewZNode( builder );
  26964. return smoothstep( near, far, viewZ );
  26965. } );
  26966. /**
  26967. * Represents an exponential squared fog. This type of fog gives
  26968. * a clear view near the camera and a faster than exponentially
  26969. * densening fog farther from the camera.
  26970. *
  26971. * @tsl
  26972. * @function
  26973. * @param {Node} density - Defines the fog density.
  26974. */
  26975. const densityFogFactor = Fn( ( [ density ], builder ) => {
  26976. const viewZ = getViewZNode( builder );
  26977. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  26978. } );
  26979. /**
  26980. * This class can be used to configure a fog for the scene.
  26981. * Nodes of this type are assigned to `Scene.fogNode`.
  26982. *
  26983. * @tsl
  26984. * @function
  26985. * @param {Node} color - Defines the color of the fog.
  26986. * @param {Node} factor - Defines how the fog is factored in the scene.
  26987. */
  26988. const fog = Fn( ( [ color, factor ] ) => {
  26989. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  26990. } );
  26991. // Deprecated
  26992. /**
  26993. * @tsl
  26994. * @function
  26995. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  26996. *
  26997. * @param {Node} color
  26998. * @param {Node} near
  26999. * @param {Node} far
  27000. * @returns {Function}
  27001. */
  27002. function rangeFog( color, near, far ) { // @deprecated, r171
  27003. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  27004. return fog( color, rangeFogFactor( near, far ) );
  27005. }
  27006. /**
  27007. * @tsl
  27008. * @function
  27009. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  27010. *
  27011. * @param {Node} color
  27012. * @param {Node} density
  27013. * @returns {Function}
  27014. */
  27015. function densityFog( color, density ) { // @deprecated, r171
  27016. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  27017. return fog( color, densityFogFactor( density ) );
  27018. }
  27019. let min = null;
  27020. let max = null;
  27021. /**
  27022. * `RangeNode` generates random instanced attribute data in a defined range.
  27023. * An exemplary use case for this utility node is to generate random per-instance
  27024. * colors:
  27025. * ```js
  27026. * const material = new MeshBasicNodeMaterial();
  27027. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  27028. * const mesh = new InstancedMesh( geometry, material, count );
  27029. * ```
  27030. * @augments Node
  27031. */
  27032. class RangeNode extends Node {
  27033. static get type() {
  27034. return 'RangeNode';
  27035. }
  27036. /**
  27037. * Constructs a new range node.
  27038. *
  27039. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27040. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27041. */
  27042. constructor( minNode = float(), maxNode = float() ) {
  27043. super();
  27044. /**
  27045. * A node defining the lower bound of the range.
  27046. *
  27047. * @type {Node<any>}
  27048. * @default float()
  27049. */
  27050. this.minNode = minNode;
  27051. /**
  27052. * A node defining the upper bound of the range.
  27053. *
  27054. * @type {Node<any>}
  27055. * @default float()
  27056. */
  27057. this.maxNode = maxNode;
  27058. }
  27059. /**
  27060. * Returns the vector length which is computed based on the range definition.
  27061. *
  27062. * @param {NodeBuilder} builder - The current node builder.
  27063. * @return {number} The vector length.
  27064. */
  27065. getVectorLength( builder ) {
  27066. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  27067. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  27068. return minLength > maxLength ? minLength : maxLength;
  27069. }
  27070. /**
  27071. * This method is overwritten since the node type is inferred from range definition.
  27072. *
  27073. * @param {NodeBuilder} builder - The current node builder.
  27074. * @return {string} The node type.
  27075. */
  27076. getNodeType( builder ) {
  27077. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  27078. }
  27079. setup( builder ) {
  27080. const object = builder.object;
  27081. let output = null;
  27082. if ( object.count > 1 ) {
  27083. const minValue = this.minNode.value;
  27084. const maxValue = this.maxNode.value;
  27085. const minLength = builder.getTypeLength( getValueType( minValue ) );
  27086. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  27087. min = min || new Vector4();
  27088. max = max || new Vector4();
  27089. min.setScalar( 0 );
  27090. max.setScalar( 0 );
  27091. if ( minLength === 1 ) min.setScalar( minValue );
  27092. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  27093. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  27094. if ( maxLength === 1 ) max.setScalar( maxValue );
  27095. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  27096. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  27097. const stride = 4;
  27098. const length = stride * object.count;
  27099. const array = new Float32Array( length );
  27100. for ( let i = 0; i < length; i ++ ) {
  27101. const index = i % stride;
  27102. const minElementValue = min.getComponent( index );
  27103. const maxElementValue = max.getComponent( index );
  27104. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  27105. }
  27106. const nodeType = this.getNodeType( builder );
  27107. if ( object.count <= 4096 ) {
  27108. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  27109. } else {
  27110. // TODO: Improve anonymous buffer attribute creation removing this part
  27111. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  27112. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  27113. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  27114. }
  27115. } else {
  27116. output = float( 0 );
  27117. }
  27118. return output;
  27119. }
  27120. }
  27121. /**
  27122. * TSL function for creating a range node.
  27123. *
  27124. * @tsl
  27125. * @function
  27126. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27127. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27128. * @returns {RangeNode}
  27129. */
  27130. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  27131. /**
  27132. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  27133. * about the currently running dispatch and/or the device it is running on.
  27134. *
  27135. * This node can only be used with a WebGPU backend.
  27136. *
  27137. * @augments Node
  27138. */
  27139. class ComputeBuiltinNode extends Node {
  27140. static get type() {
  27141. return 'ComputeBuiltinNode';
  27142. }
  27143. /**
  27144. * Constructs a new compute builtin node.
  27145. *
  27146. * @param {string} builtinName - The built-in name.
  27147. * @param {string} nodeType - The node type.
  27148. */
  27149. constructor( builtinName, nodeType ) {
  27150. super( nodeType );
  27151. /**
  27152. * The built-in name.
  27153. *
  27154. * @private
  27155. * @type {string}
  27156. */
  27157. this._builtinName = builtinName;
  27158. }
  27159. /**
  27160. * This method is overwritten since hash is derived from the built-in name.
  27161. *
  27162. * @param {NodeBuilder} builder - The current node builder.
  27163. * @return {string} The hash.
  27164. */
  27165. getHash( builder ) {
  27166. return this.getBuiltinName( builder );
  27167. }
  27168. /**
  27169. * This method is overwritten since the node type is simply derived from `nodeType`..
  27170. *
  27171. * @param {NodeBuilder} builder - The current node builder.
  27172. * @return {string} The node type.
  27173. */
  27174. getNodeType( /*builder*/ ) {
  27175. return this.nodeType;
  27176. }
  27177. /**
  27178. * Sets the builtin name.
  27179. *
  27180. * @param {string} builtinName - The built-in name.
  27181. * @return {ComputeBuiltinNode} A reference to this node.
  27182. */
  27183. setBuiltinName( builtinName ) {
  27184. this._builtinName = builtinName;
  27185. return this;
  27186. }
  27187. /**
  27188. * Returns the builtin name.
  27189. *
  27190. * @param {NodeBuilder} builder - The current node builder.
  27191. * @return {string} The builtin name.
  27192. */
  27193. getBuiltinName( /*builder*/ ) {
  27194. return this._builtinName;
  27195. }
  27196. /**
  27197. * Whether the current node builder has the builtin or not.
  27198. *
  27199. * @param {NodeBuilder} builder - The current node builder.
  27200. * @return {boolean} Whether the builder has the builtin or not.
  27201. */
  27202. hasBuiltin( builder ) {
  27203. return builder.hasBuiltin( this._builtinName );
  27204. }
  27205. generate( builder, output ) {
  27206. const builtinName = this.getBuiltinName( builder );
  27207. const nodeType = this.getNodeType( builder );
  27208. if ( builder.shaderStage === 'compute' ) {
  27209. return builder.format( builtinName, nodeType, output );
  27210. } else {
  27211. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  27212. return builder.generateConst( nodeType );
  27213. }
  27214. }
  27215. serialize( data ) {
  27216. super.serialize( data );
  27217. data.global = this.global;
  27218. data._builtinName = this._builtinName;
  27219. }
  27220. deserialize( data ) {
  27221. super.deserialize( data );
  27222. this.global = data.global;
  27223. this._builtinName = data._builtinName;
  27224. }
  27225. }
  27226. /**
  27227. * TSL function for creating a compute builtin node.
  27228. *
  27229. * @tsl
  27230. * @function
  27231. * @param {string} name - The built-in name.
  27232. * @param {string} nodeType - The node type.
  27233. * @returns {ComputeBuiltinNode}
  27234. */
  27235. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  27236. /**
  27237. * Represents the number of workgroups dispatched by the compute shader.
  27238. * ```js
  27239. * // Run 512 invocations/threads with a workgroup size of 128.
  27240. * const computeFn = Fn(() => {
  27241. *
  27242. * // numWorkgroups.x = 4
  27243. * storageBuffer.element(0).assign(numWorkgroups.x)
  27244. *
  27245. * })().compute(512, [128]);
  27246. *
  27247. * // Run 512 invocations/threads with the default workgroup size of 64.
  27248. * const computeFn = Fn(() => {
  27249. *
  27250. * // numWorkgroups.x = 8
  27251. * storageBuffer.element(0).assign(numWorkgroups.x)
  27252. *
  27253. * })().compute(512);
  27254. * ```
  27255. *
  27256. * @tsl
  27257. * @type {ComputeBuiltinNode<uvec3>}
  27258. */
  27259. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  27260. /**
  27261. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  27262. * ```js
  27263. * // Execute 12 compute threads with a workgroup size of 3.
  27264. * const computeFn = Fn( () => {
  27265. *
  27266. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  27267. *
  27268. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  27269. *
  27270. * } ).Else( () => {
  27271. *
  27272. * storageBuffer.element( instanceIndex ).assign( 0 );
  27273. *
  27274. * } );
  27275. *
  27276. * } )().compute( 12, [ 3 ] );
  27277. *
  27278. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  27279. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  27280. * ```
  27281. *
  27282. * @tsl
  27283. * @type {ComputeBuiltinNode<uvec3>}
  27284. */
  27285. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  27286. /**
  27287. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  27288. *
  27289. * @tsl
  27290. * @type {ComputeBuiltinNode<uvec3>}
  27291. */
  27292. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  27293. /**
  27294. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  27295. *
  27296. * @tsl
  27297. * @type {ComputeBuiltinNode<uvec3>}
  27298. */
  27299. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  27300. /**
  27301. * A device dependent variable that exposes the size of the current invocation's subgroup.
  27302. *
  27303. * @tsl
  27304. * @type {ComputeBuiltinNode<uint>}
  27305. */
  27306. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  27307. /**
  27308. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  27309. *
  27310. * This node can only be used with a WebGPU backend.
  27311. *
  27312. * @augments Node
  27313. */
  27314. class BarrierNode extends Node {
  27315. /**
  27316. * Constructs a new barrier node.
  27317. *
  27318. * @param {string} scope - The scope defines the behavior of the node.
  27319. */
  27320. constructor( scope ) {
  27321. super();
  27322. this.scope = scope;
  27323. }
  27324. generate( builder ) {
  27325. const { scope } = this;
  27326. const { renderer } = builder;
  27327. if ( renderer.backend.isWebGLBackend === true ) {
  27328. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  27329. } else {
  27330. builder.addLineFlowCode( `${scope}Barrier()`, this );
  27331. }
  27332. }
  27333. }
  27334. /**
  27335. * TSL function for creating a barrier node.
  27336. *
  27337. * @tsl
  27338. * @function
  27339. * @param {string} scope - The scope defines the behavior of the node..
  27340. * @returns {BarrierNode}
  27341. */
  27342. const barrier = nodeProxy( BarrierNode );
  27343. /**
  27344. * TSL function for creating a workgroup barrier. All compute shader
  27345. * invocations must wait for each invocation within a workgroup to
  27346. * complete before the barrier can be surpassed.
  27347. *
  27348. * @tsl
  27349. * @function
  27350. * @returns {BarrierNode}
  27351. */
  27352. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  27353. /**
  27354. * TSL function for creating a storage barrier. All invocations must
  27355. * wait for each access to variables within the 'storage' address space
  27356. * to complete before the barrier can be passed.
  27357. *
  27358. * @tsl
  27359. * @function
  27360. * @returns {BarrierNode}
  27361. */
  27362. const storageBarrier = () => barrier( 'storage' ).toStack();
  27363. /**
  27364. * TSL function for creating a texture barrier. All invocations must
  27365. * wait for each access to variables within the 'texture' address space
  27366. * to complete before the barrier can be passed.
  27367. *
  27368. * @tsl
  27369. * @function
  27370. * @returns {BarrierNode}
  27371. */
  27372. const textureBarrier = () => barrier( 'texture' ).toStack();
  27373. /**
  27374. * Represents an element of a 'workgroup' scoped buffer.
  27375. *
  27376. * @augments ArrayElementNode
  27377. */
  27378. class WorkgroupInfoElementNode extends ArrayElementNode {
  27379. /**
  27380. * Constructs a new workgroup info element node.
  27381. *
  27382. * @param {Node} workgroupInfoNode - The workgroup info node.
  27383. * @param {Node} indexNode - The index node that defines the element access.
  27384. */
  27385. constructor( workgroupInfoNode, indexNode ) {
  27386. super( workgroupInfoNode, indexNode );
  27387. /**
  27388. * This flag can be used for type testing.
  27389. *
  27390. * @type {boolean}
  27391. * @readonly
  27392. * @default true
  27393. */
  27394. this.isWorkgroupInfoElementNode = true;
  27395. }
  27396. generate( builder, output ) {
  27397. let snippet;
  27398. const isAssignContext = builder.context.assign;
  27399. snippet = super.generate( builder );
  27400. if ( isAssignContext !== true ) {
  27401. const type = this.getNodeType( builder );
  27402. snippet = builder.format( snippet, type, output );
  27403. }
  27404. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  27405. return snippet;
  27406. }
  27407. }
  27408. /**
  27409. * A node allowing the user to create a 'workgroup' scoped buffer within the
  27410. * context of a compute shader. Typically, workgroup scoped buffers are
  27411. * created to hold data that is transferred from a global storage scope into
  27412. * a local workgroup scope. For invocations within a workgroup, data
  27413. * access speeds on 'workgroup' scoped buffers can be significantly faster
  27414. * than similar access operations on globally accessible storage buffers.
  27415. *
  27416. * This node can only be used with a WebGPU backend.
  27417. *
  27418. * @augments Node
  27419. */
  27420. class WorkgroupInfoNode extends Node {
  27421. /**
  27422. * Constructs a new buffer scoped to type scope.
  27423. *
  27424. * @param {string} scope - TODO.
  27425. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  27426. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  27427. */
  27428. constructor( scope, bufferType, bufferCount = 0 ) {
  27429. super( bufferType );
  27430. /**
  27431. * The buffer type.
  27432. *
  27433. * @type {string}
  27434. */
  27435. this.bufferType = bufferType;
  27436. /**
  27437. * The buffer count.
  27438. *
  27439. * @type {number}
  27440. * @default 0
  27441. */
  27442. this.bufferCount = bufferCount;
  27443. /**
  27444. * This flag can be used for type testing.
  27445. *
  27446. * @type {boolean}
  27447. * @readonly
  27448. * @default true
  27449. */
  27450. this.isWorkgroupInfoNode = true;
  27451. /**
  27452. * The data type of the array buffer.
  27453. *
  27454. * @type {string}
  27455. */
  27456. this.elementType = bufferType;
  27457. /**
  27458. * TODO.
  27459. *
  27460. * @type {string}
  27461. */
  27462. this.scope = scope;
  27463. /**
  27464. * The name of the workgroup scoped buffer.
  27465. *
  27466. * @type {string}
  27467. * @default ''
  27468. */
  27469. this.name = '';
  27470. }
  27471. /**
  27472. * Sets the name of this node.
  27473. *
  27474. * @param {string} name - The name to set.
  27475. * @return {WorkgroupInfoNode} A reference to this node.
  27476. */
  27477. setName( name ) {
  27478. this.name = name;
  27479. return this;
  27480. }
  27481. /**
  27482. * Sets the name/label of this node.
  27483. *
  27484. * @deprecated
  27485. * @param {string} name - The name to set.
  27486. * @return {WorkgroupInfoNode} A reference to this node.
  27487. */
  27488. label( name ) {
  27489. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  27490. return this.setName( name );
  27491. }
  27492. /**
  27493. * Sets the scope of this node.
  27494. *
  27495. * @param {string} scope - The scope to set.
  27496. * @return {WorkgroupInfoNode} A reference to this node.
  27497. */
  27498. setScope( scope ) {
  27499. this.scope = scope;
  27500. return this;
  27501. }
  27502. /**
  27503. * The data type of the array buffer.
  27504. *
  27505. * @return {string} The element type.
  27506. */
  27507. getElementType() {
  27508. return this.elementType;
  27509. }
  27510. /**
  27511. * Overwrites the default implementation since the input type
  27512. * is inferred from the scope.
  27513. *
  27514. * @param {NodeBuilder} builder - The current node builder.
  27515. * @return {string} The input type.
  27516. */
  27517. getInputType( /*builder*/ ) {
  27518. return `${this.scope}Array`;
  27519. }
  27520. /**
  27521. * This method can be used to access elements via an index node.
  27522. *
  27523. * @param {IndexNode} indexNode - indexNode.
  27524. * @return {WorkgroupInfoElementNode} A reference to an element.
  27525. */
  27526. element( indexNode ) {
  27527. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  27528. }
  27529. generate( builder ) {
  27530. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  27531. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  27532. }
  27533. }
  27534. /**
  27535. * TSL function for creating a workgroup info node.
  27536. * Creates a new 'workgroup' scoped array buffer.
  27537. *
  27538. * @tsl
  27539. * @function
  27540. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  27541. * @param {number} [count=0] - The number of elements in the buffer.
  27542. * @returns {WorkgroupInfoNode}
  27543. */
  27544. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  27545. /**
  27546. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  27547. * within a shader. In an atomic function, any modification to an atomic variable will
  27548. * occur as an indivisible step with a defined order relative to other modifications.
  27549. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  27550. * atomic operations will not interfere with each other.
  27551. *
  27552. * This node can only be used with a WebGPU backend.
  27553. *
  27554. * @augments Node
  27555. */
  27556. class AtomicFunctionNode extends Node {
  27557. static get type() {
  27558. return 'AtomicFunctionNode';
  27559. }
  27560. /**
  27561. * Constructs a new atomic function node.
  27562. *
  27563. * @param {string} method - The signature of the atomic function to construct.
  27564. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27565. * @param {Node} valueNode - The value that mutates the atomic variable.
  27566. */
  27567. constructor( method, pointerNode, valueNode ) {
  27568. super( 'uint' );
  27569. /**
  27570. * The signature of the atomic function to construct.
  27571. *
  27572. * @type {string}
  27573. */
  27574. this.method = method;
  27575. /**
  27576. * An atomic variable or element of an atomic buffer.
  27577. *
  27578. * @type {Node}
  27579. */
  27580. this.pointerNode = pointerNode;
  27581. /**
  27582. * A value that modifies the atomic variable.
  27583. *
  27584. * @type {Node}
  27585. */
  27586. this.valueNode = valueNode;
  27587. /**
  27588. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  27589. *
  27590. * @type {boolean}
  27591. * @default true
  27592. */
  27593. this.parents = true;
  27594. }
  27595. /**
  27596. * Overwrites the default implementation to return the type of
  27597. * the pointer node.
  27598. *
  27599. * @param {NodeBuilder} builder - The current node builder.
  27600. * @return {string} The input type.
  27601. */
  27602. getInputType( builder ) {
  27603. return this.pointerNode.getNodeType( builder );
  27604. }
  27605. /**
  27606. * Overwritten since the node type is inferred from the input type.
  27607. *
  27608. * @param {NodeBuilder} builder - The current node builder.
  27609. * @return {string} The node type.
  27610. */
  27611. getNodeType( builder ) {
  27612. return this.getInputType( builder );
  27613. }
  27614. generate( builder ) {
  27615. const properties = builder.getNodeProperties( this );
  27616. const parents = properties.parents;
  27617. const method = this.method;
  27618. const type = this.getNodeType( builder );
  27619. const inputType = this.getInputType( builder );
  27620. const a = this.pointerNode;
  27621. const b = this.valueNode;
  27622. const params = [];
  27623. params.push( `&${ a.build( builder, inputType ) }` );
  27624. if ( b !== null ) {
  27625. params.push( b.build( builder, inputType ) );
  27626. }
  27627. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  27628. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  27629. if ( isVoid ) {
  27630. builder.addLineFlowCode( methodSnippet, this );
  27631. } else {
  27632. if ( properties.constNode === undefined ) {
  27633. properties.constNode = expression( methodSnippet, type ).toConst();
  27634. }
  27635. return properties.constNode.build( builder );
  27636. }
  27637. }
  27638. }
  27639. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  27640. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  27641. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  27642. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  27643. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  27644. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  27645. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  27646. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  27647. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  27648. /**
  27649. * TSL function for creating an atomic function node.
  27650. *
  27651. * @tsl
  27652. * @function
  27653. * @param {string} method - The signature of the atomic function to construct.
  27654. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27655. * @param {Node} valueNode - The value that mutates the atomic variable.
  27656. * @returns {AtomicFunctionNode}
  27657. */
  27658. const atomicNode = nodeProxy( AtomicFunctionNode );
  27659. /**
  27660. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  27661. *
  27662. * @tsl
  27663. * @function
  27664. * @param {string} method - The signature of the atomic function to construct.
  27665. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27666. * @param {Node} valueNode - The value that mutates the atomic variable.
  27667. * @returns {AtomicFunctionNode}
  27668. */
  27669. const atomicFunc = ( method, pointerNode, valueNode ) => {
  27670. return atomicNode( method, pointerNode, valueNode ).toStack();
  27671. };
  27672. /**
  27673. * Loads the value stored in the atomic variable.
  27674. *
  27675. * @tsl
  27676. * @function
  27677. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27678. * @returns {AtomicFunctionNode}
  27679. */
  27680. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  27681. /**
  27682. * Stores a value in the atomic variable.
  27683. *
  27684. * @tsl
  27685. * @function
  27686. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27687. * @param {Node} valueNode - The value that mutates the atomic variable.
  27688. * @returns {AtomicFunctionNode}
  27689. */
  27690. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  27691. /**
  27692. * Increments the value stored in the atomic variable.
  27693. *
  27694. * @tsl
  27695. * @function
  27696. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27697. * @param {Node} valueNode - The value that mutates the atomic variable.
  27698. * @returns {AtomicFunctionNode}
  27699. */
  27700. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  27701. /**
  27702. * Decrements the value stored in the atomic variable.
  27703. *
  27704. * @tsl
  27705. * @function
  27706. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27707. * @param {Node} valueNode - The value that mutates the atomic variable.
  27708. * @returns {AtomicFunctionNode}
  27709. */
  27710. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  27711. /**
  27712. * Stores in an atomic variable the maximum between its current value and a parameter.
  27713. *
  27714. * @tsl
  27715. * @function
  27716. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27717. * @param {Node} valueNode - The value that mutates the atomic variable.
  27718. * @returns {AtomicFunctionNode}
  27719. */
  27720. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  27721. /**
  27722. * Stores in an atomic variable the minimum between its current value and a parameter.
  27723. *
  27724. * @tsl
  27725. * @function
  27726. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27727. * @param {Node} valueNode - The value that mutates the atomic variable.
  27728. * @returns {AtomicFunctionNode}
  27729. */
  27730. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  27731. /**
  27732. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  27733. *
  27734. * @tsl
  27735. * @function
  27736. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27737. * @param {Node} valueNode - The value that mutates the atomic variable.
  27738. * @returns {AtomicFunctionNode}
  27739. */
  27740. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  27741. /**
  27742. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  27743. *
  27744. * @tsl
  27745. * @function
  27746. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27747. * @param {Node} valueNode - The value that mutates the atomic variable.
  27748. * @returns {AtomicFunctionNode}
  27749. */
  27750. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  27751. /**
  27752. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  27753. *
  27754. * @tsl
  27755. * @function
  27756. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27757. * @param {Node} valueNode - The value that mutates the atomic variable.
  27758. * @returns {AtomicFunctionNode}
  27759. */
  27760. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  27761. /**
  27762. * This class represents a set of built in WGSL shader functions that sync
  27763. * synchronously execute an operation across a subgroup, or 'warp', of compute
  27764. * or fragment shader invocations within a workgroup. Typically, these functions
  27765. * will synchronously execute an operation using data from all active invocations
  27766. * within the subgroup, then broadcast that result to all active invocations. In
  27767. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  27768. * (DirectX/HLSL) or warp intrinsics (CUDA).
  27769. *
  27770. * @augments TempNode
  27771. */
  27772. class SubgroupFunctionNode extends TempNode {
  27773. static get type() {
  27774. return 'SubgroupFunctionNode';
  27775. }
  27776. /**
  27777. * Constructs a new function node.
  27778. *
  27779. * @param {string} method - The subgroup/wave intrinsic method to construct.
  27780. * @param {Node} [aNode=null] - The method's first argument.
  27781. * @param {Node} [bNode=null] - The method's second argument.
  27782. */
  27783. constructor( method, aNode = null, bNode = null ) {
  27784. super();
  27785. /**
  27786. * The subgroup/wave intrinsic method to construct.
  27787. *
  27788. * @type {String}
  27789. */
  27790. this.method = method;
  27791. /**
  27792. * The method's first argument.
  27793. *
  27794. * @type {Node}
  27795. */
  27796. this.aNode = aNode;
  27797. /**
  27798. * The method's second argument.
  27799. *
  27800. * @type {Node}
  27801. */
  27802. this.bNode = bNode;
  27803. }
  27804. getInputType( builder ) {
  27805. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  27806. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  27807. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  27808. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  27809. if ( aLen > bLen ) {
  27810. return aType;
  27811. } else {
  27812. return bType;
  27813. }
  27814. }
  27815. getNodeType( builder ) {
  27816. const method = this.method;
  27817. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  27818. return 'bool';
  27819. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  27820. return 'uvec4';
  27821. } else {
  27822. return this.getInputType( builder );
  27823. }
  27824. }
  27825. generate( builder, output ) {
  27826. const method = this.method;
  27827. const type = this.getNodeType( builder );
  27828. const inputType = this.getInputType( builder );
  27829. const a = this.aNode;
  27830. const b = this.bNode;
  27831. const params = [];
  27832. if (
  27833. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  27834. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  27835. method === SubgroupFunctionNode.QUAD_BROADCAST
  27836. ) {
  27837. const bType = b.getNodeType( builder );
  27838. params.push(
  27839. a.build( builder, type ),
  27840. b.build( builder, bType === 'float' ? 'int' : type )
  27841. );
  27842. } else if (
  27843. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  27844. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  27845. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  27846. ) {
  27847. params.push(
  27848. a.build( builder, type ),
  27849. b.build( builder, 'uint' )
  27850. );
  27851. } else {
  27852. if ( a !== null ) params.push( a.build( builder, inputType ) );
  27853. if ( b !== null ) params.push( b.build( builder, inputType ) );
  27854. }
  27855. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  27856. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  27857. }
  27858. serialize( data ) {
  27859. super.serialize( data );
  27860. data.method = this.method;
  27861. }
  27862. deserialize( data ) {
  27863. super.deserialize( data );
  27864. this.method = data.method;
  27865. }
  27866. }
  27867. // 0 inputs
  27868. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  27869. // 1 input
  27870. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  27871. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  27872. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  27873. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  27874. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  27875. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  27876. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  27877. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  27878. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  27879. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  27880. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  27881. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  27882. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  27883. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  27884. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  27885. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  27886. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  27887. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  27888. // 2 inputs
  27889. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  27890. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  27891. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  27892. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  27893. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  27894. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  27895. /**
  27896. * Returns true if this invocation has the lowest subgroup_invocation_id
  27897. * among active invocations in the subgroup.
  27898. *
  27899. * @method
  27900. * @return {bool} The result of the computation.
  27901. */
  27902. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  27903. /**
  27904. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  27905. * is 1 if pred is true for that active invocation and 0 otherwise.
  27906. *
  27907. * @method
  27908. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  27909. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  27910. */
  27911. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  27912. /**
  27913. * A reduction that adds e among all active invocations and returns that result.
  27914. *
  27915. * @method
  27916. * @param {number} e - The value provided to the reduction by the current invocation.
  27917. * @return {number} The accumulated result of the reduction operation.
  27918. */
  27919. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  27920. /**
  27921. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  27922. *
  27923. * @method
  27924. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  27925. * @return {number} The accumulated result of the inclusive scan operation.
  27926. */
  27927. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  27928. /**
  27929. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  27930. *
  27931. * @method
  27932. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  27933. * @return {number} The accumulated result of the exclusive scan operation.
  27934. */
  27935. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  27936. /**
  27937. * A reduction that multiplies e among all active invocations and returns that result.
  27938. *
  27939. * @method
  27940. * @param {number} e - The value provided to the reduction by the current invocation.
  27941. * @return {number} The accumulated result of the reduction operation.
  27942. */
  27943. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  27944. /**
  27945. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  27946. *
  27947. * @method
  27948. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  27949. * @return {number} The accumulated result of the inclusive scan operation.
  27950. */
  27951. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  27952. /**
  27953. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  27954. *
  27955. * @method
  27956. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  27957. * @return {number} The accumulated result of the exclusive scan operation.
  27958. */
  27959. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  27960. /**
  27961. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  27962. *
  27963. * @method
  27964. * @param {number} e - The value provided to the reduction by the current invocation.
  27965. * @return {number} The result of the reduction operation.
  27966. */
  27967. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  27968. /**
  27969. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  27970. *
  27971. * @method
  27972. * @param {number} e - The value provided to the reduction by the current invocation.
  27973. * @return {number} The result of the reduction operation.
  27974. */
  27975. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  27976. /**
  27977. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  27978. *
  27979. * @method
  27980. * @param {number} e - The value provided to the reduction by the current invocation.
  27981. * @return {number} The result of the reduction operation.
  27982. */
  27983. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  27984. /**
  27985. * A reduction that performs a min of e among all active invocations and returns that result.
  27986. *
  27987. * @method
  27988. * @param {number} e - The value provided to the reduction by the current invocation.
  27989. * @return {number} The result of the reduction operation.
  27990. */
  27991. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  27992. /**
  27993. * A reduction that performs a max of e among all active invocations and returns that result.
  27994. *
  27995. * @method
  27996. * @param {number} e - The value provided to the reduction by the current invocation.
  27997. * @return {number} The result of the reduction operation.
  27998. */
  27999. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  28000. /**
  28001. * Returns true if e is true for all active invocations in the subgroup.
  28002. *
  28003. * @method
  28004. * @return {bool} The result of the computation.
  28005. */
  28006. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  28007. /**
  28008. * Returns true if e is true for any active invocation in the subgroup
  28009. *
  28010. * @method
  28011. * @return {bool} The result of the computation.
  28012. */
  28013. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  28014. /**
  28015. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  28016. *
  28017. * @method
  28018. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  28019. * @param {number} id - The subgroup invocation to broadcast from.
  28020. * @return {number} The broadcast value.
  28021. */
  28022. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  28023. /**
  28024. * Swaps e between invocations in the quad in the X direction.
  28025. *
  28026. * @method
  28027. * @param {number} e - The value to swap from the current invocation.
  28028. * @return {number} The value received from the swap operation.
  28029. */
  28030. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  28031. /**
  28032. * Swaps e between invocations in the quad in the Y direction.
  28033. *
  28034. * @method
  28035. * @param {number} e - The value to swap from the current invocation.
  28036. * @return {number} The value received from the swap operation.
  28037. */
  28038. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  28039. /**
  28040. * Swaps e between invocations in the quad diagonally.
  28041. *
  28042. * @method
  28043. * @param {number} e - The value to swap from the current invocation.
  28044. * @return {number} The value received from the swap operation.
  28045. */
  28046. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  28047. /**
  28048. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  28049. *
  28050. * @method
  28051. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  28052. * @param {number} id - The subgroup invocation to broadcast from.
  28053. * @return {number} The broadcast value.
  28054. */
  28055. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  28056. /**
  28057. * Returns v from the active invocation whose subgroup_invocation_id matches id
  28058. *
  28059. * @method
  28060. * @param {number} v - The value to return from subgroup invocation id^mask.
  28061. * @param {number} id - The subgroup invocation which returns the value v.
  28062. * @return {number} The broadcast value.
  28063. */
  28064. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  28065. /**
  28066. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  28067. *
  28068. * @method
  28069. * @param {number} v - The value to return from subgroup invocation id^mask.
  28070. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  28071. * @return {number} The broadcast value.
  28072. */
  28073. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  28074. /**
  28075. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  28076. *
  28077. * @method
  28078. * @param {number} v - The value to return from subgroup invocation id^mask.
  28079. * @param {number} delta - A value that offsets the current in.
  28080. * @return {number} The broadcast value.
  28081. */
  28082. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  28083. /**
  28084. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  28085. *
  28086. * @method
  28087. * @param {number} v - The value to return from subgroup invocation id^mask.
  28088. * @param {number} delta - A value that offsets the current subgroup invocation.
  28089. * @return {number} The broadcast value.
  28090. */
  28091. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  28092. /**
  28093. * Broadcasts e from the quad invocation with id equal to id.
  28094. *
  28095. * @method
  28096. * @param {number} e - The value to broadcast.
  28097. * @return {number} The broadcast value.
  28098. */
  28099. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  28100. let uniformsLib;
  28101. function getLightData( light ) {
  28102. uniformsLib = uniformsLib || new WeakMap();
  28103. let uniforms = uniformsLib.get( light );
  28104. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  28105. return uniforms;
  28106. }
  28107. /**
  28108. * TSL function for getting a shadow matrix uniform node for the given light.
  28109. *
  28110. * @tsl
  28111. * @function
  28112. * @param {Light} light -The light source.
  28113. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  28114. */
  28115. function lightShadowMatrix( light ) {
  28116. const data = getLightData( light );
  28117. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  28118. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  28119. light.shadow.updateMatrices( light );
  28120. }
  28121. return light.shadow.matrix;
  28122. } ) );
  28123. }
  28124. /**
  28125. * TSL function for getting projected uv coordinates for the given light.
  28126. * Relevant when using maps with spot lights.
  28127. *
  28128. * @tsl
  28129. * @function
  28130. * @param {Light} light -The light source.
  28131. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  28132. * @returns {Node<vec3>} The projected uvs.
  28133. */
  28134. function lightProjectionUV( light, position = positionWorld ) {
  28135. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  28136. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  28137. return projectionUV;
  28138. }
  28139. /**
  28140. * TSL function for getting the position in world space for the given light.
  28141. *
  28142. * @tsl
  28143. * @function
  28144. * @param {Light} light -The light source.
  28145. * @returns {UniformNode<vec3>} The light's position in world space.
  28146. */
  28147. function lightPosition( light ) {
  28148. const data = getLightData( light );
  28149. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  28150. }
  28151. /**
  28152. * TSL function for getting the light target position in world space for the given light.
  28153. *
  28154. * @tsl
  28155. * @function
  28156. * @param {Light} light -The light source.
  28157. * @returns {UniformNode<vec3>} The light target position in world space.
  28158. */
  28159. function lightTargetPosition( light ) {
  28160. const data = getLightData( light );
  28161. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  28162. }
  28163. /**
  28164. * TSL function for getting the position in view space for the given light.
  28165. *
  28166. * @tsl
  28167. * @function
  28168. * @param {Light} light - The light source.
  28169. * @returns {UniformNode<vec3>} The light's position in view space.
  28170. */
  28171. function lightViewPosition( light ) {
  28172. const data = getLightData( light );
  28173. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  28174. self.value = self.value || new Vector3();
  28175. self.value.setFromMatrixPosition( light.matrixWorld );
  28176. self.value.applyMatrix4( camera.matrixWorldInverse );
  28177. } ) );
  28178. }
  28179. /**
  28180. * TSL function for getting the light target direction for the given light.
  28181. *
  28182. * @tsl
  28183. * @function
  28184. * @param {Light} light -The light source.
  28185. * @returns {Node<vec3>} The light's target direction.
  28186. */
  28187. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  28188. const sortLights = ( lights ) => {
  28189. return lights.sort( ( a, b ) => a.id - b.id );
  28190. };
  28191. const getLightNodeById = ( id, lightNodes ) => {
  28192. for ( const lightNode of lightNodes ) {
  28193. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  28194. return lightNode;
  28195. }
  28196. }
  28197. return null;
  28198. };
  28199. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  28200. const _hashData = [];
  28201. /**
  28202. * This node represents the scene's lighting and manages the lighting model's life cycle
  28203. * for the current build 3D object. It is responsible for computing the total outgoing
  28204. * light in a given lighting context.
  28205. *
  28206. * @augments Node
  28207. */
  28208. class LightsNode extends Node {
  28209. static get type() {
  28210. return 'LightsNode';
  28211. }
  28212. /**
  28213. * Constructs a new lights node.
  28214. */
  28215. constructor() {
  28216. super( 'vec3' );
  28217. /**
  28218. * A node representing the total diffuse light.
  28219. *
  28220. * @type {Node<vec3>}
  28221. */
  28222. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  28223. /**
  28224. * A node representing the total specular light.
  28225. *
  28226. * @type {Node<vec3>}
  28227. */
  28228. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  28229. /**
  28230. * A node representing the outgoing light.
  28231. *
  28232. * @type {Node<vec3>}
  28233. */
  28234. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  28235. /**
  28236. * An array representing the lights in the scene.
  28237. *
  28238. * @private
  28239. * @type {Array<Light>}
  28240. */
  28241. this._lights = [];
  28242. /**
  28243. * For each light in the scene, this node will create a
  28244. * corresponding light node.
  28245. *
  28246. * @private
  28247. * @type {?Array<LightingNode>}
  28248. * @default null
  28249. */
  28250. this._lightNodes = null;
  28251. /**
  28252. * A hash for identifying the current light nodes setup.
  28253. *
  28254. * @private
  28255. * @type {?string}
  28256. * @default null
  28257. */
  28258. this._lightNodesHash = null;
  28259. /**
  28260. * `LightsNode` sets this property to `true` by default.
  28261. *
  28262. * @type {boolean}
  28263. * @default true
  28264. */
  28265. this.global = true;
  28266. }
  28267. /**
  28268. * Overwrites the default {@link Node#customCacheKey} implementation by including
  28269. * light data into the cache key.
  28270. *
  28271. * @return {number} The custom cache key.
  28272. */
  28273. customCacheKey() {
  28274. const lights = this._lights;
  28275. for ( let i = 0; i < lights.length; i ++ ) {
  28276. const light = lights[ i ];
  28277. _hashData.push( light.id );
  28278. _hashData.push( light.castShadow ? 1 : 0 );
  28279. if ( light.isSpotLight === true ) {
  28280. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  28281. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  28282. _hashData.push( hashMap, hashColorNode );
  28283. }
  28284. }
  28285. const cacheKey = hashArray( _hashData );
  28286. _hashData.length = 0;
  28287. return cacheKey;
  28288. }
  28289. /**
  28290. * Computes a hash value for identifying the current light nodes setup.
  28291. *
  28292. * @param {NodeBuilder} builder - A reference to the current node builder.
  28293. * @return {string} The computed hash.
  28294. */
  28295. getHash( builder ) {
  28296. if ( this._lightNodesHash === null ) {
  28297. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28298. const hash = [];
  28299. for ( const lightNode of this._lightNodes ) {
  28300. hash.push( lightNode.getSelf().getHash() );
  28301. }
  28302. this._lightNodesHash = 'lights-' + hash.join( ',' );
  28303. }
  28304. return this._lightNodesHash;
  28305. }
  28306. analyze( builder ) {
  28307. const properties = builder.getNodeProperties( this );
  28308. for ( const node of properties.nodes ) {
  28309. node.build( builder );
  28310. }
  28311. properties.outputNode.build( builder );
  28312. }
  28313. /**
  28314. * Creates lighting nodes for each scene light. This makes it possible to further
  28315. * process lights in the node system.
  28316. *
  28317. * @param {NodeBuilder} builder - A reference to the current node builder.
  28318. */
  28319. setupLightsNode( builder ) {
  28320. const lightNodes = [];
  28321. const previousLightNodes = this._lightNodes;
  28322. const lights = sortLights( this._lights );
  28323. const nodeLibrary = builder.renderer.library;
  28324. for ( const light of lights ) {
  28325. if ( light.isNode ) {
  28326. lightNodes.push( nodeObject( light ) );
  28327. } else {
  28328. let lightNode = null;
  28329. if ( previousLightNodes !== null ) {
  28330. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  28331. }
  28332. if ( lightNode === null ) {
  28333. // find the corresponding node type for a given light
  28334. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  28335. if ( lightNodeClass === null ) {
  28336. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  28337. continue;
  28338. }
  28339. let lightNode = null;
  28340. if ( ! _lightsNodeRef.has( light ) ) {
  28341. lightNode = nodeObject( new lightNodeClass( light ) );
  28342. _lightsNodeRef.set( light, lightNode );
  28343. } else {
  28344. lightNode = _lightsNodeRef.get( light );
  28345. }
  28346. lightNodes.push( lightNode );
  28347. }
  28348. }
  28349. }
  28350. this._lightNodes = lightNodes;
  28351. }
  28352. /**
  28353. * Sets up a direct light in the lighting model.
  28354. *
  28355. * @param {Object} builder - The builder object containing the context and stack.
  28356. * @param {Object} lightNode - The light node.
  28357. * @param {Object} lightData - The light object containing color and direction properties.
  28358. */
  28359. setupDirectLight( builder, lightNode, lightData ) {
  28360. const { lightingModel, reflectedLight } = builder.context;
  28361. lightingModel.direct( {
  28362. ...lightData,
  28363. lightNode,
  28364. reflectedLight
  28365. }, builder );
  28366. }
  28367. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  28368. const { lightingModel, reflectedLight } = builder.context;
  28369. lightingModel.directRectArea( {
  28370. ...lightData,
  28371. lightNode,
  28372. reflectedLight
  28373. }, builder );
  28374. }
  28375. /**
  28376. * Setups the internal lights by building all respective
  28377. * light nodes.
  28378. *
  28379. * @param {NodeBuilder} builder - A reference to the current node builder.
  28380. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  28381. */
  28382. setupLights( builder, lightNodes ) {
  28383. for ( const lightNode of lightNodes ) {
  28384. lightNode.build( builder );
  28385. }
  28386. }
  28387. getLightNodes( builder ) {
  28388. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28389. return this._lightNodes;
  28390. }
  28391. /**
  28392. * The implementation makes sure that for each light in the scene
  28393. * there is a corresponding light node. By building the light nodes
  28394. * and evaluating the lighting model the outgoing light is computed.
  28395. *
  28396. * @param {NodeBuilder} builder - A reference to the current node builder.
  28397. * @return {Node<vec3>} A node representing the outgoing light.
  28398. */
  28399. setup( builder ) {
  28400. const currentLightsNode = builder.lightsNode;
  28401. builder.lightsNode = this;
  28402. //
  28403. let outgoingLightNode = this.outgoingLightNode;
  28404. const context = builder.context;
  28405. const lightingModel = context.lightingModel;
  28406. const properties = builder.getNodeProperties( this );
  28407. if ( lightingModel ) {
  28408. const { totalDiffuseNode, totalSpecularNode } = this;
  28409. context.outgoingLight = outgoingLightNode;
  28410. const stack = builder.addStack();
  28411. //
  28412. properties.nodes = stack.nodes;
  28413. //
  28414. lightingModel.start( builder );
  28415. //
  28416. const { backdrop, backdropAlpha } = context;
  28417. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  28418. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  28419. if ( backdrop !== null ) {
  28420. if ( backdropAlpha !== null ) {
  28421. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  28422. } else {
  28423. totalDiffuse = vec3( backdrop );
  28424. }
  28425. context.material.transparent = true;
  28426. }
  28427. totalDiffuseNode.assign( totalDiffuse );
  28428. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  28429. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  28430. //
  28431. lightingModel.finish( builder );
  28432. //
  28433. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  28434. } else {
  28435. properties.nodes = [];
  28436. }
  28437. //
  28438. builder.lightsNode = currentLightsNode;
  28439. return outgoingLightNode;
  28440. }
  28441. /**
  28442. * Configures this node with an array of lights.
  28443. *
  28444. * @param {Array<Light>} lights - An array of lights.
  28445. * @return {LightsNode} A reference to this node.
  28446. */
  28447. setLights( lights ) {
  28448. this._lights = lights;
  28449. this._lightNodes = null;
  28450. this._lightNodesHash = null;
  28451. return this;
  28452. }
  28453. /**
  28454. * Returns an array of the scene's lights.
  28455. *
  28456. * @return {Array<Light>} The scene's lights.
  28457. */
  28458. getLights() {
  28459. return this._lights;
  28460. }
  28461. /**
  28462. * Whether the scene has lights or not.
  28463. *
  28464. * @type {boolean}
  28465. */
  28466. get hasLights() {
  28467. return this._lights.length > 0;
  28468. }
  28469. }
  28470. /**
  28471. * TSL function for creating an instance of `LightsNode` and configuring
  28472. * it with the given array of lights.
  28473. *
  28474. * @tsl
  28475. * @function
  28476. * @param {Array<Light>} lights - An array of lights.
  28477. * @return {LightsNode} The created lights node.
  28478. */
  28479. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  28480. /**
  28481. * Base class for all shadow nodes.
  28482. *
  28483. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  28484. * Lighting nodes might share the same shadow node type or use specific ones depending on
  28485. * their requirements.
  28486. *
  28487. * @augments Node
  28488. */
  28489. class ShadowBaseNode extends Node {
  28490. static get type() {
  28491. return 'ShadowBaseNode';
  28492. }
  28493. /**
  28494. * Constructs a new shadow base node.
  28495. *
  28496. * @param {Light} light - The shadow casting light.
  28497. */
  28498. constructor( light ) {
  28499. super();
  28500. /**
  28501. * The shadow casting light.
  28502. *
  28503. * @type {Light}
  28504. */
  28505. this.light = light;
  28506. /**
  28507. * Overwritten since shadows are updated by default per render.
  28508. *
  28509. * @type {string}
  28510. * @default 'render'
  28511. */
  28512. this.updateBeforeType = NodeUpdateType.RENDER;
  28513. /**
  28514. * This flag can be used for type testing.
  28515. *
  28516. * @type {boolean}
  28517. * @readonly
  28518. * @default true
  28519. */
  28520. this.isShadowBaseNode = true;
  28521. }
  28522. /**
  28523. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  28524. *
  28525. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  28526. */
  28527. setupShadowPosition( { context, material } ) {
  28528. // Use assign inside an Fn()
  28529. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  28530. }
  28531. }
  28532. /**
  28533. * TSL object that represents the vertex position in world space during the shadow pass.
  28534. *
  28535. * @tsl
  28536. * @type {Node<vec3>}
  28537. */
  28538. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  28539. /**
  28540. * Saves the state of the given renderer and stores it into the given state object.
  28541. *
  28542. * If not state object is provided, the function creates one.
  28543. *
  28544. * @function
  28545. * @param {Renderer} renderer - The renderer.
  28546. * @param {Object} [state={}] - The state.
  28547. * @return {Object} The state.
  28548. */
  28549. function saveRendererState( renderer, state = {} ) {
  28550. state.toneMapping = renderer.toneMapping;
  28551. state.toneMappingExposure = renderer.toneMappingExposure;
  28552. state.outputColorSpace = renderer.outputColorSpace;
  28553. state.renderTarget = renderer.getRenderTarget();
  28554. state.activeCubeFace = renderer.getActiveCubeFace();
  28555. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  28556. state.renderObjectFunction = renderer.getRenderObjectFunction();
  28557. state.pixelRatio = renderer.getPixelRatio();
  28558. state.mrt = renderer.getMRT();
  28559. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  28560. state.clearAlpha = renderer.getClearAlpha();
  28561. state.autoClear = renderer.autoClear;
  28562. state.scissorTest = renderer.getScissorTest();
  28563. return state;
  28564. }
  28565. /**
  28566. * Saves the state of the given renderer and stores it into the given state object.
  28567. * Besides, the function also resets the state of the renderer to its default values.
  28568. *
  28569. * If not state object is provided, the function creates one.
  28570. *
  28571. * @function
  28572. * @param {Renderer} renderer - The renderer.
  28573. * @param {Object} [state={}] - The state.
  28574. * @return {Object} The state.
  28575. */
  28576. function resetRendererState( renderer, state ) {
  28577. state = saveRendererState( renderer, state );
  28578. renderer.setMRT( null );
  28579. renderer.setRenderObjectFunction( null );
  28580. renderer.setClearColor( 0x000000, 1 );
  28581. renderer.autoClear = true;
  28582. return state;
  28583. }
  28584. /**
  28585. * Restores the state of the given renderer from the given state object.
  28586. *
  28587. * @function
  28588. * @param {Renderer} renderer - The renderer.
  28589. * @param {Object} state - The state to restore.
  28590. */
  28591. function restoreRendererState( renderer, state ) {
  28592. renderer.toneMapping = state.toneMapping;
  28593. renderer.toneMappingExposure = state.toneMappingExposure;
  28594. renderer.outputColorSpace = state.outputColorSpace;
  28595. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  28596. renderer.setRenderObjectFunction( state.renderObjectFunction );
  28597. renderer.setPixelRatio( state.pixelRatio );
  28598. renderer.setMRT( state.mrt );
  28599. renderer.setClearColor( state.clearColor, state.clearAlpha );
  28600. renderer.autoClear = state.autoClear;
  28601. renderer.setScissorTest( state.scissorTest );
  28602. }
  28603. /**
  28604. * Saves the state of the given scene and stores it into the given state object.
  28605. *
  28606. * If not state object is provided, the function creates one.
  28607. *
  28608. * @function
  28609. * @param {Scene} scene - The scene.
  28610. * @param {Object} [state={}] - The state.
  28611. * @return {Object} The state.
  28612. */
  28613. function saveSceneState( scene, state = {} ) {
  28614. state.background = scene.background;
  28615. state.backgroundNode = scene.backgroundNode;
  28616. state.overrideMaterial = scene.overrideMaterial;
  28617. return state;
  28618. }
  28619. /**
  28620. * Saves the state of the given scene and stores it into the given state object.
  28621. * Besides, the function also resets the state of the scene to its default values.
  28622. *
  28623. * If not state object is provided, the function creates one.
  28624. *
  28625. * @function
  28626. * @param {Scene} scene - The scene.
  28627. * @param {Object} [state={}] - The state.
  28628. * @return {Object} The state.
  28629. */
  28630. function resetSceneState( scene, state ) {
  28631. state = saveSceneState( scene, state );
  28632. scene.background = null;
  28633. scene.backgroundNode = null;
  28634. scene.overrideMaterial = null;
  28635. return state;
  28636. }
  28637. /**
  28638. * Restores the state of the given scene from the given state object.
  28639. *
  28640. * @function
  28641. * @param {Scene} scene - The scene.
  28642. * @param {Object} state - The state to restore.
  28643. */
  28644. function restoreSceneState( scene, state ) {
  28645. scene.background = state.background;
  28646. scene.backgroundNode = state.backgroundNode;
  28647. scene.overrideMaterial = state.overrideMaterial;
  28648. }
  28649. /**
  28650. * Saves the state of the given renderer and scene and stores it into the given state object.
  28651. *
  28652. * If not state object is provided, the function creates one.
  28653. *
  28654. * @function
  28655. * @param {Renderer} renderer - The renderer.
  28656. * @param {Scene} scene - The scene.
  28657. * @param {Object} [state={}] - The state.
  28658. * @return {Object} The state.
  28659. */
  28660. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  28661. state = saveRendererState( renderer, state );
  28662. state = saveSceneState( scene, state );
  28663. return state;
  28664. }
  28665. /**
  28666. * Saves the state of the given renderer and scene and stores it into the given state object.
  28667. * Besides, the function also resets the state of the renderer and scene to its default values.
  28668. *
  28669. * If not state object is provided, the function creates one.
  28670. *
  28671. * @function
  28672. * @param {Renderer} renderer - The renderer.
  28673. * @param {Scene} scene - The scene.
  28674. * @param {Object} [state={}] - The state.
  28675. * @return {Object} The state.
  28676. */
  28677. function resetRendererAndSceneState( renderer, scene, state ) {
  28678. state = resetRendererState( renderer, state );
  28679. state = resetSceneState( scene, state );
  28680. return state;
  28681. }
  28682. /**
  28683. * Restores the state of the given renderer and scene from the given state object.
  28684. *
  28685. * @function
  28686. * @param {Renderer} renderer - The renderer.
  28687. * @param {Scene} scene - The scene.
  28688. * @param {Object} state - The state to restore.
  28689. */
  28690. function restoreRendererAndSceneState( renderer, scene, state ) {
  28691. restoreRendererState( renderer, state );
  28692. restoreSceneState( scene, state );
  28693. }
  28694. var RendererUtils = /*#__PURE__*/Object.freeze({
  28695. __proto__: null,
  28696. resetRendererAndSceneState: resetRendererAndSceneState,
  28697. resetRendererState: resetRendererState,
  28698. resetSceneState: resetSceneState,
  28699. restoreRendererAndSceneState: restoreRendererAndSceneState,
  28700. restoreRendererState: restoreRendererState,
  28701. restoreSceneState: restoreSceneState,
  28702. saveRendererAndSceneState: saveRendererAndSceneState,
  28703. saveRendererState: saveRendererState,
  28704. saveSceneState: saveSceneState
  28705. });
  28706. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  28707. /**
  28708. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  28709. * with a binary `[0,1]` result.
  28710. *
  28711. * @method
  28712. * @param {Object} inputs - The input parameter object.
  28713. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28714. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28715. * @return {Node<float>} The filtering result.
  28716. */
  28717. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  28718. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  28719. if ( depthTexture.isArrayTexture ) {
  28720. basic = basic.depth( depthLayer );
  28721. }
  28722. return basic.compare( shadowCoord.z );
  28723. } );
  28724. /**
  28725. * A shadow filtering function performing PCF filtering.
  28726. *
  28727. * @method
  28728. * @param {Object} inputs - The input parameter object.
  28729. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28730. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28731. * @param {LightShadow} inputs.shadow - The light shadow.
  28732. * @return {Node<float>} The filtering result.
  28733. */
  28734. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  28735. const depthCompare = ( uv, compare ) => {
  28736. let depth = texture( depthTexture, uv );
  28737. if ( depthTexture.isArrayTexture ) {
  28738. depth = depth.depth( depthLayer );
  28739. }
  28740. return depth.compare( compare );
  28741. };
  28742. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28743. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28744. const texelSize = vec2( 1 ).div( mapSize );
  28745. const dx0 = texelSize.x.negate().mul( radius );
  28746. const dy0 = texelSize.y.negate().mul( radius );
  28747. const dx1 = texelSize.x.mul( radius );
  28748. const dy1 = texelSize.y.mul( radius );
  28749. const dx2 = dx0.div( 2 );
  28750. const dy2 = dy0.div( 2 );
  28751. const dx3 = dx1.div( 2 );
  28752. const dy3 = dy1.div( 2 );
  28753. return add(
  28754. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  28755. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  28756. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  28757. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  28758. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  28759. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  28760. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  28761. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  28762. depthCompare( shadowCoord.xy, shadowCoord.z ),
  28763. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  28764. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  28765. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  28766. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  28767. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  28768. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  28769. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  28770. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  28771. ).mul( 1 / 17 );
  28772. } );
  28773. /**
  28774. * A shadow filtering function performing PCF soft filtering.
  28775. *
  28776. * @method
  28777. * @param {Object} inputs - The input parameter object.
  28778. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28779. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28780. * @param {LightShadow} inputs.shadow - The light shadow.
  28781. * @return {Node<float>} The filtering result.
  28782. */
  28783. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  28784. const depthCompare = ( uv, compare ) => {
  28785. let depth = texture( depthTexture, uv );
  28786. if ( depthTexture.isArrayTexture ) {
  28787. depth = depth.depth( depthLayer );
  28788. }
  28789. return depth.compare( compare );
  28790. };
  28791. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28792. const texelSize = vec2( 1 ).div( mapSize );
  28793. const dx = texelSize.x;
  28794. const dy = texelSize.y;
  28795. const uv = shadowCoord.xy;
  28796. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  28797. uv.subAssign( f.mul( texelSize ) );
  28798. return add(
  28799. depthCompare( uv, shadowCoord.z ),
  28800. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  28801. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  28802. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  28803. mix(
  28804. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  28805. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  28806. f.x
  28807. ),
  28808. mix(
  28809. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  28810. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  28811. f.x
  28812. ),
  28813. mix(
  28814. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  28815. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  28816. f.y
  28817. ),
  28818. mix(
  28819. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  28820. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  28821. f.y
  28822. ),
  28823. mix(
  28824. mix(
  28825. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  28826. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  28827. f.x
  28828. ),
  28829. mix(
  28830. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  28831. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  28832. f.x
  28833. ),
  28834. f.y
  28835. )
  28836. ).mul( 1 / 9 );
  28837. } );
  28838. /**
  28839. * A shadow filtering function performing VSM filtering.
  28840. *
  28841. * @method
  28842. * @param {Object} inputs - The input parameter object.
  28843. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28844. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28845. * @return {Node<float>} The filtering result.
  28846. */
  28847. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  28848. const occlusion = float( 1 ).toVar();
  28849. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  28850. if ( depthTexture.isArrayTexture ) {
  28851. distribution = distribution.depth( depthLayer );
  28852. }
  28853. distribution = distribution.rg;
  28854. const hardShadow = step( shadowCoord.z, distribution.x );
  28855. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  28856. const distance = shadowCoord.z.sub( distribution.x );
  28857. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  28858. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  28859. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  28860. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  28861. } );
  28862. return occlusion;
  28863. } );
  28864. //
  28865. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  28866. let dist = positionWorld.sub( position ).length();
  28867. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  28868. dist = dist.saturate(); // clamp to [ 0, 1 ]
  28869. return dist;
  28870. } );
  28871. const linearShadowDistance = ( light ) => {
  28872. const camera = light.shadow.camera;
  28873. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  28874. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  28875. const referencePosition = objectPosition( light );
  28876. return linearDistance( referencePosition, nearDistance, farDistance );
  28877. };
  28878. /**
  28879. * Retrieves or creates a shadow material for the given light source.
  28880. *
  28881. * This function checks if a shadow material already exists for the provided light.
  28882. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  28883. * in the `shadowMaterialLib` for future use.
  28884. *
  28885. * @param {Light} light - The light source for which the shadow material is needed.
  28886. * If the light is a point light, a depth node is calculated
  28887. * using the linear shadow distance.
  28888. * @returns {NodeMaterial} The shadow material associated with the given light.
  28889. */
  28890. const getShadowMaterial = ( light ) => {
  28891. let material = shadowMaterialLib.get( light );
  28892. if ( material === undefined ) {
  28893. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  28894. material = new NodeMaterial();
  28895. material.colorNode = vec4( 0, 0, 0, 1 );
  28896. material.depthNode = depthNode;
  28897. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  28898. material.name = 'ShadowMaterial';
  28899. material.fog = false;
  28900. shadowMaterialLib.set( light, material );
  28901. }
  28902. return material;
  28903. };
  28904. //
  28905. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  28906. const _shadowRenderObjectKeys = [];
  28907. /**
  28908. * Creates a function to render shadow objects in a scene.
  28909. *
  28910. * @param {Renderer} renderer - The renderer.
  28911. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  28912. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  28913. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  28914. * @return {Function} A function that renders shadow objects.
  28915. *
  28916. * The returned function has the following parameters:
  28917. * @param {Object3D} object - The 3D object to render.
  28918. * @param {Scene} scene - The scene containing the object.
  28919. * @param {Camera} _camera - The camera used for rendering.
  28920. * @param {BufferGeometry} geometry - The geometry of the object.
  28921. * @param {Material} material - The material of the object.
  28922. * @param {Group} group - The group the object belongs to.
  28923. * @param {...any} params - Additional parameters for rendering.
  28924. */
  28925. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  28926. _shadowRenderObjectKeys[ 0 ] = renderer;
  28927. _shadowRenderObjectKeys[ 1 ] = shadow;
  28928. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  28929. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  28930. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  28931. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  28932. if ( useVelocity ) {
  28933. getDataFromObject( object ).useVelocity = true;
  28934. }
  28935. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  28936. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  28937. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  28938. }
  28939. };
  28940. renderObjectFunction.shadowType = shadowType;
  28941. renderObjectFunction.useVelocity = useVelocity;
  28942. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  28943. }
  28944. _shadowRenderObjectKeys[ 0 ] = null;
  28945. _shadowRenderObjectKeys[ 1 ] = null;
  28946. return renderObjectFunction;
  28947. };
  28948. /**
  28949. * Represents the shader code for the first VSM render pass.
  28950. *
  28951. * @method
  28952. * @param {Object} inputs - The input parameter object.
  28953. * @param {Node<float>} inputs.samples - The number of samples
  28954. * @param {Node<float>} inputs.radius - The radius.
  28955. * @param {Node<float>} inputs.size - The size.
  28956. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  28957. * @return {Node<vec2>} The VSM output.
  28958. */
  28959. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  28960. const mean = float( 0 ).toVar( 'meanVertical' );
  28961. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  28962. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  28963. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  28964. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  28965. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  28966. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  28967. if ( shadowPass.value.isArrayTexture ) {
  28968. depth = depth.depth( depthLayer );
  28969. }
  28970. depth = depth.x;
  28971. mean.addAssign( depth );
  28972. squaredMean.addAssign( depth.mul( depth ) );
  28973. } );
  28974. mean.divAssign( samples );
  28975. squaredMean.divAssign( samples );
  28976. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  28977. return vec2( mean, std_dev );
  28978. } );
  28979. /**
  28980. * Represents the shader code for the second VSM render pass.
  28981. *
  28982. * @method
  28983. * @param {Object} inputs - The input parameter object.
  28984. * @param {Node<float>} inputs.samples - The number of samples
  28985. * @param {Node<float>} inputs.radius - The radius.
  28986. * @param {Node<float>} inputs.size - The size.
  28987. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  28988. * @return {Node<vec2>} The VSM output.
  28989. */
  28990. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  28991. const mean = float( 0 ).toVar( 'meanHorizontal' );
  28992. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  28993. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  28994. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  28995. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  28996. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  28997. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  28998. if ( shadowPass.value.isArrayTexture ) {
  28999. distribution = distribution.depth( depthLayer );
  29000. }
  29001. mean.addAssign( distribution.x );
  29002. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  29003. } );
  29004. mean.divAssign( samples );
  29005. squaredMean.divAssign( samples );
  29006. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29007. return vec2( mean, std_dev );
  29008. } );
  29009. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  29010. //
  29011. let _rendererState;
  29012. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  29013. /**
  29014. * Represents the default shadow implementation for lighting nodes.
  29015. *
  29016. * @augments ShadowBaseNode
  29017. */
  29018. class ShadowNode extends ShadowBaseNode {
  29019. static get type() {
  29020. return 'ShadowNode';
  29021. }
  29022. /**
  29023. * Constructs a new shadow node.
  29024. *
  29025. * @param {Light} light - The shadow casting light.
  29026. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  29027. */
  29028. constructor( light, shadow = null ) {
  29029. super( light );
  29030. /**
  29031. * The light shadow which defines the properties light's
  29032. * shadow.
  29033. *
  29034. * @type {?LightShadow}
  29035. * @default null
  29036. */
  29037. this.shadow = shadow || light.shadow;
  29038. /**
  29039. * A reference to the shadow map which is a render target.
  29040. *
  29041. * @type {?RenderTarget}
  29042. * @default null
  29043. */
  29044. this.shadowMap = null;
  29045. /**
  29046. * Only relevant for VSM shadows. Render target for the
  29047. * first VSM render pass.
  29048. *
  29049. * @type {?RenderTarget}
  29050. * @default null
  29051. */
  29052. this.vsmShadowMapVertical = null;
  29053. /**
  29054. * Only relevant for VSM shadows. Render target for the
  29055. * second VSM render pass.
  29056. *
  29057. * @type {?RenderTarget}
  29058. * @default null
  29059. */
  29060. this.vsmShadowMapHorizontal = null;
  29061. /**
  29062. * Only relevant for VSM shadows. Node material which
  29063. * is used to render the first VSM pass.
  29064. *
  29065. * @type {?NodeMaterial}
  29066. * @default null
  29067. */
  29068. this.vsmMaterialVertical = null;
  29069. /**
  29070. * Only relevant for VSM shadows. Node material which
  29071. * is used to render the second VSM pass.
  29072. *
  29073. * @type {?NodeMaterial}
  29074. * @default null
  29075. */
  29076. this.vsmMaterialHorizontal = null;
  29077. /**
  29078. * A reference to the output node which defines the
  29079. * final result of this shadow node.
  29080. *
  29081. * @type {?Node}
  29082. * @private
  29083. * @default null
  29084. */
  29085. this._node = null;
  29086. this._cameraFrameId = new WeakMap();
  29087. /**
  29088. * This flag can be used for type testing.
  29089. *
  29090. * @type {boolean}
  29091. * @readonly
  29092. * @default true
  29093. */
  29094. this.isShadowNode = true;
  29095. /**
  29096. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  29097. *
  29098. * @type {number}
  29099. * @readonly
  29100. * @default true
  29101. */
  29102. this.depthLayer = 0;
  29103. }
  29104. /**
  29105. * Setups the shadow filtering.
  29106. *
  29107. * @param {NodeBuilder} builder - A reference to the current node builder.
  29108. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29109. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29110. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29111. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29112. * @param {LightShadow} inputs.shadow - The light shadow.
  29113. * @return {Node<float>} The result node of the shadow filtering.
  29114. */
  29115. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  29116. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  29117. .and( shadowCoord.x.lessThanEqual( 1 ) )
  29118. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  29119. .and( shadowCoord.y.lessThanEqual( 1 ) )
  29120. .and( shadowCoord.z.lessThanEqual( 1 ) );
  29121. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  29122. return frustumTest.select( shadowNode, float( 1 ) );
  29123. }
  29124. /**
  29125. * Setups the shadow coordinates.
  29126. *
  29127. * @param {NodeBuilder} builder - A reference to the current node builder.
  29128. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29129. * @return {Node<vec3>} The shadow coordinates.
  29130. */
  29131. setupShadowCoord( builder, shadowPosition ) {
  29132. const { shadow } = this;
  29133. const { renderer } = builder;
  29134. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29135. let shadowCoord = shadowPosition;
  29136. let coordZ;
  29137. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  29138. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  29139. coordZ = shadowCoord.z;
  29140. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  29141. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  29142. }
  29143. } else {
  29144. const w = shadowCoord.w;
  29145. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  29146. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  29147. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  29148. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  29149. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  29150. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  29151. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  29152. }
  29153. shadowCoord = vec3(
  29154. shadowCoord.x,
  29155. shadowCoord.y.oneMinus(), // follow webgpu standards
  29156. coordZ.add( bias )
  29157. );
  29158. return shadowCoord;
  29159. }
  29160. /**
  29161. * Returns the shadow filtering function for the given shadow type.
  29162. *
  29163. * @param {number} type - The shadow type.
  29164. * @return {Function} The filtering function.
  29165. */
  29166. getShadowFilterFn( type ) {
  29167. return _shadowFilterLib[ type ];
  29168. }
  29169. setupRenderTarget( shadow, builder ) {
  29170. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  29171. depthTexture.name = 'ShadowDepthTexture';
  29172. depthTexture.compareFunction = LessCompare;
  29173. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  29174. shadowMap.texture.name = 'ShadowMap';
  29175. shadowMap.texture.type = shadow.mapType;
  29176. shadowMap.depthTexture = depthTexture;
  29177. return { shadowMap, depthTexture };
  29178. }
  29179. /**
  29180. * Setups the shadow output node.
  29181. *
  29182. * @param {NodeBuilder} builder - A reference to the current node builder.
  29183. * @return {Node<vec3>} The shadow output node.
  29184. */
  29185. setupShadow( builder ) {
  29186. const { renderer } = builder;
  29187. const { light, shadow } = this;
  29188. const shadowMapType = renderer.shadowMap.type;
  29189. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  29190. shadow.camera.updateProjectionMatrix();
  29191. // VSM
  29192. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29193. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  29194. if ( shadowMap.depth > 1 ) {
  29195. if ( ! shadowMap._vsmShadowMapVertical ) {
  29196. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29197. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  29198. }
  29199. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  29200. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  29201. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29202. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  29203. }
  29204. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  29205. } else {
  29206. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29207. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29208. }
  29209. let shadowPassVertical = texture( depthTexture );
  29210. if ( depthTexture.isArrayTexture ) {
  29211. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  29212. }
  29213. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  29214. if ( depthTexture.isArrayTexture ) {
  29215. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  29216. }
  29217. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  29218. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29219. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29220. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  29221. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29222. material.name = 'VSMVertical';
  29223. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  29224. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29225. material.name = 'VSMHorizontal';
  29226. }
  29227. //
  29228. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  29229. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  29230. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  29231. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  29232. //
  29233. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  29234. if ( filterFn === null ) {
  29235. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  29236. }
  29237. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  29238. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  29239. let shadowColor = texture( shadowMap.texture, shadowCoord );
  29240. if ( depthTexture.isArrayTexture ) {
  29241. shadowColor = shadowColor.depth( this.depthLayer );
  29242. }
  29243. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  29244. this.shadowMap = shadowMap;
  29245. this.shadow.map = shadowMap;
  29246. return shadowOutput;
  29247. }
  29248. /**
  29249. * The implementation performs the setup of the output node. An output is only
  29250. * produces if shadow mapping is globally enabled in the renderer.
  29251. *
  29252. * @param {NodeBuilder} builder - A reference to the current node builder.
  29253. * @return {ShaderCallNodeInternal} The output node.
  29254. */
  29255. setup( builder ) {
  29256. if ( builder.renderer.shadowMap.enabled === false ) return;
  29257. return Fn( () => {
  29258. let node = this._node;
  29259. this.setupShadowPosition( builder );
  29260. if ( node === null ) {
  29261. this._node = node = this.setupShadow( builder );
  29262. }
  29263. if ( builder.material.shadowNode ) { // @deprecated, r171
  29264. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  29265. }
  29266. if ( builder.material.receivedShadowNode ) {
  29267. node = builder.material.receivedShadowNode( node );
  29268. }
  29269. return node;
  29270. } )();
  29271. }
  29272. /**
  29273. * Renders the shadow. The logic of this function could be included
  29274. * into {@link ShadowNode#updateShadow} however more specialized shadow
  29275. * nodes might require a custom shadow map rendering. By having a
  29276. * dedicated method, it's easier to overwrite the default behavior.
  29277. *
  29278. * @param {NodeFrame} frame - A reference to the current node frame.
  29279. */
  29280. renderShadow( frame ) {
  29281. const { shadow, shadowMap, light } = this;
  29282. const { renderer, scene } = frame;
  29283. shadow.updateMatrices( light );
  29284. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  29285. renderer.render( scene, shadow.camera );
  29286. }
  29287. /**
  29288. * Updates the shadow.
  29289. *
  29290. * @param {NodeFrame} frame - A reference to the current node frame.
  29291. */
  29292. updateShadow( frame ) {
  29293. const { shadowMap, light, shadow } = this;
  29294. const { renderer, scene, camera } = frame;
  29295. const shadowType = renderer.shadowMap.type;
  29296. const depthVersion = shadowMap.depthTexture.version;
  29297. this._depthVersionCached = depthVersion;
  29298. const _shadowCameraLayer = shadow.camera.layers.mask;
  29299. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  29300. shadow.camera.layers.mask = camera.layers.mask;
  29301. }
  29302. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  29303. const currentMRT = renderer.getMRT();
  29304. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  29305. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  29306. scene.overrideMaterial = getShadowMaterial( light );
  29307. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  29308. renderer.setClearColor( 0x000000, 0 );
  29309. renderer.setRenderTarget( shadowMap );
  29310. this.renderShadow( frame );
  29311. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  29312. // vsm blur pass
  29313. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29314. this.vsmPass( renderer );
  29315. }
  29316. shadow.camera.layers.mask = _shadowCameraLayer;
  29317. restoreRendererAndSceneState( renderer, scene, _rendererState );
  29318. }
  29319. /**
  29320. * For VSM additional render passes are required.
  29321. *
  29322. * @param {Renderer} renderer - A reference to the current renderer.
  29323. */
  29324. vsmPass( renderer ) {
  29325. const { shadow } = this;
  29326. const depth = this.shadowMap.depth;
  29327. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29328. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29329. renderer.setRenderTarget( this.vsmShadowMapVertical );
  29330. _quadMesh.material = this.vsmMaterialVertical;
  29331. _quadMesh.render( renderer );
  29332. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  29333. _quadMesh.material = this.vsmMaterialHorizontal;
  29334. _quadMesh.render( renderer );
  29335. }
  29336. /**
  29337. * Frees the internal resources of this shadow node.
  29338. */
  29339. dispose() {
  29340. this.shadowMap.dispose();
  29341. this.shadowMap = null;
  29342. if ( this.vsmShadowMapVertical !== null ) {
  29343. this.vsmShadowMapVertical.dispose();
  29344. this.vsmShadowMapVertical = null;
  29345. this.vsmMaterialVertical.dispose();
  29346. this.vsmMaterialVertical = null;
  29347. }
  29348. if ( this.vsmShadowMapHorizontal !== null ) {
  29349. this.vsmShadowMapHorizontal.dispose();
  29350. this.vsmShadowMapHorizontal = null;
  29351. this.vsmMaterialHorizontal.dispose();
  29352. this.vsmMaterialHorizontal = null;
  29353. }
  29354. super.dispose();
  29355. }
  29356. /**
  29357. * The implementation performs the update of the shadow map if necessary.
  29358. *
  29359. * @param {NodeFrame} frame - A reference to the current node frame.
  29360. */
  29361. updateBefore( frame ) {
  29362. const { shadow } = this;
  29363. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  29364. if ( needsUpdate ) {
  29365. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  29366. needsUpdate = false;
  29367. }
  29368. this._cameraFrameId[ frame.camera ] = frame.frameId;
  29369. }
  29370. if ( needsUpdate ) {
  29371. this.updateShadow( frame );
  29372. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  29373. shadow.needsUpdate = false;
  29374. }
  29375. }
  29376. }
  29377. }
  29378. /**
  29379. * TSL function for creating an instance of `ShadowNode`.
  29380. *
  29381. * @tsl
  29382. * @function
  29383. * @param {Light} light - The shadow casting light.
  29384. * @param {?LightShadow} [shadow] - The light shadow.
  29385. * @return {ShadowNode} The created shadow node.
  29386. */
  29387. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  29388. const _clearColor$1 = /*@__PURE__*/ new Color();
  29389. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  29390. // vector suitable for 2D texture mapping. This code uses the following layout for the
  29391. // 2D texture:
  29392. //
  29393. // xzXZ
  29394. // y Y
  29395. //
  29396. // Y - Positive y direction
  29397. // y - Negative y direction
  29398. // X - Positive x direction
  29399. // x - Negative x direction
  29400. // Z - Positive z direction
  29401. // z - Negative z direction
  29402. //
  29403. // Source and test bed:
  29404. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  29405. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  29406. const v = pos.toVar();
  29407. // Number of texels to avoid at the edge of each square
  29408. const absV = abs( v );
  29409. // Intersect unit cube
  29410. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  29411. absV.mulAssign( scaleToCube );
  29412. // Apply scale to avoid seams
  29413. // two texels less per square (one texel will do for NEAREST)
  29414. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  29415. // Unwrap
  29416. // space: -1 ... 1 range for each square
  29417. //
  29418. // #X## dim := ( 4 , 2 )
  29419. // # # center := ( 1 , 1 )
  29420. const planar = vec2( v.xy ).toVar();
  29421. const almostATexel = texelSizeY.mul( 1.5 );
  29422. const almostOne = almostATexel.oneMinus();
  29423. If( absV.z.greaterThanEqual( almostOne ), () => {
  29424. If( v.z.greaterThan( 0.0 ), () => {
  29425. planar.x.assign( sub( 4.0, v.x ) );
  29426. } );
  29427. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  29428. const signX = sign( v.x );
  29429. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  29430. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  29431. const signY = sign( v.y );
  29432. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  29433. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  29434. } );
  29435. // Transform to UV space
  29436. // scale := 0.5 / dim
  29437. // translate := ( center + 0.5 ) / dim
  29438. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  29439. } ).setLayout( {
  29440. name: 'cubeToUV',
  29441. type: 'vec2',
  29442. inputs: [
  29443. { name: 'pos', type: 'vec3' },
  29444. { name: 'texelSizeY', type: 'float' }
  29445. ]
  29446. } );
  29447. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  29448. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  29449. } );
  29450. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  29451. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29452. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  29453. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  29454. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  29455. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  29456. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  29457. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  29458. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  29459. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  29460. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  29461. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  29462. .mul( 1.0 / 9.0 );
  29463. } );
  29464. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  29465. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  29466. // the vector from the light to the world-space position of the fragment.
  29467. const lightToPosition = shadowCoord.xyz.toVar();
  29468. const lightToPositionLength = lightToPosition.length();
  29469. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  29470. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  29471. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29472. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  29473. const result = float( 1.0 ).toVar();
  29474. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  29475. // dp = normalized distance from light to fragment position
  29476. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  29477. dp.addAssign( bias );
  29478. // bd3D = base direction 3D
  29479. const bd3D = lightToPosition.normalize();
  29480. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  29481. // percentage-closer filtering
  29482. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  29483. } );
  29484. return result;
  29485. } );
  29486. const _viewport = /*@__PURE__*/ new Vector4();
  29487. const _viewportSize = /*@__PURE__*/ new Vector2();
  29488. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  29489. /**
  29490. * Represents the shadow implementation for point light nodes.
  29491. *
  29492. * @augments ShadowNode
  29493. */
  29494. class PointShadowNode extends ShadowNode {
  29495. static get type() {
  29496. return 'PointShadowNode';
  29497. }
  29498. /**
  29499. * Constructs a new point shadow node.
  29500. *
  29501. * @param {PointLight} light - The shadow casting point light.
  29502. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  29503. */
  29504. constructor( light, shadow = null ) {
  29505. super( light, shadow );
  29506. }
  29507. /**
  29508. * Overwrites the default implementation to return point light shadow specific
  29509. * filtering functions.
  29510. *
  29511. * @param {number} type - The shadow type.
  29512. * @return {Function} The filtering function.
  29513. */
  29514. getShadowFilterFn( type ) {
  29515. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  29516. }
  29517. /**
  29518. * Overwrites the default implementation so the unaltered shadow position is used.
  29519. *
  29520. * @param {NodeBuilder} builder - A reference to the current node builder.
  29521. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29522. * @return {Node<vec3>} The shadow coordinates.
  29523. */
  29524. setupShadowCoord( builder, shadowPosition ) {
  29525. return shadowPosition;
  29526. }
  29527. /**
  29528. * Overwrites the default implementation to only use point light specific
  29529. * shadow filter functions.
  29530. *
  29531. * @param {NodeBuilder} builder - A reference to the current node builder.
  29532. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29533. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29534. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  29535. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29536. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29537. * @param {LightShadow} inputs.shadow - The light shadow.
  29538. * @return {Node<float>} The result node of the shadow filtering.
  29539. */
  29540. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  29541. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  29542. }
  29543. /**
  29544. * Overwrites the default implementation with point light specific
  29545. * rendering code.
  29546. *
  29547. * @param {NodeFrame} frame - A reference to the current node frame.
  29548. */
  29549. renderShadow( frame ) {
  29550. const { shadow, shadowMap, light } = this;
  29551. const { renderer, scene } = frame;
  29552. const shadowFrameExtents = shadow.getFrameExtents();
  29553. _shadowMapSize.copy( shadow.mapSize );
  29554. _shadowMapSize.multiply( shadowFrameExtents );
  29555. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  29556. _viewportSize.copy( shadow.mapSize );
  29557. //
  29558. const previousAutoClear = renderer.autoClear;
  29559. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  29560. const previousClearAlpha = renderer.getClearAlpha();
  29561. renderer.autoClear = false;
  29562. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  29563. renderer.clear();
  29564. const viewportCount = shadow.getViewportCount();
  29565. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  29566. const viewport = shadow.getViewport( vp );
  29567. const x = _viewportSize.x * viewport.x;
  29568. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  29569. _viewport.set(
  29570. x,
  29571. y,
  29572. _viewportSize.x * viewport.z,
  29573. _viewportSize.y * viewport.w
  29574. );
  29575. shadowMap.viewport.copy( _viewport );
  29576. shadow.updateMatrices( light, vp );
  29577. renderer.render( scene, shadow.camera );
  29578. }
  29579. //
  29580. renderer.autoClear = previousAutoClear;
  29581. renderer.setClearColor( previousClearColor, previousClearAlpha );
  29582. }
  29583. }
  29584. /**
  29585. * TSL function for creating an instance of `PointShadowNode`.
  29586. *
  29587. * @tsl
  29588. * @function
  29589. * @param {PointLight} light - The shadow casting point light.
  29590. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  29591. * @return {PointShadowNode} The created point shadow node.
  29592. */
  29593. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  29594. /**
  29595. * Base class for analytic light nodes.
  29596. *
  29597. * @augments LightingNode
  29598. */
  29599. class AnalyticLightNode extends LightingNode {
  29600. static get type() {
  29601. return 'AnalyticLightNode';
  29602. }
  29603. /**
  29604. * Constructs a new analytic light node.
  29605. *
  29606. * @param {?Light} [light=null] - The light source.
  29607. */
  29608. constructor( light = null ) {
  29609. super();
  29610. /**
  29611. * The light source.
  29612. *
  29613. * @type {?Light}
  29614. * @default null
  29615. */
  29616. this.light = light;
  29617. /**
  29618. * The light's color value.
  29619. *
  29620. * @type {Color}
  29621. */
  29622. this.color = new Color();
  29623. /**
  29624. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  29625. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  29626. *
  29627. * @type {Node}
  29628. */
  29629. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  29630. /**
  29631. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  29632. * The final color node is represented by a different node when using shadows.
  29633. *
  29634. * @type {?Node}
  29635. * @default null
  29636. */
  29637. this.baseColorNode = null;
  29638. /**
  29639. * Represents the light's shadow.
  29640. *
  29641. * @type {?ShadowNode}
  29642. * @default null
  29643. */
  29644. this.shadowNode = null;
  29645. /**
  29646. * Represents the light's shadow color.
  29647. *
  29648. * @type {?Node}
  29649. * @default null
  29650. */
  29651. this.shadowColorNode = null;
  29652. /**
  29653. * This flag can be used for type testing.
  29654. *
  29655. * @type {boolean}
  29656. * @readonly
  29657. * @default true
  29658. */
  29659. this.isAnalyticLightNode = true;
  29660. /**
  29661. * Overwritten since analytic light nodes are updated
  29662. * once per frame.
  29663. *
  29664. * @type {string}
  29665. * @default 'frame'
  29666. */
  29667. this.updateType = NodeUpdateType.FRAME;
  29668. }
  29669. getHash() {
  29670. return this.light.uuid;
  29671. }
  29672. /**
  29673. * Returns a node representing a direction vector which points from the current
  29674. * position in view space to the light's position in view space.
  29675. *
  29676. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29677. * @return {Node<vec3>} The light vector node.
  29678. */
  29679. getLightVector( builder ) {
  29680. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  29681. }
  29682. /**
  29683. * Sets up the direct lighting for the analytic light node.
  29684. *
  29685. * @abstract
  29686. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29687. * @return {Object|undefined} The direct light data (color and direction).
  29688. */
  29689. setupDirect( /*builder*/ ) { }
  29690. /**
  29691. * Sets up the direct rect area lighting for the analytic light node.
  29692. *
  29693. * @abstract
  29694. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29695. * @return {Object|undefined} The direct rect area light data.
  29696. */
  29697. setupDirectRectArea( /*builder*/ ) { }
  29698. /**
  29699. * Setups the shadow node for this light. The method exists so concrete light classes
  29700. * can setup different types of shadow nodes.
  29701. *
  29702. * @return {ShadowNode} The created shadow node.
  29703. */
  29704. setupShadowNode() {
  29705. return shadow( this.light );
  29706. }
  29707. /**
  29708. * Setups the shadow for this light. This method is only executed if the light
  29709. * cast shadows and the current build object receives shadows. It incorporates
  29710. * shadows into the lighting computation.
  29711. *
  29712. * @param {NodeBuilder} builder - The current node builder.
  29713. */
  29714. setupShadow( builder ) {
  29715. const { renderer } = builder;
  29716. if ( renderer.shadowMap.enabled === false ) return;
  29717. let shadowColorNode = this.shadowColorNode;
  29718. if ( shadowColorNode === null ) {
  29719. const customShadowNode = this.light.shadow.shadowNode;
  29720. let shadowNode;
  29721. if ( customShadowNode !== undefined ) {
  29722. shadowNode = nodeObject( customShadowNode );
  29723. } else {
  29724. shadowNode = this.setupShadowNode();
  29725. }
  29726. this.shadowNode = shadowNode;
  29727. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  29728. this.baseColorNode = this.colorNode;
  29729. }
  29730. //
  29731. this.colorNode = shadowColorNode;
  29732. }
  29733. /**
  29734. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  29735. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  29736. * invocate the respective interface methods.
  29737. *
  29738. * @param {NodeBuilder} builder - The current node builder.
  29739. */
  29740. setup( builder ) {
  29741. this.colorNode = this.baseColorNode || this.colorNode;
  29742. if ( this.light.castShadow ) {
  29743. if ( builder.object.receiveShadow ) {
  29744. this.setupShadow( builder );
  29745. }
  29746. } else if ( this.shadowNode !== null ) {
  29747. this.shadowNode.dispose();
  29748. this.shadowNode = null;
  29749. this.shadowColorNode = null;
  29750. }
  29751. const directLightData = this.setupDirect( builder );
  29752. const directRectAreaLightData = this.setupDirectRectArea( builder );
  29753. if ( directLightData ) {
  29754. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  29755. }
  29756. if ( directRectAreaLightData ) {
  29757. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  29758. }
  29759. }
  29760. /**
  29761. * The update method is used to update light uniforms per frame.
  29762. * Potentially overwritten in concrete light nodes to update light
  29763. * specific uniforms.
  29764. *
  29765. * @param {NodeFrame} frame - A reference to the current node frame.
  29766. */
  29767. update( /*frame*/ ) {
  29768. const { light } = this;
  29769. this.color.copy( light.color ).multiplyScalar( light.intensity );
  29770. }
  29771. }
  29772. /**
  29773. * Represents a `discard` shader operation in TSL.
  29774. *
  29775. * @method
  29776. * @param {Object} inputs - The input parameter object.
  29777. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  29778. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  29779. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  29780. * @return {Node<float>} The distance falloff.
  29781. */
  29782. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  29783. // based upon Frostbite 3 Moving to Physically-based Rendering
  29784. // page 32, equation 26: E[window1]
  29785. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29786. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  29787. return cutoffDistance.greaterThan( 0 ).select(
  29788. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  29789. distanceFalloff
  29790. );
  29791. } ); // validated
  29792. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  29793. const lightDirection = lightVector.normalize();
  29794. const lightDistance = lightVector.length();
  29795. const attenuation = getDistanceAttenuation( {
  29796. lightDistance,
  29797. cutoffDistance,
  29798. decayExponent
  29799. } );
  29800. const lightColor = color.mul( attenuation );
  29801. return { lightDirection, lightColor };
  29802. };
  29803. /**
  29804. * Module for representing point lights as nodes.
  29805. *
  29806. * @augments AnalyticLightNode
  29807. */
  29808. class PointLightNode extends AnalyticLightNode {
  29809. static get type() {
  29810. return 'PointLightNode';
  29811. }
  29812. /**
  29813. * Constructs a new point light node.
  29814. *
  29815. * @param {?PointLight} [light=null] - The point light source.
  29816. */
  29817. constructor( light = null ) {
  29818. super( light );
  29819. /**
  29820. * Uniform node representing the cutoff distance.
  29821. *
  29822. * @type {UniformNode<float>}
  29823. */
  29824. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  29825. /**
  29826. * Uniform node representing the decay exponent.
  29827. *
  29828. * @type {UniformNode<float>}
  29829. */
  29830. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  29831. }
  29832. /**
  29833. * Overwritten to updated point light specific uniforms.
  29834. *
  29835. * @param {NodeFrame} frame - A reference to the current node frame.
  29836. */
  29837. update( frame ) {
  29838. const { light } = this;
  29839. super.update( frame );
  29840. this.cutoffDistanceNode.value = light.distance;
  29841. this.decayExponentNode.value = light.decay;
  29842. }
  29843. /**
  29844. * Overwritten to setup point light specific shadow.
  29845. *
  29846. * @return {PointShadowNode}
  29847. */
  29848. setupShadowNode() {
  29849. return pointShadow( this.light );
  29850. }
  29851. setupDirect( builder ) {
  29852. return directPointLight( {
  29853. color: this.colorNode,
  29854. lightVector: this.getLightVector( builder ),
  29855. cutoffDistance: this.cutoffDistanceNode,
  29856. decayExponent: this.decayExponentNode
  29857. } );
  29858. }
  29859. }
  29860. /**
  29861. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  29862. *
  29863. * @tsl
  29864. * @function
  29865. * @param {Node<vec2>} coord - The uv coordinates.
  29866. * @return {Node<float>} The result data.
  29867. */
  29868. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  29869. const uv = coord.mul( 2.0 );
  29870. const cx = uv.x.floor();
  29871. const cy = uv.y.floor();
  29872. const result = cx.add( cy ).mod( 2.0 );
  29873. return result.sign();
  29874. } );
  29875. /**
  29876. * Generates a circle based on the uv coordinates.
  29877. *
  29878. * @tsl
  29879. * @function
  29880. * @param {Node<vec2>} coord - The uv to generate the circle.
  29881. * @return {Node<float>} The circle shape.
  29882. */
  29883. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  29884. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  29885. let alpha;
  29886. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  29887. const dlen = float( len2.fwidth() ).toVar();
  29888. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  29889. } else {
  29890. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  29891. }
  29892. return alpha;
  29893. } );
  29894. // Three.js Transpiler
  29895. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  29896. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  29897. const f = float( f_immutable ).toVar();
  29898. const t = float( t_immutable ).toVar();
  29899. const b = bool( b_immutable ).toVar();
  29900. return select( b, t, f );
  29901. } ).setLayout( {
  29902. name: 'mx_select',
  29903. type: 'float',
  29904. inputs: [
  29905. { name: 'b', type: 'bool' },
  29906. { name: 't', type: 'float' },
  29907. { name: 'f', type: 'float' }
  29908. ]
  29909. } );
  29910. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  29911. const b = bool( b_immutable ).toVar();
  29912. const val = float( val_immutable ).toVar();
  29913. return select( b, val.negate(), val );
  29914. } ).setLayout( {
  29915. name: 'mx_negate_if',
  29916. type: 'float',
  29917. inputs: [
  29918. { name: 'val', type: 'float' },
  29919. { name: 'b', type: 'bool' }
  29920. ]
  29921. } );
  29922. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29923. const x = float( x_immutable ).toVar();
  29924. return int( floor( x ) );
  29925. } ).setLayout( {
  29926. name: 'mx_floor',
  29927. type: 'int',
  29928. inputs: [
  29929. { name: 'x', type: 'float' }
  29930. ]
  29931. } );
  29932. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  29933. const x = float( x_immutable ).toVar();
  29934. i.assign( mx_floor( x ) );
  29935. return x.sub( float( i ) );
  29936. } );
  29937. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  29938. const t = float( t_immutable ).toVar();
  29939. const s = float( s_immutable ).toVar();
  29940. const v3 = float( v3_immutable ).toVar();
  29941. const v2 = float( v2_immutable ).toVar();
  29942. const v1 = float( v1_immutable ).toVar();
  29943. const v0 = float( v0_immutable ).toVar();
  29944. const s1 = float( sub( 1.0, s ) ).toVar();
  29945. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29946. } ).setLayout( {
  29947. name: 'mx_bilerp_0',
  29948. type: 'float',
  29949. inputs: [
  29950. { name: 'v0', type: 'float' },
  29951. { name: 'v1', type: 'float' },
  29952. { name: 'v2', type: 'float' },
  29953. { name: 'v3', type: 'float' },
  29954. { name: 's', type: 'float' },
  29955. { name: 't', type: 'float' }
  29956. ]
  29957. } );
  29958. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  29959. const t = float( t_immutable ).toVar();
  29960. const s = float( s_immutable ).toVar();
  29961. const v3 = vec3( v3_immutable ).toVar();
  29962. const v2 = vec3( v2_immutable ).toVar();
  29963. const v1 = vec3( v1_immutable ).toVar();
  29964. const v0 = vec3( v0_immutable ).toVar();
  29965. const s1 = float( sub( 1.0, s ) ).toVar();
  29966. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29967. } ).setLayout( {
  29968. name: 'mx_bilerp_1',
  29969. type: 'vec3',
  29970. inputs: [
  29971. { name: 'v0', type: 'vec3' },
  29972. { name: 'v1', type: 'vec3' },
  29973. { name: 'v2', type: 'vec3' },
  29974. { name: 'v3', type: 'vec3' },
  29975. { name: 's', type: 'float' },
  29976. { name: 't', type: 'float' }
  29977. ]
  29978. } );
  29979. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  29980. 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 ] ) => {
  29981. const r = float( r_immutable ).toVar();
  29982. const t = float( t_immutable ).toVar();
  29983. const s = float( s_immutable ).toVar();
  29984. const v7 = float( v7_immutable ).toVar();
  29985. const v6 = float( v6_immutable ).toVar();
  29986. const v5 = float( v5_immutable ).toVar();
  29987. const v4 = float( v4_immutable ).toVar();
  29988. const v3 = float( v3_immutable ).toVar();
  29989. const v2 = float( v2_immutable ).toVar();
  29990. const v1 = float( v1_immutable ).toVar();
  29991. const v0 = float( v0_immutable ).toVar();
  29992. const s1 = float( sub( 1.0, s ) ).toVar();
  29993. const t1 = float( sub( 1.0, t ) ).toVar();
  29994. const r1 = float( sub( 1.0, r ) ).toVar();
  29995. 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 ) ) ) ) ) );
  29996. } ).setLayout( {
  29997. name: 'mx_trilerp_0',
  29998. type: 'float',
  29999. inputs: [
  30000. { name: 'v0', type: 'float' },
  30001. { name: 'v1', type: 'float' },
  30002. { name: 'v2', type: 'float' },
  30003. { name: 'v3', type: 'float' },
  30004. { name: 'v4', type: 'float' },
  30005. { name: 'v5', type: 'float' },
  30006. { name: 'v6', type: 'float' },
  30007. { name: 'v7', type: 'float' },
  30008. { name: 's', type: 'float' },
  30009. { name: 't', type: 'float' },
  30010. { name: 'r', type: 'float' }
  30011. ]
  30012. } );
  30013. 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 ] ) => {
  30014. const r = float( r_immutable ).toVar();
  30015. const t = float( t_immutable ).toVar();
  30016. const s = float( s_immutable ).toVar();
  30017. const v7 = vec3( v7_immutable ).toVar();
  30018. const v6 = vec3( v6_immutable ).toVar();
  30019. const v5 = vec3( v5_immutable ).toVar();
  30020. const v4 = vec3( v4_immutable ).toVar();
  30021. const v3 = vec3( v3_immutable ).toVar();
  30022. const v2 = vec3( v2_immutable ).toVar();
  30023. const v1 = vec3( v1_immutable ).toVar();
  30024. const v0 = vec3( v0_immutable ).toVar();
  30025. const s1 = float( sub( 1.0, s ) ).toVar();
  30026. const t1 = float( sub( 1.0, t ) ).toVar();
  30027. const r1 = float( sub( 1.0, r ) ).toVar();
  30028. 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 ) ) ) ) ) );
  30029. } ).setLayout( {
  30030. name: 'mx_trilerp_1',
  30031. type: 'vec3',
  30032. inputs: [
  30033. { name: 'v0', type: 'vec3' },
  30034. { name: 'v1', type: 'vec3' },
  30035. { name: 'v2', type: 'vec3' },
  30036. { name: 'v3', type: 'vec3' },
  30037. { name: 'v4', type: 'vec3' },
  30038. { name: 'v5', type: 'vec3' },
  30039. { name: 'v6', type: 'vec3' },
  30040. { name: 'v7', type: 'vec3' },
  30041. { name: 's', type: 'float' },
  30042. { name: 't', type: 'float' },
  30043. { name: 'r', type: 'float' }
  30044. ]
  30045. } );
  30046. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  30047. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30048. const y = float( y_immutable ).toVar();
  30049. const x = float( x_immutable ).toVar();
  30050. const hash = uint( hash_immutable ).toVar();
  30051. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  30052. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  30053. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  30054. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30055. } ).setLayout( {
  30056. name: 'mx_gradient_float_0',
  30057. type: 'float',
  30058. inputs: [
  30059. { name: 'hash', type: 'uint' },
  30060. { name: 'x', type: 'float' },
  30061. { name: 'y', type: 'float' }
  30062. ]
  30063. } );
  30064. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30065. const z = float( z_immutable ).toVar();
  30066. const y = float( y_immutable ).toVar();
  30067. const x = float( x_immutable ).toVar();
  30068. const hash = uint( hash_immutable ).toVar();
  30069. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  30070. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  30071. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  30072. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30073. } ).setLayout( {
  30074. name: 'mx_gradient_float_1',
  30075. type: 'float',
  30076. inputs: [
  30077. { name: 'hash', type: 'uint' },
  30078. { name: 'x', type: 'float' },
  30079. { name: 'y', type: 'float' },
  30080. { name: 'z', type: 'float' }
  30081. ]
  30082. } );
  30083. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  30084. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30085. const y = float( y_immutable ).toVar();
  30086. const x = float( x_immutable ).toVar();
  30087. const hash = uvec3( hash_immutable ).toVar();
  30088. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  30089. } ).setLayout( {
  30090. name: 'mx_gradient_vec3_0',
  30091. type: 'vec3',
  30092. inputs: [
  30093. { name: 'hash', type: 'uvec3' },
  30094. { name: 'x', type: 'float' },
  30095. { name: 'y', type: 'float' }
  30096. ]
  30097. } );
  30098. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30099. const z = float( z_immutable ).toVar();
  30100. const y = float( y_immutable ).toVar();
  30101. const x = float( x_immutable ).toVar();
  30102. const hash = uvec3( hash_immutable ).toVar();
  30103. 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 ) );
  30104. } ).setLayout( {
  30105. name: 'mx_gradient_vec3_1',
  30106. type: 'vec3',
  30107. inputs: [
  30108. { name: 'hash', type: 'uvec3' },
  30109. { name: 'x', type: 'float' },
  30110. { name: 'y', type: 'float' },
  30111. { name: 'z', type: 'float' }
  30112. ]
  30113. } );
  30114. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  30115. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30116. const v = float( v_immutable ).toVar();
  30117. return mul( 0.6616, v );
  30118. } ).setLayout( {
  30119. name: 'mx_gradient_scale2d_0',
  30120. type: 'float',
  30121. inputs: [
  30122. { name: 'v', type: 'float' }
  30123. ]
  30124. } );
  30125. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30126. const v = float( v_immutable ).toVar();
  30127. return mul( 0.9820, v );
  30128. } ).setLayout( {
  30129. name: 'mx_gradient_scale3d_0',
  30130. type: 'float',
  30131. inputs: [
  30132. { name: 'v', type: 'float' }
  30133. ]
  30134. } );
  30135. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30136. const v = vec3( v_immutable ).toVar();
  30137. return mul( 0.6616, v );
  30138. } ).setLayout( {
  30139. name: 'mx_gradient_scale2d_1',
  30140. type: 'vec3',
  30141. inputs: [
  30142. { name: 'v', type: 'vec3' }
  30143. ]
  30144. } );
  30145. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  30146. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30147. const v = vec3( v_immutable ).toVar();
  30148. return mul( 0.9820, v );
  30149. } ).setLayout( {
  30150. name: 'mx_gradient_scale3d_1',
  30151. type: 'vec3',
  30152. inputs: [
  30153. { name: 'v', type: 'vec3' }
  30154. ]
  30155. } );
  30156. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  30157. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  30158. const k = int( k_immutable ).toVar();
  30159. const x = uint( x_immutable ).toVar();
  30160. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  30161. } ).setLayout( {
  30162. name: 'mx_rotl32',
  30163. type: 'uint',
  30164. inputs: [
  30165. { name: 'x', type: 'uint' },
  30166. { name: 'k', type: 'int' }
  30167. ]
  30168. } );
  30169. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  30170. a.subAssign( c );
  30171. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  30172. c.addAssign( b );
  30173. b.subAssign( a );
  30174. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  30175. a.addAssign( c );
  30176. c.subAssign( b );
  30177. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  30178. b.addAssign( a );
  30179. a.subAssign( c );
  30180. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  30181. c.addAssign( b );
  30182. b.subAssign( a );
  30183. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  30184. a.addAssign( c );
  30185. c.subAssign( b );
  30186. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  30187. b.addAssign( a );
  30188. } );
  30189. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  30190. const c = uint( c_immutable ).toVar();
  30191. const b = uint( b_immutable ).toVar();
  30192. const a = uint( a_immutable ).toVar();
  30193. c.bitXorAssign( b );
  30194. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  30195. a.bitXorAssign( c );
  30196. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  30197. b.bitXorAssign( a );
  30198. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  30199. c.bitXorAssign( b );
  30200. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  30201. a.bitXorAssign( c );
  30202. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  30203. b.bitXorAssign( a );
  30204. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  30205. c.bitXorAssign( b );
  30206. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  30207. return c;
  30208. } ).setLayout( {
  30209. name: 'mx_bjfinal',
  30210. type: 'uint',
  30211. inputs: [
  30212. { name: 'a', type: 'uint' },
  30213. { name: 'b', type: 'uint' },
  30214. { name: 'c', type: 'uint' }
  30215. ]
  30216. } );
  30217. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  30218. const bits = uint( bits_immutable ).toVar();
  30219. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  30220. } ).setLayout( {
  30221. name: 'mx_bits_to_01',
  30222. type: 'float',
  30223. inputs: [
  30224. { name: 'bits', type: 'uint' }
  30225. ]
  30226. } );
  30227. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  30228. const t = float( t_immutable ).toVar();
  30229. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  30230. } ).setLayout( {
  30231. name: 'mx_fade',
  30232. type: 'float',
  30233. inputs: [
  30234. { name: 't', type: 'float' }
  30235. ]
  30236. } );
  30237. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30238. const x = int( x_immutable ).toVar();
  30239. const len = uint( uint( 1 ) ).toVar();
  30240. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  30241. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  30242. } ).setLayout( {
  30243. name: 'mx_hash_int_0',
  30244. type: 'uint',
  30245. inputs: [
  30246. { name: 'x', type: 'int' }
  30247. ]
  30248. } );
  30249. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30250. const y = int( y_immutable ).toVar();
  30251. const x = int( x_immutable ).toVar();
  30252. const len = uint( uint( 2 ) ).toVar();
  30253. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30254. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30255. a.addAssign( uint( x ) );
  30256. b.addAssign( uint( y ) );
  30257. return mx_bjfinal( a, b, c );
  30258. } ).setLayout( {
  30259. name: 'mx_hash_int_1',
  30260. type: 'uint',
  30261. inputs: [
  30262. { name: 'x', type: 'int' },
  30263. { name: 'y', type: 'int' }
  30264. ]
  30265. } );
  30266. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30267. const z = int( z_immutable ).toVar();
  30268. const y = int( y_immutable ).toVar();
  30269. const x = int( x_immutable ).toVar();
  30270. const len = uint( uint( 3 ) ).toVar();
  30271. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30272. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30273. a.addAssign( uint( x ) );
  30274. b.addAssign( uint( y ) );
  30275. c.addAssign( uint( z ) );
  30276. return mx_bjfinal( a, b, c );
  30277. } ).setLayout( {
  30278. name: 'mx_hash_int_2',
  30279. type: 'uint',
  30280. inputs: [
  30281. { name: 'x', type: 'int' },
  30282. { name: 'y', type: 'int' },
  30283. { name: 'z', type: 'int' }
  30284. ]
  30285. } );
  30286. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  30287. const xx = int( xx_immutable ).toVar();
  30288. const z = int( z_immutable ).toVar();
  30289. const y = int( y_immutable ).toVar();
  30290. const x = int( x_immutable ).toVar();
  30291. const len = uint( uint( 4 ) ).toVar();
  30292. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30293. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30294. a.addAssign( uint( x ) );
  30295. b.addAssign( uint( y ) );
  30296. c.addAssign( uint( z ) );
  30297. mx_bjmix( a, b, c );
  30298. a.addAssign( uint( xx ) );
  30299. return mx_bjfinal( a, b, c );
  30300. } ).setLayout( {
  30301. name: 'mx_hash_int_3',
  30302. type: 'uint',
  30303. inputs: [
  30304. { name: 'x', type: 'int' },
  30305. { name: 'y', type: 'int' },
  30306. { name: 'z', type: 'int' },
  30307. { name: 'xx', type: 'int' }
  30308. ]
  30309. } );
  30310. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  30311. const yy = int( yy_immutable ).toVar();
  30312. const xx = int( xx_immutable ).toVar();
  30313. const z = int( z_immutable ).toVar();
  30314. const y = int( y_immutable ).toVar();
  30315. const x = int( x_immutable ).toVar();
  30316. const len = uint( uint( 5 ) ).toVar();
  30317. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30318. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30319. a.addAssign( uint( x ) );
  30320. b.addAssign( uint( y ) );
  30321. c.addAssign( uint( z ) );
  30322. mx_bjmix( a, b, c );
  30323. a.addAssign( uint( xx ) );
  30324. b.addAssign( uint( yy ) );
  30325. return mx_bjfinal( a, b, c );
  30326. } ).setLayout( {
  30327. name: 'mx_hash_int_4',
  30328. type: 'uint',
  30329. inputs: [
  30330. { name: 'x', type: 'int' },
  30331. { name: 'y', type: 'int' },
  30332. { name: 'z', type: 'int' },
  30333. { name: 'xx', type: 'int' },
  30334. { name: 'yy', type: 'int' }
  30335. ]
  30336. } );
  30337. 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 ] );
  30338. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30339. const y = int( y_immutable ).toVar();
  30340. const x = int( x_immutable ).toVar();
  30341. const h = uint( mx_hash_int( x, y ) ).toVar();
  30342. const result = uvec3().toVar();
  30343. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30344. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30345. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30346. return result;
  30347. } ).setLayout( {
  30348. name: 'mx_hash_vec3_0',
  30349. type: 'uvec3',
  30350. inputs: [
  30351. { name: 'x', type: 'int' },
  30352. { name: 'y', type: 'int' }
  30353. ]
  30354. } );
  30355. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30356. const z = int( z_immutable ).toVar();
  30357. const y = int( y_immutable ).toVar();
  30358. const x = int( x_immutable ).toVar();
  30359. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  30360. const result = uvec3().toVar();
  30361. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30362. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30363. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30364. return result;
  30365. } ).setLayout( {
  30366. name: 'mx_hash_vec3_1',
  30367. type: 'uvec3',
  30368. inputs: [
  30369. { name: 'x', type: 'int' },
  30370. { name: 'y', type: 'int' },
  30371. { name: 'z', type: 'int' }
  30372. ]
  30373. } );
  30374. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  30375. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30376. const p = vec2( p_immutable ).toVar();
  30377. const X = int().toVar(), Y = int().toVar();
  30378. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30379. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30380. const u = float( mx_fade( fx ) ).toVar();
  30381. const v = float( mx_fade( fy ) ).toVar();
  30382. 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();
  30383. return mx_gradient_scale2d( result );
  30384. } ).setLayout( {
  30385. name: 'mx_perlin_noise_float_0',
  30386. type: 'float',
  30387. inputs: [
  30388. { name: 'p', type: 'vec2' }
  30389. ]
  30390. } );
  30391. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30392. const p = vec3( p_immutable ).toVar();
  30393. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30394. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30395. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30396. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  30397. const u = float( mx_fade( fx ) ).toVar();
  30398. const v = float( mx_fade( fy ) ).toVar();
  30399. const w = float( mx_fade( fz ) ).toVar();
  30400. 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();
  30401. return mx_gradient_scale3d( result );
  30402. } ).setLayout( {
  30403. name: 'mx_perlin_noise_float_1',
  30404. type: 'float',
  30405. inputs: [
  30406. { name: 'p', type: 'vec3' }
  30407. ]
  30408. } );
  30409. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  30410. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30411. const p = vec2( p_immutable ).toVar();
  30412. const X = int().toVar(), Y = int().toVar();
  30413. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30414. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30415. const u = float( mx_fade( fx ) ).toVar();
  30416. const v = float( mx_fade( fy ) ).toVar();
  30417. 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();
  30418. return mx_gradient_scale2d( result );
  30419. } ).setLayout( {
  30420. name: 'mx_perlin_noise_vec3_0',
  30421. type: 'vec3',
  30422. inputs: [
  30423. { name: 'p', type: 'vec2' }
  30424. ]
  30425. } );
  30426. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30427. const p = vec3( p_immutable ).toVar();
  30428. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30429. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30430. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30431. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  30432. const u = float( mx_fade( fx ) ).toVar();
  30433. const v = float( mx_fade( fy ) ).toVar();
  30434. const w = float( mx_fade( fz ) ).toVar();
  30435. 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();
  30436. return mx_gradient_scale3d( result );
  30437. } ).setLayout( {
  30438. name: 'mx_perlin_noise_vec3_1',
  30439. type: 'vec3',
  30440. inputs: [
  30441. { name: 'p', type: 'vec3' }
  30442. ]
  30443. } );
  30444. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  30445. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30446. const p = float( p_immutable ).toVar();
  30447. const ix = int( mx_floor( p ) ).toVar();
  30448. return mx_bits_to_01( mx_hash_int( ix ) );
  30449. } ).setLayout( {
  30450. name: 'mx_cell_noise_float_0',
  30451. type: 'float',
  30452. inputs: [
  30453. { name: 'p', type: 'float' }
  30454. ]
  30455. } );
  30456. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30457. const p = vec2( p_immutable ).toVar();
  30458. const ix = int( mx_floor( p.x ) ).toVar();
  30459. const iy = int( mx_floor( p.y ) ).toVar();
  30460. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  30461. } ).setLayout( {
  30462. name: 'mx_cell_noise_float_1',
  30463. type: 'float',
  30464. inputs: [
  30465. { name: 'p', type: 'vec2' }
  30466. ]
  30467. } );
  30468. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30469. const p = vec3( p_immutable ).toVar();
  30470. const ix = int( mx_floor( p.x ) ).toVar();
  30471. const iy = int( mx_floor( p.y ) ).toVar();
  30472. const iz = int( mx_floor( p.z ) ).toVar();
  30473. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  30474. } ).setLayout( {
  30475. name: 'mx_cell_noise_float_2',
  30476. type: 'float',
  30477. inputs: [
  30478. { name: 'p', type: 'vec3' }
  30479. ]
  30480. } );
  30481. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30482. const p = vec4( p_immutable ).toVar();
  30483. const ix = int( mx_floor( p.x ) ).toVar();
  30484. const iy = int( mx_floor( p.y ) ).toVar();
  30485. const iz = int( mx_floor( p.z ) ).toVar();
  30486. const iw = int( mx_floor( p.w ) ).toVar();
  30487. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  30488. } ).setLayout( {
  30489. name: 'mx_cell_noise_float_3',
  30490. type: 'float',
  30491. inputs: [
  30492. { name: 'p', type: 'vec4' }
  30493. ]
  30494. } );
  30495. 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 ] );
  30496. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30497. const p = float( p_immutable ).toVar();
  30498. const ix = int( mx_floor( p ) ).toVar();
  30499. 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 ) ) ) );
  30500. } ).setLayout( {
  30501. name: 'mx_cell_noise_vec3_0',
  30502. type: 'vec3',
  30503. inputs: [
  30504. { name: 'p', type: 'float' }
  30505. ]
  30506. } );
  30507. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30508. const p = vec2( p_immutable ).toVar();
  30509. const ix = int( mx_floor( p.x ) ).toVar();
  30510. const iy = int( mx_floor( p.y ) ).toVar();
  30511. 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 ) ) ) );
  30512. } ).setLayout( {
  30513. name: 'mx_cell_noise_vec3_1',
  30514. type: 'vec3',
  30515. inputs: [
  30516. { name: 'p', type: 'vec2' }
  30517. ]
  30518. } );
  30519. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30520. const p = vec3( p_immutable ).toVar();
  30521. const ix = int( mx_floor( p.x ) ).toVar();
  30522. const iy = int( mx_floor( p.y ) ).toVar();
  30523. const iz = int( mx_floor( p.z ) ).toVar();
  30524. 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 ) ) ) );
  30525. } ).setLayout( {
  30526. name: 'mx_cell_noise_vec3_2',
  30527. type: 'vec3',
  30528. inputs: [
  30529. { name: 'p', type: 'vec3' }
  30530. ]
  30531. } );
  30532. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30533. const p = vec4( p_immutable ).toVar();
  30534. const ix = int( mx_floor( p.x ) ).toVar();
  30535. const iy = int( mx_floor( p.y ) ).toVar();
  30536. const iz = int( mx_floor( p.z ) ).toVar();
  30537. const iw = int( mx_floor( p.w ) ).toVar();
  30538. 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 ) ) ) );
  30539. } ).setLayout( {
  30540. name: 'mx_cell_noise_vec3_3',
  30541. type: 'vec3',
  30542. inputs: [
  30543. { name: 'p', type: 'vec4' }
  30544. ]
  30545. } );
  30546. 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 ] );
  30547. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30548. const diminish = float( diminish_immutable ).toVar();
  30549. const lacunarity = float( lacunarity_immutable ).toVar();
  30550. const octaves = int( octaves_immutable ).toVar();
  30551. const p = vec3( p_immutable ).toVar();
  30552. const result = float( 0.0 ).toVar();
  30553. const amplitude = float( 1.0 ).toVar();
  30554. Loop( octaves, () => {
  30555. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  30556. amplitude.mulAssign( diminish );
  30557. p.mulAssign( lacunarity );
  30558. } );
  30559. return result;
  30560. } ).setLayout( {
  30561. name: 'mx_fractal_noise_float',
  30562. type: 'float',
  30563. inputs: [
  30564. { name: 'p', type: 'vec3' },
  30565. { name: 'octaves', type: 'int' },
  30566. { name: 'lacunarity', type: 'float' },
  30567. { name: 'diminish', type: 'float' }
  30568. ]
  30569. } );
  30570. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30571. const diminish = float( diminish_immutable ).toVar();
  30572. const lacunarity = float( lacunarity_immutable ).toVar();
  30573. const octaves = int( octaves_immutable ).toVar();
  30574. const p = vec3( p_immutable ).toVar();
  30575. const result = vec3( 0.0 ).toVar();
  30576. const amplitude = float( 1.0 ).toVar();
  30577. Loop( octaves, () => {
  30578. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  30579. amplitude.mulAssign( diminish );
  30580. p.mulAssign( lacunarity );
  30581. } );
  30582. return result;
  30583. } ).setLayout( {
  30584. name: 'mx_fractal_noise_vec3',
  30585. type: 'vec3',
  30586. inputs: [
  30587. { name: 'p', type: 'vec3' },
  30588. { name: 'octaves', type: 'int' },
  30589. { name: 'lacunarity', type: 'float' },
  30590. { name: 'diminish', type: 'float' }
  30591. ]
  30592. } );
  30593. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30594. const diminish = float( diminish_immutable ).toVar();
  30595. const lacunarity = float( lacunarity_immutable ).toVar();
  30596. const octaves = int( octaves_immutable ).toVar();
  30597. const p = vec3( p_immutable ).toVar();
  30598. 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 ) );
  30599. } ).setLayout( {
  30600. name: 'mx_fractal_noise_vec2',
  30601. type: 'vec2',
  30602. inputs: [
  30603. { name: 'p', type: 'vec3' },
  30604. { name: 'octaves', type: 'int' },
  30605. { name: 'lacunarity', type: 'float' },
  30606. { name: 'diminish', type: 'float' }
  30607. ]
  30608. } );
  30609. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30610. const diminish = float( diminish_immutable ).toVar();
  30611. const lacunarity = float( lacunarity_immutable ).toVar();
  30612. const octaves = int( octaves_immutable ).toVar();
  30613. const p = vec3( p_immutable ).toVar();
  30614. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  30615. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  30616. return vec4( c, f );
  30617. } ).setLayout( {
  30618. name: 'mx_fractal_noise_vec4',
  30619. type: 'vec4',
  30620. inputs: [
  30621. { name: 'p', type: 'vec3' },
  30622. { name: 'octaves', type: 'int' },
  30623. { name: 'lacunarity', type: 'float' },
  30624. { name: 'diminish', type: 'float' }
  30625. ]
  30626. } );
  30627. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  30628. const metric = int( metric_immutable ).toVar();
  30629. const jitter = float( jitter_immutable ).toVar();
  30630. const yoff = int( yoff_immutable ).toVar();
  30631. const xoff = int( xoff_immutable ).toVar();
  30632. const y = int( y_immutable ).toVar();
  30633. const x = int( x_immutable ).toVar();
  30634. const p = vec2( p_immutable ).toVar();
  30635. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  30636. const off = vec2( tmp.x, tmp.y ).toVar();
  30637. off.subAssign( 0.5 );
  30638. off.mulAssign( jitter );
  30639. off.addAssign( 0.5 );
  30640. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  30641. const diff = vec2( cellpos.sub( p ) ).toVar();
  30642. If( metric.equal( int( 2 ) ), () => {
  30643. return abs( diff.x ).add( abs( diff.y ) );
  30644. } );
  30645. If( metric.equal( int( 3 ) ), () => {
  30646. return max$1( abs( diff.x ), abs( diff.y ) );
  30647. } );
  30648. return dot( diff, diff );
  30649. } ).setLayout( {
  30650. name: 'mx_worley_distance_0',
  30651. type: 'float',
  30652. inputs: [
  30653. { name: 'p', type: 'vec2' },
  30654. { name: 'x', type: 'int' },
  30655. { name: 'y', type: 'int' },
  30656. { name: 'xoff', type: 'int' },
  30657. { name: 'yoff', type: 'int' },
  30658. { name: 'jitter', type: 'float' },
  30659. { name: 'metric', type: 'int' }
  30660. ]
  30661. } );
  30662. 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 ] ) => {
  30663. const metric = int( metric_immutable ).toVar();
  30664. const jitter = float( jitter_immutable ).toVar();
  30665. const zoff = int( zoff_immutable ).toVar();
  30666. const yoff = int( yoff_immutable ).toVar();
  30667. const xoff = int( xoff_immutable ).toVar();
  30668. const z = int( z_immutable ).toVar();
  30669. const y = int( y_immutable ).toVar();
  30670. const x = int( x_immutable ).toVar();
  30671. const p = vec3( p_immutable ).toVar();
  30672. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  30673. off.subAssign( 0.5 );
  30674. off.mulAssign( jitter );
  30675. off.addAssign( 0.5 );
  30676. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  30677. const diff = vec3( cellpos.sub( p ) ).toVar();
  30678. If( metric.equal( int( 2 ) ), () => {
  30679. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  30680. } );
  30681. If( metric.equal( int( 3 ) ), () => {
  30682. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  30683. } );
  30684. return dot( diff, diff );
  30685. } ).setLayout( {
  30686. name: 'mx_worley_distance_1',
  30687. type: 'float',
  30688. inputs: [
  30689. { name: 'p', type: 'vec3' },
  30690. { name: 'x', type: 'int' },
  30691. { name: 'y', type: 'int' },
  30692. { name: 'z', type: 'int' },
  30693. { name: 'xoff', type: 'int' },
  30694. { name: 'yoff', type: 'int' },
  30695. { name: 'zoff', type: 'int' },
  30696. { name: 'jitter', type: 'float' },
  30697. { name: 'metric', type: 'int' }
  30698. ]
  30699. } );
  30700. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  30701. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30702. const metric = int( metric_immutable ).toVar();
  30703. const jitter = float( jitter_immutable ).toVar();
  30704. const p = vec2( p_immutable ).toVar();
  30705. const X = int().toVar(), Y = int().toVar();
  30706. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30707. const sqdist = float( 1e6 ).toVar();
  30708. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30709. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30710. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30711. sqdist.assign( min$1( sqdist, dist ) );
  30712. } );
  30713. } );
  30714. If( metric.equal( int( 0 ) ), () => {
  30715. sqdist.assign( sqrt( sqdist ) );
  30716. } );
  30717. return sqdist;
  30718. } ).setLayout( {
  30719. name: 'mx_worley_noise_float_0',
  30720. type: 'float',
  30721. inputs: [
  30722. { name: 'p', type: 'vec2' },
  30723. { name: 'jitter', type: 'float' },
  30724. { name: 'metric', type: 'int' }
  30725. ]
  30726. } );
  30727. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30728. const metric = int( metric_immutable ).toVar();
  30729. const jitter = float( jitter_immutable ).toVar();
  30730. const p = vec2( p_immutable ).toVar();
  30731. const X = int().toVar(), Y = int().toVar();
  30732. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30733. const sqdist = vec2( 1e6, 1e6 ).toVar();
  30734. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30735. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30736. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30737. If( dist.lessThan( sqdist.x ), () => {
  30738. sqdist.y.assign( sqdist.x );
  30739. sqdist.x.assign( dist );
  30740. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30741. sqdist.y.assign( dist );
  30742. } );
  30743. } );
  30744. } );
  30745. If( metric.equal( int( 0 ) ), () => {
  30746. sqdist.assign( sqrt( sqdist ) );
  30747. } );
  30748. return sqdist;
  30749. } ).setLayout( {
  30750. name: 'mx_worley_noise_vec2_0',
  30751. type: 'vec2',
  30752. inputs: [
  30753. { name: 'p', type: 'vec2' },
  30754. { name: 'jitter', type: 'float' },
  30755. { name: 'metric', type: 'int' }
  30756. ]
  30757. } );
  30758. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30759. const metric = int( metric_immutable ).toVar();
  30760. const jitter = float( jitter_immutable ).toVar();
  30761. const p = vec2( p_immutable ).toVar();
  30762. const X = int().toVar(), Y = int().toVar();
  30763. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30764. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  30765. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30766. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30767. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30768. If( dist.lessThan( sqdist.x ), () => {
  30769. sqdist.z.assign( sqdist.y );
  30770. sqdist.y.assign( sqdist.x );
  30771. sqdist.x.assign( dist );
  30772. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30773. sqdist.z.assign( sqdist.y );
  30774. sqdist.y.assign( dist );
  30775. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  30776. sqdist.z.assign( dist );
  30777. } );
  30778. } );
  30779. } );
  30780. If( metric.equal( int( 0 ) ), () => {
  30781. sqdist.assign( sqrt( sqdist ) );
  30782. } );
  30783. return sqdist;
  30784. } ).setLayout( {
  30785. name: 'mx_worley_noise_vec3_0',
  30786. type: 'vec3',
  30787. inputs: [
  30788. { name: 'p', type: 'vec2' },
  30789. { name: 'jitter', type: 'float' },
  30790. { name: 'metric', type: 'int' }
  30791. ]
  30792. } );
  30793. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30794. const metric = int( metric_immutable ).toVar();
  30795. const jitter = float( jitter_immutable ).toVar();
  30796. const p = vec3( p_immutable ).toVar();
  30797. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30798. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30799. const sqdist = float( 1e6 ).toVar();
  30800. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30801. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30802. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30803. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30804. sqdist.assign( min$1( sqdist, dist ) );
  30805. } );
  30806. } );
  30807. } );
  30808. If( metric.equal( int( 0 ) ), () => {
  30809. sqdist.assign( sqrt( sqdist ) );
  30810. } );
  30811. return sqdist;
  30812. } ).setLayout( {
  30813. name: 'mx_worley_noise_float_1',
  30814. type: 'float',
  30815. inputs: [
  30816. { name: 'p', type: 'vec3' },
  30817. { name: 'jitter', type: 'float' },
  30818. { name: 'metric', type: 'int' }
  30819. ]
  30820. } );
  30821. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  30822. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30823. const metric = int( metric_immutable ).toVar();
  30824. const jitter = float( jitter_immutable ).toVar();
  30825. const p = vec3( p_immutable ).toVar();
  30826. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30827. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30828. const sqdist = vec2( 1e6, 1e6 ).toVar();
  30829. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30830. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30831. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30832. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30833. If( dist.lessThan( sqdist.x ), () => {
  30834. sqdist.y.assign( sqdist.x );
  30835. sqdist.x.assign( dist );
  30836. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30837. sqdist.y.assign( dist );
  30838. } );
  30839. } );
  30840. } );
  30841. } );
  30842. If( metric.equal( int( 0 ) ), () => {
  30843. sqdist.assign( sqrt( sqdist ) );
  30844. } );
  30845. return sqdist;
  30846. } ).setLayout( {
  30847. name: 'mx_worley_noise_vec2_1',
  30848. type: 'vec2',
  30849. inputs: [
  30850. { name: 'p', type: 'vec3' },
  30851. { name: 'jitter', type: 'float' },
  30852. { name: 'metric', type: 'int' }
  30853. ]
  30854. } );
  30855. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  30856. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30857. const metric = int( metric_immutable ).toVar();
  30858. const jitter = float( jitter_immutable ).toVar();
  30859. const p = vec3( p_immutable ).toVar();
  30860. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30861. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30862. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  30863. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30864. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30865. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30866. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30867. If( dist.lessThan( sqdist.x ), () => {
  30868. sqdist.z.assign( sqdist.y );
  30869. sqdist.y.assign( sqdist.x );
  30870. sqdist.x.assign( dist );
  30871. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30872. sqdist.z.assign( sqdist.y );
  30873. sqdist.y.assign( dist );
  30874. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  30875. sqdist.z.assign( dist );
  30876. } );
  30877. } );
  30878. } );
  30879. } );
  30880. If( metric.equal( int( 0 ) ), () => {
  30881. sqdist.assign( sqrt( sqdist ) );
  30882. } );
  30883. return sqdist;
  30884. } ).setLayout( {
  30885. name: 'mx_worley_noise_vec3_1',
  30886. type: 'vec3',
  30887. inputs: [
  30888. { name: 'p', type: 'vec3' },
  30889. { name: 'jitter', type: 'float' },
  30890. { name: 'metric', type: 'int' }
  30891. ]
  30892. } );
  30893. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  30894. // Unified Noise 2D
  30895. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  30896. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  30897. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  30898. octaves_immutable, lacunarity_immutable, diminish_immutable
  30899. ] ) => {
  30900. const noiseType = int( noiseType_immutable ).toVar();
  30901. const texcoord = vec2( texcoord_immutable ).toVar();
  30902. const freq = vec2( freq_immutable ).toVar();
  30903. const offset = vec2( offset_immutable ).toVar();
  30904. const jitter = float( jitter_immutable ).toVar();
  30905. const outmin = float( outmin_immutable ).toVar();
  30906. const outmax = float( outmax_immutable ).toVar();
  30907. const clampoutput = bool( clampoutput_immutable ).toVar();
  30908. const octaves = int( octaves_immutable ).toVar();
  30909. const lacunarity = float( lacunarity_immutable ).toVar();
  30910. const diminish = float( diminish_immutable ).toVar();
  30911. // Compute input position
  30912. const p = texcoord.mul( freq ).add( offset );
  30913. const result = float( 0.0 ).toVar();
  30914. // Perlin
  30915. If( noiseType.equal( int( 0 ) ), () => {
  30916. result.assign( mx_perlin_noise_vec3( p ) );
  30917. } );
  30918. // Cell
  30919. If( noiseType.equal( int( 1 ) ), () => {
  30920. result.assign( mx_cell_noise_vec3( p ) );
  30921. } );
  30922. // Worley (metric=0 = euclidean)
  30923. If( noiseType.equal( int( 2 ) ), () => {
  30924. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  30925. } );
  30926. // Fractal (use vec3(p, 0.0) for 2D input)
  30927. If( noiseType.equal( int( 3 ) ), () => {
  30928. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  30929. } );
  30930. // Remap output to [outmin, outmax]
  30931. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  30932. // Clamp if requested
  30933. If( clampoutput, () => {
  30934. result.assign( clamp( result, outmin, outmax ) );
  30935. } );
  30936. return result;
  30937. } ).setLayout( {
  30938. name: 'mx_unifiednoise2d',
  30939. type: 'float',
  30940. inputs: [
  30941. { name: 'noiseType', type: 'int' },
  30942. { name: 'texcoord', type: 'vec2' },
  30943. { name: 'freq', type: 'vec2' },
  30944. { name: 'offset', type: 'vec2' },
  30945. { name: 'jitter', type: 'float' },
  30946. { name: 'outmin', type: 'float' },
  30947. { name: 'outmax', type: 'float' },
  30948. { name: 'clampoutput', type: 'bool' },
  30949. { name: 'octaves', type: 'int' },
  30950. { name: 'lacunarity', type: 'float' },
  30951. { name: 'diminish', type: 'float' }
  30952. ]
  30953. } );
  30954. // Unified Noise 3D
  30955. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  30956. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  30957. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  30958. octaves_immutable, lacunarity_immutable, diminish_immutable
  30959. ] ) => {
  30960. const noiseType = int( noiseType_immutable ).toVar();
  30961. const position = vec3( position_immutable ).toVar();
  30962. const freq = vec3( freq_immutable ).toVar();
  30963. const offset = vec3( offset_immutable ).toVar();
  30964. const jitter = float( jitter_immutable ).toVar();
  30965. const outmin = float( outmin_immutable ).toVar();
  30966. const outmax = float( outmax_immutable ).toVar();
  30967. const clampoutput = bool( clampoutput_immutable ).toVar();
  30968. const octaves = int( octaves_immutable ).toVar();
  30969. const lacunarity = float( lacunarity_immutable ).toVar();
  30970. const diminish = float( diminish_immutable ).toVar();
  30971. // Compute input position
  30972. const p = position.mul( freq ).add( offset );
  30973. const result = float( 0.0 ).toVar();
  30974. // Perlin
  30975. If( noiseType.equal( int( 0 ) ), () => {
  30976. result.assign( mx_perlin_noise_vec3( p ) );
  30977. } );
  30978. // Cell
  30979. If( noiseType.equal( int( 1 ) ), () => {
  30980. result.assign( mx_cell_noise_vec3( p ) );
  30981. } );
  30982. // Worley (metric=0 = euclidean)
  30983. If( noiseType.equal( int( 2 ) ), () => {
  30984. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  30985. } );
  30986. // Fractal
  30987. If( noiseType.equal( int( 3 ) ), () => {
  30988. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  30989. } );
  30990. // Remap output to [outmin, outmax]
  30991. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  30992. // Clamp if requested
  30993. If( clampoutput, () => {
  30994. result.assign( clamp( result, outmin, outmax ) );
  30995. } );
  30996. return result;
  30997. } ).setLayout( {
  30998. name: 'mx_unifiednoise3d',
  30999. type: 'float',
  31000. inputs: [
  31001. { name: 'noiseType', type: 'int' },
  31002. { name: 'position', type: 'vec3' },
  31003. { name: 'freq', type: 'vec3' },
  31004. { name: 'offset', type: 'vec3' },
  31005. { name: 'jitter', type: 'float' },
  31006. { name: 'outmin', type: 'float' },
  31007. { name: 'outmax', type: 'float' },
  31008. { name: 'clampoutput', type: 'bool' },
  31009. { name: 'octaves', type: 'int' },
  31010. { name: 'lacunarity', type: 'float' },
  31011. { name: 'diminish', type: 'float' }
  31012. ]
  31013. } );
  31014. // Three.js Transpiler
  31015. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  31016. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  31017. const s = hsv.y;
  31018. const v = hsv.z;
  31019. const result = vec3().toVar();
  31020. If( s.lessThan( 0.0001 ), () => {
  31021. result.assign( vec3( v, v, v ) );
  31022. } ).Else( () => {
  31023. let h = hsv.x;
  31024. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  31025. const hi = int( trunc( h ) );
  31026. const f = h.sub( float( hi ) );
  31027. const p = v.mul( s.oneMinus() );
  31028. const q = v.mul( s.mul( f ).oneMinus() );
  31029. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  31030. If( hi.equal( int( 0 ) ), () => {
  31031. result.assign( vec3( v, t, p ) );
  31032. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  31033. result.assign( vec3( q, v, p ) );
  31034. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  31035. result.assign( vec3( p, v, t ) );
  31036. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  31037. result.assign( vec3( p, q, v ) );
  31038. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  31039. result.assign( vec3( t, p, v ) );
  31040. } ).Else( () => {
  31041. result.assign( vec3( v, p, q ) );
  31042. } );
  31043. } );
  31044. return result;
  31045. } ).setLayout( {
  31046. name: 'mx_hsvtorgb',
  31047. type: 'vec3',
  31048. inputs: [
  31049. { name: 'hsv', type: 'vec3' }
  31050. ]
  31051. } );
  31052. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  31053. const c = vec3( c_immutable ).toVar();
  31054. const r = float( c.x ).toVar();
  31055. const g = float( c.y ).toVar();
  31056. const b = float( c.z ).toVar();
  31057. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  31058. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  31059. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  31060. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  31061. v.assign( maxcomp );
  31062. If( maxcomp.greaterThan( 0.0 ), () => {
  31063. s.assign( delta.div( maxcomp ) );
  31064. } ).Else( () => {
  31065. s.assign( 0.0 );
  31066. } );
  31067. If( s.lessThanEqual( 0.0 ), () => {
  31068. h.assign( 0.0 );
  31069. } ).Else( () => {
  31070. If( r.greaterThanEqual( maxcomp ), () => {
  31071. h.assign( g.sub( b ).div( delta ) );
  31072. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  31073. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  31074. } ).Else( () => {
  31075. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  31076. } );
  31077. h.mulAssign( 1.0 / 6.0 );
  31078. If( h.lessThan( 0.0 ), () => {
  31079. h.addAssign( 1.0 );
  31080. } );
  31081. } );
  31082. return vec3( h, s, v );
  31083. } ).setLayout( {
  31084. name: 'mx_rgbtohsv',
  31085. type: 'vec3',
  31086. inputs: [
  31087. { name: 'c', type: 'vec3' }
  31088. ]
  31089. } );
  31090. // Three.js Transpiler
  31091. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  31092. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  31093. const color = vec3( color_immutable ).toVar();
  31094. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  31095. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  31096. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  31097. return mix( linSeg, powSeg, isAbove );
  31098. } ).setLayout( {
  31099. name: 'mx_srgb_texture_to_lin_rec709',
  31100. type: 'vec3',
  31101. inputs: [
  31102. { name: 'color', type: 'vec3' }
  31103. ]
  31104. } );
  31105. const mx_aastep = ( threshold, value ) => {
  31106. threshold = float( threshold );
  31107. value = float( value );
  31108. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  31109. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  31110. };
  31111. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  31112. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  31113. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  31114. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  31115. const mx_ramp4 = (
  31116. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  31117. ) => {
  31118. const u = texcoord.x.clamp();
  31119. const v = texcoord.y.clamp();
  31120. const top = mix( valuetl, valuetr, u );
  31121. const bottom = mix( valuebl, valuebr, u );
  31122. return mix( top, bottom, v );
  31123. };
  31124. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  31125. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  31126. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  31127. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  31128. const mx_safepower = ( in1, in2 = 1 ) => {
  31129. in1 = float( in1 );
  31130. return in1.abs().pow( in2 ).mul( in1.sign() );
  31131. };
  31132. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  31133. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31134. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31135. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31136. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  31137. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  31138. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  31139. return noise_vec4.mul( amplitude ).add( pivot );
  31140. };
  31141. 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 );
  31142. 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 );
  31143. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31144. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31145. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31146. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  31147. 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 );
  31148. 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 );
  31149. 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 );
  31150. 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 );
  31151. // === Moved from MaterialXLoader.js ===
  31152. // Math ops
  31153. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  31154. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  31155. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  31156. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  31157. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  31158. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  31159. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  31160. const mx_timer = () => time;
  31161. const mx_frame = () => frameId;
  31162. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  31163. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  31164. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  31165. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  31166. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  31167. const mx_separate = ( in1, channelOrOut = null ) => {
  31168. if ( typeof channelOrOut === 'string' ) {
  31169. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31170. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  31171. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  31172. }
  31173. if ( typeof channelOrOut === 'number' ) {
  31174. return in1.element( channelOrOut );
  31175. }
  31176. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  31177. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31178. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  31179. }
  31180. return in1;
  31181. };
  31182. const mx_place2d = (
  31183. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  31184. ) => {
  31185. let uv = texcoord;
  31186. if ( pivot ) uv = uv.sub( pivot );
  31187. if ( scale ) uv = uv.mul( scale );
  31188. if ( rotate ) {
  31189. const rad = rotate.mul( Math.PI / 180.0 );
  31190. const cosR = rad.cos();
  31191. const sinR = rad.sin();
  31192. uv = vec2(
  31193. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  31194. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  31195. );
  31196. }
  31197. if ( pivot ) uv = uv.add( pivot );
  31198. if ( offset ) uv = uv.add( offset );
  31199. return uv;
  31200. };
  31201. const mx_rotate2d = ( input, amount ) => {
  31202. input = vec2( input );
  31203. amount = float( amount );
  31204. const radians = amount.mul( Math.PI / 180.0 );
  31205. return rotate( input, radians );
  31206. };
  31207. const mx_rotate3d = ( input, amount, axis ) => {
  31208. input = vec3( input );
  31209. amount = float( amount );
  31210. axis = vec3( axis );
  31211. const radians = amount.mul( Math.PI / 180.0 );
  31212. const nAxis = axis.normalize();
  31213. const cosA = radians.cos();
  31214. const sinA = radians.sin();
  31215. const oneMinusCosA = float( 1 ).sub( cosA );
  31216. const rot =
  31217. input.mul( cosA )
  31218. .add( nAxis.cross( input ).mul( sinA ) )
  31219. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  31220. return rot;
  31221. };
  31222. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  31223. input = vec3( input );
  31224. scale = float( scale );
  31225. return bumpMap( input, scale );
  31226. };
  31227. /**
  31228. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  31229. *
  31230. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  31231. *
  31232. * ```js
  31233. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  31234. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  31235. * ```
  31236. *
  31237. * @tsl
  31238. * @function
  31239. * @param {Node<vec3>} normal - The normal to correct.
  31240. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  31241. * @param {Node<vec3>} cubePos - The cube position.
  31242. * @return {Node<vec3>} The parallax corrected normal.
  31243. */
  31244. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  31245. const nDir = normalize( normal ).toVar();
  31246. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31247. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31248. const rbminmax = vec3().toVar();
  31249. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  31250. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  31251. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  31252. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  31253. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  31254. return boxIntersection.sub( cubePos );
  31255. } );
  31256. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  31257. // normal is assumed to have unit length
  31258. const x = normal.x, y = normal.y, z = normal.z;
  31259. // band 0
  31260. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  31261. // band 1
  31262. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  31263. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  31264. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  31265. // band 2
  31266. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  31267. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  31268. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  31269. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  31270. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  31271. return result;
  31272. } );
  31273. // constants
  31274. var TSL = /*#__PURE__*/Object.freeze({
  31275. __proto__: null,
  31276. BRDF_GGX: BRDF_GGX,
  31277. BRDF_Lambert: BRDF_Lambert,
  31278. BasicPointShadowFilter: BasicPointShadowFilter,
  31279. BasicShadowFilter: BasicShadowFilter,
  31280. Break: Break,
  31281. Const: Const,
  31282. Continue: Continue,
  31283. DFGApprox: DFGApprox,
  31284. D_GGX: D_GGX,
  31285. Discard: Discard,
  31286. EPSILON: EPSILON,
  31287. F_Schlick: F_Schlick,
  31288. Fn: Fn,
  31289. INFINITY: INFINITY,
  31290. If: If,
  31291. Loop: Loop,
  31292. NodeAccess: NodeAccess,
  31293. NodeShaderStage: NodeShaderStage,
  31294. NodeType: NodeType,
  31295. NodeUpdateType: NodeUpdateType,
  31296. OnMaterialUpdate: OnMaterialUpdate,
  31297. OnObjectUpdate: OnObjectUpdate,
  31298. PCFShadowFilter: PCFShadowFilter,
  31299. PCFSoftShadowFilter: PCFSoftShadowFilter,
  31300. PI: PI,
  31301. PI2: PI2,
  31302. PointShadowFilter: PointShadowFilter,
  31303. Return: Return,
  31304. Schlick_to_F0: Schlick_to_F0,
  31305. ScriptableNodeResources: ScriptableNodeResources,
  31306. ShaderNode: ShaderNode,
  31307. Stack: Stack,
  31308. Switch: Switch,
  31309. TBNViewMatrix: TBNViewMatrix,
  31310. VSMShadowFilter: VSMShadowFilter,
  31311. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  31312. Var: Var,
  31313. VarIntent: VarIntent,
  31314. abs: abs,
  31315. acesFilmicToneMapping: acesFilmicToneMapping,
  31316. acos: acos,
  31317. add: add,
  31318. addMethodChaining: addMethodChaining,
  31319. addNodeElement: addNodeElement,
  31320. agxToneMapping: agxToneMapping,
  31321. all: all,
  31322. alphaT: alphaT,
  31323. and: and,
  31324. anisotropy: anisotropy,
  31325. anisotropyB: anisotropyB,
  31326. anisotropyT: anisotropyT,
  31327. any: any,
  31328. append: append,
  31329. array: array,
  31330. arrayBuffer: arrayBuffer,
  31331. asin: asin,
  31332. assign: assign,
  31333. atan: atan,
  31334. atan2: atan2,
  31335. atomicAdd: atomicAdd,
  31336. atomicAnd: atomicAnd,
  31337. atomicFunc: atomicFunc,
  31338. atomicLoad: atomicLoad,
  31339. atomicMax: atomicMax,
  31340. atomicMin: atomicMin,
  31341. atomicOr: atomicOr,
  31342. atomicStore: atomicStore,
  31343. atomicSub: atomicSub,
  31344. atomicXor: atomicXor,
  31345. attenuationColor: attenuationColor,
  31346. attenuationDistance: attenuationDistance,
  31347. attribute: attribute,
  31348. attributeArray: attributeArray,
  31349. backgroundBlurriness: backgroundBlurriness,
  31350. backgroundIntensity: backgroundIntensity,
  31351. backgroundRotation: backgroundRotation,
  31352. batch: batch,
  31353. bentNormalView: bentNormalView,
  31354. billboarding: billboarding,
  31355. bitAnd: bitAnd,
  31356. bitNot: bitNot,
  31357. bitOr: bitOr,
  31358. bitXor: bitXor,
  31359. bitangentGeometry: bitangentGeometry,
  31360. bitangentLocal: bitangentLocal,
  31361. bitangentView: bitangentView,
  31362. bitangentWorld: bitangentWorld,
  31363. bitcast: bitcast,
  31364. blendBurn: blendBurn,
  31365. blendColor: blendColor,
  31366. blendDodge: blendDodge,
  31367. blendOverlay: blendOverlay,
  31368. blendScreen: blendScreen,
  31369. blur: blur,
  31370. bool: bool,
  31371. buffer: buffer,
  31372. bufferAttribute: bufferAttribute,
  31373. bumpMap: bumpMap,
  31374. burn: burn,
  31375. bvec2: bvec2,
  31376. bvec3: bvec3,
  31377. bvec4: bvec4,
  31378. bypass: bypass,
  31379. cache: cache,
  31380. call: call,
  31381. cameraFar: cameraFar,
  31382. cameraIndex: cameraIndex,
  31383. cameraNear: cameraNear,
  31384. cameraNormalMatrix: cameraNormalMatrix,
  31385. cameraPosition: cameraPosition,
  31386. cameraProjectionMatrix: cameraProjectionMatrix,
  31387. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  31388. cameraViewMatrix: cameraViewMatrix,
  31389. cameraViewport: cameraViewport,
  31390. cameraWorldMatrix: cameraWorldMatrix,
  31391. cbrt: cbrt,
  31392. cdl: cdl,
  31393. ceil: ceil,
  31394. checker: checker,
  31395. cineonToneMapping: cineonToneMapping,
  31396. clamp: clamp,
  31397. clearcoat: clearcoat,
  31398. clearcoatNormalView: clearcoatNormalView,
  31399. clearcoatRoughness: clearcoatRoughness,
  31400. code: code,
  31401. color: color,
  31402. colorSpaceToWorking: colorSpaceToWorking,
  31403. colorToDirection: colorToDirection,
  31404. compute: compute,
  31405. computeKernel: computeKernel,
  31406. computeSkinning: computeSkinning,
  31407. context: context,
  31408. convert: convert,
  31409. convertColorSpace: convertColorSpace,
  31410. convertToTexture: convertToTexture,
  31411. cos: cos,
  31412. cross: cross,
  31413. cubeTexture: cubeTexture,
  31414. cubeTextureBase: cubeTextureBase,
  31415. cubeToUV: cubeToUV,
  31416. dFdx: dFdx,
  31417. dFdy: dFdy,
  31418. dashSize: dashSize,
  31419. debug: debug,
  31420. decrement: decrement,
  31421. decrementBefore: decrementBefore,
  31422. defaultBuildStages: defaultBuildStages,
  31423. defaultShaderStages: defaultShaderStages,
  31424. defined: defined,
  31425. degrees: degrees,
  31426. deltaTime: deltaTime,
  31427. densityFog: densityFog,
  31428. densityFogFactor: densityFogFactor,
  31429. depth: depth,
  31430. depthPass: depthPass,
  31431. determinant: determinant,
  31432. difference: difference,
  31433. diffuseColor: diffuseColor,
  31434. directPointLight: directPointLight,
  31435. directionToColor: directionToColor,
  31436. directionToFaceDirection: directionToFaceDirection,
  31437. dispersion: dispersion,
  31438. distance: distance,
  31439. div: div,
  31440. dodge: dodge,
  31441. dot: dot,
  31442. drawIndex: drawIndex,
  31443. dynamicBufferAttribute: dynamicBufferAttribute,
  31444. element: element,
  31445. emissive: emissive,
  31446. equal: equal,
  31447. equals: equals,
  31448. equirectUV: equirectUV,
  31449. exp: exp,
  31450. exp2: exp2,
  31451. expression: expression,
  31452. faceDirection: faceDirection,
  31453. faceForward: faceForward,
  31454. faceforward: faceforward,
  31455. float: float,
  31456. floor: floor,
  31457. fog: fog,
  31458. fract: fract,
  31459. frameGroup: frameGroup,
  31460. frameId: frameId,
  31461. frontFacing: frontFacing,
  31462. fwidth: fwidth,
  31463. gain: gain,
  31464. gapSize: gapSize,
  31465. getConstNodeType: getConstNodeType,
  31466. getCurrentStack: getCurrentStack,
  31467. getDirection: getDirection,
  31468. getDistanceAttenuation: getDistanceAttenuation,
  31469. getGeometryRoughness: getGeometryRoughness,
  31470. getNormalFromDepth: getNormalFromDepth,
  31471. getParallaxCorrectNormal: getParallaxCorrectNormal,
  31472. getRoughness: getRoughness,
  31473. getScreenPosition: getScreenPosition,
  31474. getShIrradianceAt: getShIrradianceAt,
  31475. getShadowMaterial: getShadowMaterial,
  31476. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  31477. getTextureIndex: getTextureIndex,
  31478. getViewPosition: getViewPosition,
  31479. globalId: globalId,
  31480. glsl: glsl,
  31481. glslFn: glslFn,
  31482. grayscale: grayscale,
  31483. greaterThan: greaterThan,
  31484. greaterThanEqual: greaterThanEqual,
  31485. hash: hash,
  31486. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  31487. highpModelViewMatrix: highpModelViewMatrix,
  31488. hue: hue,
  31489. increment: increment,
  31490. incrementBefore: incrementBefore,
  31491. instance: instance,
  31492. instanceIndex: instanceIndex,
  31493. instancedArray: instancedArray,
  31494. instancedBufferAttribute: instancedBufferAttribute,
  31495. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  31496. instancedMesh: instancedMesh,
  31497. int: int,
  31498. inverse: inverse,
  31499. inverseSqrt: inverseSqrt,
  31500. inversesqrt: inversesqrt,
  31501. invocationLocalIndex: invocationLocalIndex,
  31502. invocationSubgroupIndex: invocationSubgroupIndex,
  31503. ior: ior,
  31504. iridescence: iridescence,
  31505. iridescenceIOR: iridescenceIOR,
  31506. iridescenceThickness: iridescenceThickness,
  31507. ivec2: ivec2,
  31508. ivec3: ivec3,
  31509. ivec4: ivec4,
  31510. js: js,
  31511. label: label,
  31512. length: length,
  31513. lengthSq: lengthSq,
  31514. lessThan: lessThan,
  31515. lessThanEqual: lessThanEqual,
  31516. lightPosition: lightPosition,
  31517. lightProjectionUV: lightProjectionUV,
  31518. lightShadowMatrix: lightShadowMatrix,
  31519. lightTargetDirection: lightTargetDirection,
  31520. lightTargetPosition: lightTargetPosition,
  31521. lightViewPosition: lightViewPosition,
  31522. lightingContext: lightingContext,
  31523. lights: lights,
  31524. linearDepth: linearDepth,
  31525. linearToneMapping: linearToneMapping,
  31526. localId: localId,
  31527. log: log,
  31528. log2: log2,
  31529. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  31530. luminance: luminance,
  31531. mat2: mat2,
  31532. mat3: mat3,
  31533. mat4: mat4,
  31534. matcapUV: matcapUV,
  31535. materialAO: materialAO,
  31536. materialAlphaTest: materialAlphaTest,
  31537. materialAnisotropy: materialAnisotropy,
  31538. materialAnisotropyVector: materialAnisotropyVector,
  31539. materialAttenuationColor: materialAttenuationColor,
  31540. materialAttenuationDistance: materialAttenuationDistance,
  31541. materialClearcoat: materialClearcoat,
  31542. materialClearcoatNormal: materialClearcoatNormal,
  31543. materialClearcoatRoughness: materialClearcoatRoughness,
  31544. materialColor: materialColor,
  31545. materialDispersion: materialDispersion,
  31546. materialEmissive: materialEmissive,
  31547. materialEnvIntensity: materialEnvIntensity,
  31548. materialEnvRotation: materialEnvRotation,
  31549. materialIOR: materialIOR,
  31550. materialIridescence: materialIridescence,
  31551. materialIridescenceIOR: materialIridescenceIOR,
  31552. materialIridescenceThickness: materialIridescenceThickness,
  31553. materialLightMap: materialLightMap,
  31554. materialLineDashOffset: materialLineDashOffset,
  31555. materialLineDashSize: materialLineDashSize,
  31556. materialLineGapSize: materialLineGapSize,
  31557. materialLineScale: materialLineScale,
  31558. materialLineWidth: materialLineWidth,
  31559. materialMetalness: materialMetalness,
  31560. materialNormal: materialNormal,
  31561. materialOpacity: materialOpacity,
  31562. materialPointSize: materialPointSize,
  31563. materialReference: materialReference,
  31564. materialReflectivity: materialReflectivity,
  31565. materialRefractionRatio: materialRefractionRatio,
  31566. materialRotation: materialRotation,
  31567. materialRoughness: materialRoughness,
  31568. materialSheen: materialSheen,
  31569. materialSheenRoughness: materialSheenRoughness,
  31570. materialShininess: materialShininess,
  31571. materialSpecular: materialSpecular,
  31572. materialSpecularColor: materialSpecularColor,
  31573. materialSpecularIntensity: materialSpecularIntensity,
  31574. materialSpecularStrength: materialSpecularStrength,
  31575. materialThickness: materialThickness,
  31576. materialTransmission: materialTransmission,
  31577. max: max$1,
  31578. maxMipLevel: maxMipLevel,
  31579. mediumpModelViewMatrix: mediumpModelViewMatrix,
  31580. metalness: metalness,
  31581. min: min$1,
  31582. mix: mix,
  31583. mixElement: mixElement,
  31584. mod: mod,
  31585. modInt: modInt,
  31586. modelDirection: modelDirection,
  31587. modelNormalMatrix: modelNormalMatrix,
  31588. modelPosition: modelPosition,
  31589. modelRadius: modelRadius,
  31590. modelScale: modelScale,
  31591. modelViewMatrix: modelViewMatrix,
  31592. modelViewPosition: modelViewPosition,
  31593. modelViewProjection: modelViewProjection,
  31594. modelWorldMatrix: modelWorldMatrix,
  31595. modelWorldMatrixInverse: modelWorldMatrixInverse,
  31596. morphReference: morphReference,
  31597. mrt: mrt,
  31598. mul: mul,
  31599. mx_aastep: mx_aastep,
  31600. mx_add: mx_add,
  31601. mx_atan2: mx_atan2,
  31602. mx_cell_noise_float: mx_cell_noise_float,
  31603. mx_contrast: mx_contrast,
  31604. mx_divide: mx_divide,
  31605. mx_fractal_noise_float: mx_fractal_noise_float,
  31606. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  31607. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  31608. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  31609. mx_frame: mx_frame,
  31610. mx_heighttonormal: mx_heighttonormal,
  31611. mx_hsvtorgb: mx_hsvtorgb,
  31612. mx_ifequal: mx_ifequal,
  31613. mx_ifgreater: mx_ifgreater,
  31614. mx_ifgreatereq: mx_ifgreatereq,
  31615. mx_invert: mx_invert,
  31616. mx_modulo: mx_modulo,
  31617. mx_multiply: mx_multiply,
  31618. mx_noise_float: mx_noise_float,
  31619. mx_noise_vec3: mx_noise_vec3,
  31620. mx_noise_vec4: mx_noise_vec4,
  31621. mx_place2d: mx_place2d,
  31622. mx_power: mx_power,
  31623. mx_ramp4: mx_ramp4,
  31624. mx_ramplr: mx_ramplr,
  31625. mx_ramptb: mx_ramptb,
  31626. mx_rgbtohsv: mx_rgbtohsv,
  31627. mx_rotate2d: mx_rotate2d,
  31628. mx_rotate3d: mx_rotate3d,
  31629. mx_safepower: mx_safepower,
  31630. mx_separate: mx_separate,
  31631. mx_splitlr: mx_splitlr,
  31632. mx_splittb: mx_splittb,
  31633. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  31634. mx_subtract: mx_subtract,
  31635. mx_timer: mx_timer,
  31636. mx_transform_uv: mx_transform_uv,
  31637. mx_unifiednoise2d: mx_unifiednoise2d,
  31638. mx_unifiednoise3d: mx_unifiednoise3d,
  31639. mx_worley_noise_float: mx_worley_noise_float,
  31640. mx_worley_noise_vec2: mx_worley_noise_vec2,
  31641. mx_worley_noise_vec3: mx_worley_noise_vec3,
  31642. negate: negate,
  31643. neutralToneMapping: neutralToneMapping,
  31644. nodeArray: nodeArray,
  31645. nodeImmutable: nodeImmutable,
  31646. nodeObject: nodeObject,
  31647. nodeObjectIntent: nodeObjectIntent,
  31648. nodeObjects: nodeObjects,
  31649. nodeProxy: nodeProxy,
  31650. nodeProxyIntent: nodeProxyIntent,
  31651. normalFlat: normalFlat,
  31652. normalGeometry: normalGeometry,
  31653. normalLocal: normalLocal,
  31654. normalMap: normalMap,
  31655. normalView: normalView,
  31656. normalViewGeometry: normalViewGeometry,
  31657. normalWorld: normalWorld,
  31658. normalWorldGeometry: normalWorldGeometry,
  31659. normalize: normalize,
  31660. not: not,
  31661. notEqual: notEqual,
  31662. numWorkgroups: numWorkgroups,
  31663. objectDirection: objectDirection,
  31664. objectGroup: objectGroup,
  31665. objectPosition: objectPosition,
  31666. objectRadius: objectRadius,
  31667. objectScale: objectScale,
  31668. objectViewPosition: objectViewPosition,
  31669. objectWorldMatrix: objectWorldMatrix,
  31670. oneMinus: oneMinus,
  31671. or: or,
  31672. orthographicDepthToViewZ: orthographicDepthToViewZ,
  31673. oscSawtooth: oscSawtooth,
  31674. oscSine: oscSine,
  31675. oscSquare: oscSquare,
  31676. oscTriangle: oscTriangle,
  31677. output: output,
  31678. outputStruct: outputStruct,
  31679. overlay: overlay,
  31680. overloadingFn: overloadingFn,
  31681. parabola: parabola,
  31682. parallaxDirection: parallaxDirection,
  31683. parallaxUV: parallaxUV,
  31684. parameter: parameter,
  31685. pass: pass,
  31686. passTexture: passTexture,
  31687. pcurve: pcurve,
  31688. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  31689. pmremTexture: pmremTexture,
  31690. pointShadow: pointShadow,
  31691. pointUV: pointUV,
  31692. pointWidth: pointWidth,
  31693. positionGeometry: positionGeometry,
  31694. positionLocal: positionLocal,
  31695. positionPrevious: positionPrevious,
  31696. positionView: positionView,
  31697. positionViewDirection: positionViewDirection,
  31698. positionWorld: positionWorld,
  31699. positionWorldDirection: positionWorldDirection,
  31700. posterize: posterize,
  31701. pow: pow,
  31702. pow2: pow2,
  31703. pow3: pow3,
  31704. pow4: pow4,
  31705. premultiplyAlpha: premultiplyAlpha,
  31706. property: property,
  31707. quadBroadcast: quadBroadcast,
  31708. quadSwapDiagonal: quadSwapDiagonal,
  31709. quadSwapX: quadSwapX,
  31710. quadSwapY: quadSwapY,
  31711. radians: radians,
  31712. rand: rand,
  31713. range: range,
  31714. rangeFog: rangeFog,
  31715. rangeFogFactor: rangeFogFactor,
  31716. reciprocal: reciprocal,
  31717. reference: reference,
  31718. referenceBuffer: referenceBuffer,
  31719. reflect: reflect,
  31720. reflectVector: reflectVector,
  31721. reflectView: reflectView,
  31722. reflector: reflector,
  31723. refract: refract,
  31724. refractVector: refractVector,
  31725. refractView: refractView,
  31726. reinhardToneMapping: reinhardToneMapping,
  31727. remap: remap,
  31728. remapClamp: remapClamp,
  31729. renderGroup: renderGroup,
  31730. renderOutput: renderOutput,
  31731. rendererReference: rendererReference,
  31732. rotate: rotate,
  31733. rotateUV: rotateUV,
  31734. roughness: roughness,
  31735. round: round,
  31736. rtt: rtt,
  31737. sRGBTransferEOTF: sRGBTransferEOTF,
  31738. sRGBTransferOETF: sRGBTransferOETF,
  31739. sample: sample,
  31740. sampler: sampler,
  31741. samplerComparison: samplerComparison,
  31742. saturate: saturate,
  31743. saturation: saturation,
  31744. screen: screen,
  31745. screenCoordinate: screenCoordinate,
  31746. screenSize: screenSize,
  31747. screenUV: screenUV,
  31748. scriptable: scriptable,
  31749. scriptableValue: scriptableValue,
  31750. select: select,
  31751. setCurrentStack: setCurrentStack,
  31752. setName: setName,
  31753. shaderStages: shaderStages,
  31754. shadow: shadow,
  31755. shadowPositionWorld: shadowPositionWorld,
  31756. shapeCircle: shapeCircle,
  31757. sharedUniformGroup: sharedUniformGroup,
  31758. sheen: sheen,
  31759. sheenRoughness: sheenRoughness,
  31760. shiftLeft: shiftLeft,
  31761. shiftRight: shiftRight,
  31762. shininess: shininess,
  31763. sign: sign,
  31764. sin: sin,
  31765. sinc: sinc,
  31766. skinning: skinning,
  31767. smoothstep: smoothstep,
  31768. smoothstepElement: smoothstepElement,
  31769. specularColor: specularColor,
  31770. specularF90: specularF90,
  31771. spherizeUV: spherizeUV,
  31772. split: split,
  31773. spritesheetUV: spritesheetUV,
  31774. sqrt: sqrt,
  31775. stack: stack,
  31776. step: step,
  31777. stepElement: stepElement,
  31778. storage: storage,
  31779. storageBarrier: storageBarrier,
  31780. storageObject: storageObject,
  31781. storageTexture: storageTexture,
  31782. string: string,
  31783. struct: struct,
  31784. sub: sub,
  31785. subBuild: subBuild,
  31786. subgroupAdd: subgroupAdd,
  31787. subgroupAll: subgroupAll,
  31788. subgroupAnd: subgroupAnd,
  31789. subgroupAny: subgroupAny,
  31790. subgroupBallot: subgroupBallot,
  31791. subgroupBroadcast: subgroupBroadcast,
  31792. subgroupBroadcastFirst: subgroupBroadcastFirst,
  31793. subgroupElect: subgroupElect,
  31794. subgroupExclusiveAdd: subgroupExclusiveAdd,
  31795. subgroupExclusiveMul: subgroupExclusiveMul,
  31796. subgroupInclusiveAdd: subgroupInclusiveAdd,
  31797. subgroupInclusiveMul: subgroupInclusiveMul,
  31798. subgroupIndex: subgroupIndex,
  31799. subgroupMax: subgroupMax,
  31800. subgroupMin: subgroupMin,
  31801. subgroupMul: subgroupMul,
  31802. subgroupOr: subgroupOr,
  31803. subgroupShuffle: subgroupShuffle,
  31804. subgroupShuffleDown: subgroupShuffleDown,
  31805. subgroupShuffleUp: subgroupShuffleUp,
  31806. subgroupShuffleXor: subgroupShuffleXor,
  31807. subgroupSize: subgroupSize,
  31808. subgroupXor: subgroupXor,
  31809. tan: tan,
  31810. tangentGeometry: tangentGeometry,
  31811. tangentLocal: tangentLocal,
  31812. tangentView: tangentView,
  31813. tangentWorld: tangentWorld,
  31814. texture: texture,
  31815. texture3D: texture3D,
  31816. textureBarrier: textureBarrier,
  31817. textureBicubic: textureBicubic,
  31818. textureBicubicLevel: textureBicubicLevel,
  31819. textureCubeUV: textureCubeUV,
  31820. textureLoad: textureLoad,
  31821. textureSize: textureSize,
  31822. textureStore: textureStore,
  31823. thickness: thickness,
  31824. time: time,
  31825. toneMapping: toneMapping,
  31826. toneMappingExposure: toneMappingExposure,
  31827. toonOutlinePass: toonOutlinePass,
  31828. transformDirection: transformDirection,
  31829. transformNormal: transformNormal,
  31830. transformNormalToView: transformNormalToView,
  31831. transformedClearcoatNormalView: transformedClearcoatNormalView,
  31832. transformedNormalView: transformedNormalView,
  31833. transformedNormalWorld: transformedNormalWorld,
  31834. transmission: transmission,
  31835. transpose: transpose,
  31836. triNoise3D: triNoise3D,
  31837. triplanarTexture: triplanarTexture,
  31838. triplanarTextures: triplanarTextures,
  31839. trunc: trunc,
  31840. uint: uint,
  31841. uniform: uniform,
  31842. uniformArray: uniformArray,
  31843. uniformCubeTexture: uniformCubeTexture,
  31844. uniformFlow: uniformFlow,
  31845. uniformGroup: uniformGroup,
  31846. uniformTexture: uniformTexture,
  31847. unpremultiplyAlpha: unpremultiplyAlpha,
  31848. userData: userData,
  31849. uv: uv$1,
  31850. uvec2: uvec2,
  31851. uvec3: uvec3,
  31852. uvec4: uvec4,
  31853. varying: varying,
  31854. varyingProperty: varyingProperty,
  31855. vec2: vec2,
  31856. vec3: vec3,
  31857. vec4: vec4,
  31858. vectorComponents: vectorComponents,
  31859. velocity: velocity,
  31860. vertexColor: vertexColor,
  31861. vertexIndex: vertexIndex,
  31862. vertexStage: vertexStage,
  31863. vibrance: vibrance,
  31864. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  31865. viewZToOrthographicDepth: viewZToOrthographicDepth,
  31866. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  31867. viewport: viewport,
  31868. viewportCoordinate: viewportCoordinate,
  31869. viewportDepthTexture: viewportDepthTexture,
  31870. viewportLinearDepth: viewportLinearDepth,
  31871. viewportMipTexture: viewportMipTexture,
  31872. viewportResolution: viewportResolution,
  31873. viewportSafeUV: viewportSafeUV,
  31874. viewportSharedTexture: viewportSharedTexture,
  31875. viewportSize: viewportSize,
  31876. viewportTexture: viewportTexture,
  31877. viewportUV: viewportUV,
  31878. wgsl: wgsl,
  31879. wgslFn: wgslFn,
  31880. workgroupArray: workgroupArray,
  31881. workgroupBarrier: workgroupBarrier,
  31882. workgroupId: workgroupId,
  31883. workingToColorSpace: workingToColorSpace,
  31884. xor: xor
  31885. });
  31886. const _clearColor = /*@__PURE__*/ new Color4();
  31887. /**
  31888. * This renderer module manages the background.
  31889. *
  31890. * @private
  31891. * @augments DataMap
  31892. */
  31893. class Background extends DataMap {
  31894. /**
  31895. * Constructs a new background management component.
  31896. *
  31897. * @param {Renderer} renderer - The renderer.
  31898. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  31899. */
  31900. constructor( renderer, nodes ) {
  31901. super();
  31902. /**
  31903. * The renderer.
  31904. *
  31905. * @type {Renderer}
  31906. */
  31907. this.renderer = renderer;
  31908. /**
  31909. * Renderer component for managing nodes related logic.
  31910. *
  31911. * @type {Nodes}
  31912. */
  31913. this.nodes = nodes;
  31914. }
  31915. /**
  31916. * Updates the background for the given scene. Depending on how `Scene.background`
  31917. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  31918. * or add a mesh to the render list for rendering the background as a textured plane
  31919. * or skybox.
  31920. *
  31921. * @param {Scene} scene - The scene.
  31922. * @param {RenderList} renderList - The current render list.
  31923. * @param {RenderContext} renderContext - The current render context.
  31924. */
  31925. update( scene, renderList, renderContext ) {
  31926. const renderer = this.renderer;
  31927. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  31928. let forceClear = false;
  31929. if ( background === null ) {
  31930. // no background settings, use clear color configuration from the renderer
  31931. renderer._clearColor.getRGB( _clearColor );
  31932. _clearColor.a = renderer._clearColor.a;
  31933. } else if ( background.isColor === true ) {
  31934. // background is an opaque color
  31935. background.getRGB( _clearColor );
  31936. _clearColor.a = 1;
  31937. forceClear = true;
  31938. } else if ( background.isNode === true ) {
  31939. const sceneData = this.get( scene );
  31940. const backgroundNode = background;
  31941. _clearColor.copy( renderer._clearColor );
  31942. let backgroundMesh = sceneData.backgroundMesh;
  31943. if ( backgroundMesh === undefined ) {
  31944. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  31945. // @TODO: Add Texture2D support using node context
  31946. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  31947. getTextureLevel: () => backgroundBlurriness
  31948. } );
  31949. let viewProj = modelViewProjection;
  31950. viewProj = viewProj.setZ( viewProj.w );
  31951. const nodeMaterial = new NodeMaterial();
  31952. nodeMaterial.name = 'Background.material';
  31953. nodeMaterial.side = BackSide;
  31954. nodeMaterial.depthTest = false;
  31955. nodeMaterial.depthWrite = false;
  31956. nodeMaterial.allowOverride = false;
  31957. nodeMaterial.fog = false;
  31958. nodeMaterial.lights = false;
  31959. nodeMaterial.vertexNode = viewProj;
  31960. nodeMaterial.colorNode = backgroundMeshNode;
  31961. sceneData.backgroundMeshNode = backgroundMeshNode;
  31962. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  31963. backgroundMesh.frustumCulled = false;
  31964. backgroundMesh.name = 'Background.mesh';
  31965. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  31966. this.matrixWorld.copyPosition( camera.matrixWorld );
  31967. };
  31968. function onBackgroundDispose() {
  31969. background.removeEventListener( 'dispose', onBackgroundDispose );
  31970. backgroundMesh.material.dispose();
  31971. backgroundMesh.geometry.dispose();
  31972. }
  31973. background.addEventListener( 'dispose', onBackgroundDispose );
  31974. }
  31975. const backgroundCacheKey = backgroundNode.getCacheKey();
  31976. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  31977. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  31978. sceneData.backgroundMeshNode.needsUpdate = true;
  31979. backgroundMesh.material.needsUpdate = true;
  31980. sceneData.backgroundCacheKey = backgroundCacheKey;
  31981. }
  31982. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  31983. } else {
  31984. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  31985. }
  31986. //
  31987. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  31988. if ( environmentBlendMode === 'additive' ) {
  31989. _clearColor.set( 0, 0, 0, 1 );
  31990. } else if ( environmentBlendMode === 'alpha-blend' ) {
  31991. _clearColor.set( 0, 0, 0, 0 );
  31992. }
  31993. //
  31994. if ( renderer.autoClear === true || forceClear === true ) {
  31995. const clearColorValue = renderContext.clearColorValue;
  31996. clearColorValue.r = _clearColor.r;
  31997. clearColorValue.g = _clearColor.g;
  31998. clearColorValue.b = _clearColor.b;
  31999. clearColorValue.a = _clearColor.a;
  32000. // premultiply alpha
  32001. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  32002. clearColorValue.r *= clearColorValue.a;
  32003. clearColorValue.g *= clearColorValue.a;
  32004. clearColorValue.b *= clearColorValue.a;
  32005. }
  32006. //
  32007. renderContext.depthClearValue = renderer._clearDepth;
  32008. renderContext.stencilClearValue = renderer._clearStencil;
  32009. renderContext.clearColor = renderer.autoClearColor === true;
  32010. renderContext.clearDepth = renderer.autoClearDepth === true;
  32011. renderContext.clearStencil = renderer.autoClearStencil === true;
  32012. } else {
  32013. renderContext.clearColor = false;
  32014. renderContext.clearDepth = false;
  32015. renderContext.clearStencil = false;
  32016. }
  32017. }
  32018. }
  32019. let _id$6 = 0;
  32020. /**
  32021. * A bind group represents a collection of bindings and thus a collection
  32022. * or resources. Bind groups are assigned to pipelines to provide them
  32023. * with the required resources (like uniform buffers or textures).
  32024. *
  32025. * @private
  32026. */
  32027. class BindGroup {
  32028. /**
  32029. * Constructs a new bind group.
  32030. *
  32031. * @param {string} name - The bind group's name.
  32032. * @param {Array<Binding>} bindings - An array of bindings.
  32033. * @param {number} index - The group index.
  32034. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  32035. */
  32036. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  32037. /**
  32038. * The bind group's name.
  32039. *
  32040. * @type {string}
  32041. */
  32042. this.name = name;
  32043. /**
  32044. * An array of bindings.
  32045. *
  32046. * @type {Array<Binding>}
  32047. */
  32048. this.bindings = bindings;
  32049. /**
  32050. * The group index.
  32051. *
  32052. * @type {number}
  32053. */
  32054. this.index = index;
  32055. /**
  32056. * An array of reference bindings.
  32057. *
  32058. * @type {Array<Binding>}
  32059. */
  32060. this.bindingsReference = bindingsReference;
  32061. /**
  32062. * The group's ID.
  32063. *
  32064. * @type {number}
  32065. */
  32066. this.id = _id$6 ++;
  32067. }
  32068. }
  32069. /**
  32070. * This module represents the state of a node builder after it was
  32071. * used to build the nodes for a render object. The state holds the
  32072. * results of the build for further processing in the renderer.
  32073. *
  32074. * Render objects with identical cache keys share the same node builder state.
  32075. *
  32076. * @private
  32077. */
  32078. class NodeBuilderState {
  32079. /**
  32080. * Constructs a new node builder state.
  32081. *
  32082. * @param {string} vertexShader - The native vertex shader code.
  32083. * @param {string} fragmentShader - The native fragment shader code.
  32084. * @param {string} computeShader - The native compute shader code.
  32085. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  32086. * @param {Array<BindGroup>} bindings - An array of bind groups.
  32087. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  32088. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  32089. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  32090. * @param {NodeMaterialObserver} observer - A node material observer.
  32091. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  32092. */
  32093. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  32094. /**
  32095. * The native vertex shader code.
  32096. *
  32097. * @type {string}
  32098. */
  32099. this.vertexShader = vertexShader;
  32100. /**
  32101. * The native fragment shader code.
  32102. *
  32103. * @type {string}
  32104. */
  32105. this.fragmentShader = fragmentShader;
  32106. /**
  32107. * The native compute shader code.
  32108. *
  32109. * @type {string}
  32110. */
  32111. this.computeShader = computeShader;
  32112. /**
  32113. * An array with transform attribute objects.
  32114. * Only relevant when using compute shaders with WebGL 2.
  32115. *
  32116. * @type {Array<Object>}
  32117. */
  32118. this.transforms = transforms;
  32119. /**
  32120. * An array of node attributes representing
  32121. * the attributes of the shaders.
  32122. *
  32123. * @type {Array<NodeAttribute>}
  32124. */
  32125. this.nodeAttributes = nodeAttributes;
  32126. /**
  32127. * An array of bind groups representing the uniform or storage
  32128. * buffers, texture or samplers of the shader.
  32129. *
  32130. * @type {Array<BindGroup>}
  32131. */
  32132. this.bindings = bindings;
  32133. /**
  32134. * An array of nodes that implement their `update()` method.
  32135. *
  32136. * @type {Array<Node>}
  32137. */
  32138. this.updateNodes = updateNodes;
  32139. /**
  32140. * An array of nodes that implement their `updateBefore()` method.
  32141. *
  32142. * @type {Array<Node>}
  32143. */
  32144. this.updateBeforeNodes = updateBeforeNodes;
  32145. /**
  32146. * An array of nodes that implement their `updateAfter()` method.
  32147. *
  32148. * @type {Array<Node>}
  32149. */
  32150. this.updateAfterNodes = updateAfterNodes;
  32151. /**
  32152. * A node material observer.
  32153. *
  32154. * @type {NodeMaterialObserver}
  32155. */
  32156. this.observer = observer;
  32157. /**
  32158. * How often this state is used by render objects.
  32159. *
  32160. * @type {number}
  32161. */
  32162. this.usedTimes = 0;
  32163. }
  32164. /**
  32165. * This method is used to create a array of bind groups based
  32166. * on the existing bind groups of this state. Shared groups are
  32167. * not cloned.
  32168. *
  32169. * @return {Array<BindGroup>} A array of bind groups.
  32170. */
  32171. createBindings() {
  32172. const bindings = [];
  32173. for ( const instanceGroup of this.bindings ) {
  32174. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  32175. if ( shared !== true ) {
  32176. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  32177. bindings.push( bindingsGroup );
  32178. for ( const instanceBinding of instanceGroup.bindings ) {
  32179. bindingsGroup.bindings.push( instanceBinding.clone() );
  32180. }
  32181. } else {
  32182. bindings.push( instanceGroup );
  32183. }
  32184. }
  32185. return bindings;
  32186. }
  32187. }
  32188. /**
  32189. * {@link NodeBuilder} is going to create instances of this class during the build process
  32190. * of nodes. They represent the final shader attributes that are going to be generated
  32191. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  32192. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  32193. */
  32194. class NodeAttribute {
  32195. /**
  32196. * Constructs a new node attribute.
  32197. *
  32198. * @param {string} name - The name of the attribute.
  32199. * @param {string} type - The type of the attribute.
  32200. * @param {?Node} node - An optional reference to the node.
  32201. */
  32202. constructor( name, type, node = null ) {
  32203. /**
  32204. * This flag can be used for type testing.
  32205. *
  32206. * @type {boolean}
  32207. * @readonly
  32208. * @default true
  32209. */
  32210. this.isNodeAttribute = true;
  32211. /**
  32212. * The name of the attribute.
  32213. *
  32214. * @type {string}
  32215. */
  32216. this.name = name;
  32217. /**
  32218. * The type of the attribute.
  32219. *
  32220. * @type {string}
  32221. */
  32222. this.type = type;
  32223. /**
  32224. * An optional reference to the node.
  32225. *
  32226. * @type {?Node}
  32227. * @default null
  32228. */
  32229. this.node = node;
  32230. }
  32231. }
  32232. /**
  32233. * {@link NodeBuilder} is going to create instances of this class during the build process
  32234. * of nodes. They represent the final shader uniforms that are going to be generated
  32235. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  32236. * for this purpose.
  32237. */
  32238. class NodeUniform {
  32239. /**
  32240. * Constructs a new node uniform.
  32241. *
  32242. * @param {string} name - The name of the uniform.
  32243. * @param {string} type - The type of the uniform.
  32244. * @param {UniformNode} node - An reference to the node.
  32245. */
  32246. constructor( name, type, node ) {
  32247. /**
  32248. * This flag can be used for type testing.
  32249. *
  32250. * @type {boolean}
  32251. * @readonly
  32252. * @default true
  32253. */
  32254. this.isNodeUniform = true;
  32255. /**
  32256. * The name of the uniform.
  32257. *
  32258. * @type {string}
  32259. */
  32260. this.name = name;
  32261. /**
  32262. * The type of the uniform.
  32263. *
  32264. * @type {string}
  32265. */
  32266. this.type = type;
  32267. /**
  32268. * An reference to the node.
  32269. *
  32270. * @type {UniformNode}
  32271. */
  32272. this.node = node.getSelf();
  32273. }
  32274. /**
  32275. * The value of the uniform node.
  32276. *
  32277. * @type {any}
  32278. */
  32279. get value() {
  32280. return this.node.value;
  32281. }
  32282. set value( val ) {
  32283. this.node.value = val;
  32284. }
  32285. /**
  32286. * The id of the uniform node.
  32287. *
  32288. * @type {number}
  32289. */
  32290. get id() {
  32291. return this.node.id;
  32292. }
  32293. /**
  32294. * The uniform node's group.
  32295. *
  32296. * @type {UniformGroupNode}
  32297. */
  32298. get groupNode() {
  32299. return this.node.groupNode;
  32300. }
  32301. }
  32302. /**
  32303. * {@link NodeBuilder} is going to create instances of this class during the build process
  32304. * of nodes. They represent the final shader variables that are going to be generated
  32305. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  32306. * this purpose.
  32307. */
  32308. class NodeVar {
  32309. /**
  32310. * Constructs a new node variable.
  32311. *
  32312. * @param {string} name - The name of the variable.
  32313. * @param {string} type - The type of the variable.
  32314. * @param {boolean} [readOnly=false] - The read-only flag.
  32315. * @param {?number} [count=null] - The size.
  32316. */
  32317. constructor( name, type, readOnly = false, count = null ) {
  32318. /**
  32319. * This flag can be used for type testing.
  32320. *
  32321. * @type {boolean}
  32322. * @readonly
  32323. * @default true
  32324. */
  32325. this.isNodeVar = true;
  32326. /**
  32327. * The name of the variable.
  32328. *
  32329. * @type {string}
  32330. */
  32331. this.name = name;
  32332. /**
  32333. * The type of the variable.
  32334. *
  32335. * @type {string}
  32336. */
  32337. this.type = type;
  32338. /**
  32339. * The read-only flag.
  32340. *
  32341. * @type {boolean}
  32342. */
  32343. this.readOnly = readOnly;
  32344. /**
  32345. * The size.
  32346. *
  32347. * @type {?number}
  32348. */
  32349. this.count = count;
  32350. }
  32351. }
  32352. /**
  32353. * {@link NodeBuilder} is going to create instances of this class during the build process
  32354. * of nodes. They represent the final shader varyings that are going to be generated
  32355. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  32356. * this purpose.
  32357. *
  32358. * @augments NodeVar
  32359. */
  32360. class NodeVarying extends NodeVar {
  32361. /**
  32362. * Constructs a new node varying.
  32363. *
  32364. * @param {string} name - The name of the varying.
  32365. * @param {string} type - The type of the varying.
  32366. * @param {?string} interpolationType - The interpolation type of the varying.
  32367. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32368. */
  32369. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  32370. super( name, type );
  32371. /**
  32372. * Whether this varying requires interpolation or not. This property can be used
  32373. * to check if the varying can be optimized for a variable.
  32374. *
  32375. * @type {boolean}
  32376. * @default false
  32377. */
  32378. this.needsInterpolation = false;
  32379. /**
  32380. * This flag can be used for type testing.
  32381. *
  32382. * @type {boolean}
  32383. * @readonly
  32384. * @default true
  32385. */
  32386. this.isNodeVarying = true;
  32387. /**
  32388. * The interpolation type of the varying data.
  32389. *
  32390. * @type {?string}
  32391. * @default null
  32392. */
  32393. this.interpolationType = interpolationType;
  32394. /**
  32395. * The interpolation sampling type of varying data.
  32396. *
  32397. * @type {?string}
  32398. * @default null
  32399. */
  32400. this.interpolationSampling = interpolationSampling;
  32401. }
  32402. }
  32403. /**
  32404. * {@link NodeBuilder} is going to create instances of this class during the build process
  32405. * of nodes. They represent user-defined, native shader code portions that are going to be
  32406. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  32407. * for this purpose.
  32408. */
  32409. class NodeCode {
  32410. /**
  32411. * Constructs a new code node.
  32412. *
  32413. * @param {string} name - The name of the code.
  32414. * @param {string} type - The node type.
  32415. * @param {string} [code=''] - The native shader code.
  32416. */
  32417. constructor( name, type, code = '' ) {
  32418. /**
  32419. * The name of the code.
  32420. *
  32421. * @type {string}
  32422. */
  32423. this.name = name;
  32424. /**
  32425. * The node type.
  32426. *
  32427. * @type {string}
  32428. */
  32429. this.type = type;
  32430. /**
  32431. * The native shader code.
  32432. *
  32433. * @type {string}
  32434. * @default ''
  32435. */
  32436. this.code = code;
  32437. Object.defineProperty( this, 'isNodeCode', { value: true } );
  32438. }
  32439. }
  32440. let _id$5 = 0;
  32441. /**
  32442. * This utility class is used in {@link NodeBuilder} as an internal
  32443. * cache data structure for node data.
  32444. */
  32445. class NodeCache {
  32446. /**
  32447. * Constructs a new node cache.
  32448. *
  32449. * @param {?NodeCache} parent - A reference to a parent cache.
  32450. */
  32451. constructor( parent = null ) {
  32452. /**
  32453. * The id of the cache.
  32454. *
  32455. * @type {number}
  32456. * @readonly
  32457. */
  32458. this.id = _id$5 ++;
  32459. /**
  32460. * A weak map for managing node data.
  32461. *
  32462. * @type {WeakMap<Node, Object>}
  32463. */
  32464. this.nodesData = new WeakMap();
  32465. /**
  32466. * Reference to a parent node cache.
  32467. *
  32468. * @type {?NodeCache}
  32469. * @default null
  32470. */
  32471. this.parent = parent;
  32472. }
  32473. /**
  32474. * Returns the data for the given node.
  32475. *
  32476. * @param {Node} node - The node.
  32477. * @return {?Object} The data for the node.
  32478. */
  32479. getData( node ) {
  32480. let data = this.nodesData.get( node );
  32481. if ( data === undefined && this.parent !== null ) {
  32482. data = this.parent.getData( node );
  32483. }
  32484. return data;
  32485. }
  32486. /**
  32487. * Sets the data for a given node.
  32488. *
  32489. * @param {Node} node - The node.
  32490. * @param {Object} data - The data that should be cached.
  32491. */
  32492. setData( node, data ) {
  32493. this.nodesData.set( node, data );
  32494. }
  32495. }
  32496. class StructType {
  32497. constructor( name, members ) {
  32498. this.name = name;
  32499. this.members = members;
  32500. this.output = false;
  32501. }
  32502. }
  32503. /**
  32504. * Abstract base class for uniforms.
  32505. *
  32506. * @abstract
  32507. * @private
  32508. */
  32509. class Uniform {
  32510. /**
  32511. * Constructs a new uniform.
  32512. *
  32513. * @param {string} name - The uniform's name.
  32514. * @param {any} value - The uniform's value.
  32515. */
  32516. constructor( name, value ) {
  32517. /**
  32518. * The uniform's name.
  32519. *
  32520. * @type {string}
  32521. */
  32522. this.name = name;
  32523. /**
  32524. * The uniform's value.
  32525. *
  32526. * @type {any}
  32527. */
  32528. this.value = value;
  32529. /**
  32530. * Used to build the uniform buffer according to the STD140 layout.
  32531. * Derived uniforms will set this property to a data type specific
  32532. * value.
  32533. *
  32534. * @type {number}
  32535. */
  32536. this.boundary = 0;
  32537. /**
  32538. * The item size. Derived uniforms will set this property to a data
  32539. * type specific value.
  32540. *
  32541. * @type {number}
  32542. */
  32543. this.itemSize = 0;
  32544. /**
  32545. * This property is set by {@link UniformsGroup} and marks
  32546. * the start position in the uniform buffer.
  32547. *
  32548. * @type {number}
  32549. */
  32550. this.offset = 0;
  32551. }
  32552. /**
  32553. * Sets the uniform's value.
  32554. *
  32555. * @param {any} value - The value to set.
  32556. */
  32557. setValue( value ) {
  32558. this.value = value;
  32559. }
  32560. /**
  32561. * Returns the uniform's value.
  32562. *
  32563. * @return {any} The value.
  32564. */
  32565. getValue() {
  32566. return this.value;
  32567. }
  32568. }
  32569. /**
  32570. * Represents a Number uniform.
  32571. *
  32572. * @private
  32573. * @augments Uniform
  32574. */
  32575. class NumberUniform extends Uniform {
  32576. /**
  32577. * Constructs a new Number uniform.
  32578. *
  32579. * @param {string} name - The uniform's name.
  32580. * @param {number} value - The uniform's value.
  32581. */
  32582. constructor( name, value = 0 ) {
  32583. super( name, value );
  32584. /**
  32585. * This flag can be used for type testing.
  32586. *
  32587. * @type {boolean}
  32588. * @readonly
  32589. * @default true
  32590. */
  32591. this.isNumberUniform = true;
  32592. this.boundary = 4;
  32593. this.itemSize = 1;
  32594. }
  32595. }
  32596. /**
  32597. * Represents a Vector2 uniform.
  32598. *
  32599. * @private
  32600. * @augments Uniform
  32601. */
  32602. class Vector2Uniform extends Uniform {
  32603. /**
  32604. * Constructs a new Number uniform.
  32605. *
  32606. * @param {string} name - The uniform's name.
  32607. * @param {Vector2} value - The uniform's value.
  32608. */
  32609. constructor( name, value = new Vector2() ) {
  32610. super( name, value );
  32611. /**
  32612. * This flag can be used for type testing.
  32613. *
  32614. * @type {boolean}
  32615. * @readonly
  32616. * @default true
  32617. */
  32618. this.isVector2Uniform = true;
  32619. this.boundary = 8;
  32620. this.itemSize = 2;
  32621. }
  32622. }
  32623. /**
  32624. * Represents a Vector3 uniform.
  32625. *
  32626. * @private
  32627. * @augments Uniform
  32628. */
  32629. class Vector3Uniform extends Uniform {
  32630. /**
  32631. * Constructs a new Number uniform.
  32632. *
  32633. * @param {string} name - The uniform's name.
  32634. * @param {Vector3} value - The uniform's value.
  32635. */
  32636. constructor( name, value = new Vector3() ) {
  32637. super( name, value );
  32638. /**
  32639. * This flag can be used for type testing.
  32640. *
  32641. * @type {boolean}
  32642. * @readonly
  32643. * @default true
  32644. */
  32645. this.isVector3Uniform = true;
  32646. this.boundary = 16;
  32647. this.itemSize = 3;
  32648. }
  32649. }
  32650. /**
  32651. * Represents a Vector4 uniform.
  32652. *
  32653. * @private
  32654. * @augments Uniform
  32655. */
  32656. class Vector4Uniform extends Uniform {
  32657. /**
  32658. * Constructs a new Number uniform.
  32659. *
  32660. * @param {string} name - The uniform's name.
  32661. * @param {Vector4} value - The uniform's value.
  32662. */
  32663. constructor( name, value = new Vector4() ) {
  32664. super( name, value );
  32665. /**
  32666. * This flag can be used for type testing.
  32667. *
  32668. * @type {boolean}
  32669. * @readonly
  32670. * @default true
  32671. */
  32672. this.isVector4Uniform = true;
  32673. this.boundary = 16;
  32674. this.itemSize = 4;
  32675. }
  32676. }
  32677. /**
  32678. * Represents a Color uniform.
  32679. *
  32680. * @private
  32681. * @augments Uniform
  32682. */
  32683. class ColorUniform extends Uniform {
  32684. /**
  32685. * Constructs a new Number uniform.
  32686. *
  32687. * @param {string} name - The uniform's name.
  32688. * @param {Color} value - The uniform's value.
  32689. */
  32690. constructor( name, value = new Color() ) {
  32691. super( name, value );
  32692. /**
  32693. * This flag can be used for type testing.
  32694. *
  32695. * @type {boolean}
  32696. * @readonly
  32697. * @default true
  32698. */
  32699. this.isColorUniform = true;
  32700. this.boundary = 16;
  32701. this.itemSize = 3;
  32702. }
  32703. }
  32704. /**
  32705. * Represents a Matrix2 uniform.
  32706. *
  32707. * @private
  32708. * @augments Uniform
  32709. */
  32710. class Matrix2Uniform extends Uniform {
  32711. /**
  32712. * Constructs a new Number uniform.
  32713. *
  32714. * @param {string} name - The uniform's name.
  32715. * @param {Matrix2} value - The uniform's value.
  32716. */
  32717. constructor( name, value = new Matrix2() ) {
  32718. super( name, value );
  32719. /**
  32720. * This flag can be used for type testing.
  32721. *
  32722. * @type {boolean}
  32723. * @readonly
  32724. * @default true
  32725. */
  32726. this.isMatrix2Uniform = true;
  32727. this.boundary = 8;
  32728. this.itemSize = 4;
  32729. }
  32730. }
  32731. /**
  32732. * Represents a Matrix3 uniform.
  32733. *
  32734. * @private
  32735. * @augments Uniform
  32736. */
  32737. class Matrix3Uniform extends Uniform {
  32738. /**
  32739. * Constructs a new Number uniform.
  32740. *
  32741. * @param {string} name - The uniform's name.
  32742. * @param {Matrix3} value - The uniform's value.
  32743. */
  32744. constructor( name, value = new Matrix3() ) {
  32745. super( name, value );
  32746. /**
  32747. * This flag can be used for type testing.
  32748. *
  32749. * @type {boolean}
  32750. * @readonly
  32751. * @default true
  32752. */
  32753. this.isMatrix3Uniform = true;
  32754. this.boundary = 48;
  32755. this.itemSize = 12;
  32756. }
  32757. }
  32758. /**
  32759. * Represents a Matrix4 uniform.
  32760. *
  32761. * @private
  32762. * @augments Uniform
  32763. */
  32764. class Matrix4Uniform extends Uniform {
  32765. /**
  32766. * Constructs a new Number uniform.
  32767. *
  32768. * @param {string} name - The uniform's name.
  32769. * @param {Matrix4} value - The uniform's value.
  32770. */
  32771. constructor( name, value = new Matrix4() ) {
  32772. super( name, value );
  32773. /**
  32774. * This flag can be used for type testing.
  32775. *
  32776. * @type {boolean}
  32777. * @readonly
  32778. * @default true
  32779. */
  32780. this.isMatrix4Uniform = true;
  32781. this.boundary = 64;
  32782. this.itemSize = 16;
  32783. }
  32784. }
  32785. /**
  32786. * A special form of Number uniform binding type.
  32787. * It's value is managed by a node object.
  32788. *
  32789. * @private
  32790. * @augments NumberUniform
  32791. */
  32792. class NumberNodeUniform extends NumberUniform {
  32793. /**
  32794. * Constructs a new node-based Number uniform.
  32795. *
  32796. * @param {NodeUniform} nodeUniform - The node uniform.
  32797. */
  32798. constructor( nodeUniform ) {
  32799. super( nodeUniform.name, nodeUniform.value );
  32800. /**
  32801. * The node uniform.
  32802. *
  32803. * @type {NodeUniform}
  32804. */
  32805. this.nodeUniform = nodeUniform;
  32806. }
  32807. /**
  32808. * Overwritten to return the value of the node uniform.
  32809. *
  32810. * @return {number} The value.
  32811. */
  32812. getValue() {
  32813. return this.nodeUniform.value;
  32814. }
  32815. /**
  32816. * Returns the node uniform data type.
  32817. *
  32818. * @return {string} The data type.
  32819. */
  32820. getType() {
  32821. return this.nodeUniform.type;
  32822. }
  32823. }
  32824. /**
  32825. * A special form of Vector2 uniform binding type.
  32826. * It's value is managed by a node object.
  32827. *
  32828. * @private
  32829. * @augments Vector2Uniform
  32830. */
  32831. class Vector2NodeUniform extends Vector2Uniform {
  32832. /**
  32833. * Constructs a new node-based Vector2 uniform.
  32834. *
  32835. * @param {NodeUniform} nodeUniform - The node uniform.
  32836. */
  32837. constructor( nodeUniform ) {
  32838. super( nodeUniform.name, nodeUniform.value );
  32839. /**
  32840. * The node uniform.
  32841. *
  32842. * @type {NodeUniform}
  32843. */
  32844. this.nodeUniform = nodeUniform;
  32845. }
  32846. /**
  32847. * Overwritten to return the value of the node uniform.
  32848. *
  32849. * @return {Vector2} The value.
  32850. */
  32851. getValue() {
  32852. return this.nodeUniform.value;
  32853. }
  32854. /**
  32855. * Returns the node uniform data type.
  32856. *
  32857. * @return {string} The data type.
  32858. */
  32859. getType() {
  32860. return this.nodeUniform.type;
  32861. }
  32862. }
  32863. /**
  32864. * A special form of Vector3 uniform binding type.
  32865. * It's value is managed by a node object.
  32866. *
  32867. * @private
  32868. * @augments Vector3Uniform
  32869. */
  32870. class Vector3NodeUniform extends Vector3Uniform {
  32871. /**
  32872. * Constructs a new node-based Vector3 uniform.
  32873. *
  32874. * @param {NodeUniform} nodeUniform - The node uniform.
  32875. */
  32876. constructor( nodeUniform ) {
  32877. super( nodeUniform.name, nodeUniform.value );
  32878. /**
  32879. * The node uniform.
  32880. *
  32881. * @type {NodeUniform}
  32882. */
  32883. this.nodeUniform = nodeUniform;
  32884. }
  32885. /**
  32886. * Overwritten to return the value of the node uniform.
  32887. *
  32888. * @return {Vector3} The value.
  32889. */
  32890. getValue() {
  32891. return this.nodeUniform.value;
  32892. }
  32893. /**
  32894. * Returns the node uniform data type.
  32895. *
  32896. * @return {string} The data type.
  32897. */
  32898. getType() {
  32899. return this.nodeUniform.type;
  32900. }
  32901. }
  32902. /**
  32903. * A special form of Vector4 uniform binding type.
  32904. * It's value is managed by a node object.
  32905. *
  32906. * @private
  32907. * @augments Vector4Uniform
  32908. */
  32909. class Vector4NodeUniform extends Vector4Uniform {
  32910. /**
  32911. * Constructs a new node-based Vector4 uniform.
  32912. *
  32913. * @param {NodeUniform} nodeUniform - The node uniform.
  32914. */
  32915. constructor( nodeUniform ) {
  32916. super( nodeUniform.name, nodeUniform.value );
  32917. /**
  32918. * The node uniform.
  32919. *
  32920. * @type {NodeUniform}
  32921. */
  32922. this.nodeUniform = nodeUniform;
  32923. }
  32924. /**
  32925. * Overwritten to return the value of the node uniform.
  32926. *
  32927. * @return {Vector4} The value.
  32928. */
  32929. getValue() {
  32930. return this.nodeUniform.value;
  32931. }
  32932. /**
  32933. * Returns the node uniform data type.
  32934. *
  32935. * @return {string} The data type.
  32936. */
  32937. getType() {
  32938. return this.nodeUniform.type;
  32939. }
  32940. }
  32941. /**
  32942. * A special form of Color uniform binding type.
  32943. * It's value is managed by a node object.
  32944. *
  32945. * @private
  32946. * @augments ColorUniform
  32947. */
  32948. class ColorNodeUniform extends ColorUniform {
  32949. /**
  32950. * Constructs a new node-based Color uniform.
  32951. *
  32952. * @param {NodeUniform} nodeUniform - The node uniform.
  32953. */
  32954. constructor( nodeUniform ) {
  32955. super( nodeUniform.name, nodeUniform.value );
  32956. /**
  32957. * The node uniform.
  32958. *
  32959. * @type {NodeUniform}
  32960. */
  32961. this.nodeUniform = nodeUniform;
  32962. }
  32963. /**
  32964. * Overwritten to return the value of the node uniform.
  32965. *
  32966. * @return {Color} The value.
  32967. */
  32968. getValue() {
  32969. return this.nodeUniform.value;
  32970. }
  32971. /**
  32972. * Returns the node uniform data type.
  32973. *
  32974. * @return {string} The data type.
  32975. */
  32976. getType() {
  32977. return this.nodeUniform.type;
  32978. }
  32979. }
  32980. /**
  32981. * A special form of Matrix2 uniform binding type.
  32982. * It's value is managed by a node object.
  32983. *
  32984. * @private
  32985. * @augments Matrix2Uniform
  32986. */
  32987. class Matrix2NodeUniform extends Matrix2Uniform {
  32988. /**
  32989. * Constructs a new node-based Matrix2 uniform.
  32990. *
  32991. * @param {NodeUniform} nodeUniform - The node uniform.
  32992. */
  32993. constructor( nodeUniform ) {
  32994. super( nodeUniform.name, nodeUniform.value );
  32995. /**
  32996. * The node uniform.
  32997. *
  32998. * @type {NodeUniform}
  32999. */
  33000. this.nodeUniform = nodeUniform;
  33001. }
  33002. /**
  33003. * Overwritten to return the value of the node uniform.
  33004. *
  33005. * @return {Matrix2} The value.
  33006. */
  33007. getValue() {
  33008. return this.nodeUniform.value;
  33009. }
  33010. /**
  33011. * Returns the node uniform data type.
  33012. *
  33013. * @return {string} The data type.
  33014. */
  33015. getType() {
  33016. return this.nodeUniform.type;
  33017. }
  33018. }
  33019. /**
  33020. * A special form of Matrix3 uniform binding type.
  33021. * It's value is managed by a node object.
  33022. *
  33023. * @private
  33024. * @augments Matrix3Uniform
  33025. */
  33026. class Matrix3NodeUniform extends Matrix3Uniform {
  33027. /**
  33028. * Constructs a new node-based Matrix3 uniform.
  33029. *
  33030. * @param {NodeUniform} nodeUniform - The node uniform.
  33031. */
  33032. constructor( nodeUniform ) {
  33033. super( nodeUniform.name, nodeUniform.value );
  33034. /**
  33035. * The node uniform.
  33036. *
  33037. * @type {NodeUniform}
  33038. */
  33039. this.nodeUniform = nodeUniform;
  33040. }
  33041. /**
  33042. * Overwritten to return the value of the node uniform.
  33043. *
  33044. * @return {Matrix3} The value.
  33045. */
  33046. getValue() {
  33047. return this.nodeUniform.value;
  33048. }
  33049. /**
  33050. * Returns the node uniform data type.
  33051. *
  33052. * @return {string} The data type.
  33053. */
  33054. getType() {
  33055. return this.nodeUniform.type;
  33056. }
  33057. }
  33058. /**
  33059. * A special form of Matrix4 uniform binding type.
  33060. * It's value is managed by a node object.
  33061. *
  33062. * @private
  33063. * @augments Matrix4Uniform
  33064. */
  33065. class Matrix4NodeUniform extends Matrix4Uniform {
  33066. /**
  33067. * Constructs a new node-based Matrix4 uniform.
  33068. *
  33069. * @param {NodeUniform} nodeUniform - The node uniform.
  33070. */
  33071. constructor( nodeUniform ) {
  33072. super( nodeUniform.name, nodeUniform.value );
  33073. /**
  33074. * The node uniform.
  33075. *
  33076. * @type {NodeUniform}
  33077. */
  33078. this.nodeUniform = nodeUniform;
  33079. }
  33080. /**
  33081. * Overwritten to return the value of the node uniform.
  33082. *
  33083. * @return {Matrix4} The value.
  33084. */
  33085. getValue() {
  33086. return this.nodeUniform.value;
  33087. }
  33088. /**
  33089. * Returns the node uniform data type.
  33090. *
  33091. * @return {string} The data type.
  33092. */
  33093. getType() {
  33094. return this.nodeUniform.type;
  33095. }
  33096. }
  33097. const rendererCache = new WeakMap();
  33098. const typeFromArray = new Map( [
  33099. [ Int8Array, 'int' ],
  33100. [ Int16Array, 'int' ],
  33101. [ Int32Array, 'int' ],
  33102. [ Uint8Array, 'uint' ],
  33103. [ Uint16Array, 'uint' ],
  33104. [ Uint32Array, 'uint' ],
  33105. [ Float32Array, 'float' ]
  33106. ] );
  33107. const toFloat = ( value ) => {
  33108. if ( /e/g.test( value ) ) {
  33109. return String( value ).replace( /\+/g, '' );
  33110. } else {
  33111. value = Number( value );
  33112. return value + ( value % 1 ? '' : '.0' );
  33113. }
  33114. };
  33115. /**
  33116. * Base class for builders which generate a shader program based
  33117. * on a 3D object and its node material definition.
  33118. */
  33119. class NodeBuilder {
  33120. /**
  33121. * Constructs a new node builder.
  33122. *
  33123. * @param {Object3D} object - The 3D object.
  33124. * @param {Renderer} renderer - The current renderer.
  33125. * @param {NodeParser} parser - A reference to a node parser.
  33126. */
  33127. constructor( object, renderer, parser ) {
  33128. /**
  33129. * The 3D object.
  33130. *
  33131. * @type {Object3D}
  33132. */
  33133. this.object = object;
  33134. /**
  33135. * The material of the 3D object.
  33136. *
  33137. * @type {?Material}
  33138. */
  33139. this.material = ( object && object.material ) || null;
  33140. /**
  33141. * The geometry of the 3D object.
  33142. *
  33143. * @type {?BufferGeometry}
  33144. */
  33145. this.geometry = ( object && object.geometry ) || null;
  33146. /**
  33147. * The current renderer.
  33148. *
  33149. * @type {Renderer}
  33150. */
  33151. this.renderer = renderer;
  33152. /**
  33153. * A reference to a node parser.
  33154. *
  33155. * @type {NodeParser}
  33156. */
  33157. this.parser = parser;
  33158. /**
  33159. * The scene the 3D object belongs to.
  33160. *
  33161. * @type {?Scene}
  33162. * @default null
  33163. */
  33164. this.scene = null;
  33165. /**
  33166. * The camera the 3D object is rendered with.
  33167. *
  33168. * @type {?Camera}
  33169. * @default null
  33170. */
  33171. this.camera = null;
  33172. /**
  33173. * A list of all nodes the builder is processing
  33174. * for this 3D object.
  33175. *
  33176. * @type {Array<Node>}
  33177. */
  33178. this.nodes = [];
  33179. /**
  33180. * A list of all sequential nodes.
  33181. *
  33182. * @type {Array<Node>}
  33183. */
  33184. this.sequentialNodes = [];
  33185. /**
  33186. * A list of all nodes which {@link Node#update} method should be executed.
  33187. *
  33188. * @type {Array<Node>}
  33189. */
  33190. this.updateNodes = [];
  33191. /**
  33192. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  33193. *
  33194. * @type {Array<Node>}
  33195. */
  33196. this.updateBeforeNodes = [];
  33197. /**
  33198. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  33199. *
  33200. * @type {Array<Node>}
  33201. */
  33202. this.updateAfterNodes = [];
  33203. /**
  33204. * A dictionary that assigns each node to a unique hash.
  33205. *
  33206. * @type {Object<number,Node>}
  33207. */
  33208. this.hashNodes = {};
  33209. /**
  33210. * A reference to a node material observer.
  33211. *
  33212. * @type {?NodeMaterialObserver}
  33213. * @default null
  33214. */
  33215. this.observer = null;
  33216. /**
  33217. * A reference to the current lights node.
  33218. *
  33219. * @type {?LightsNode}
  33220. * @default null
  33221. */
  33222. this.lightsNode = null;
  33223. /**
  33224. * A reference to the current environment node.
  33225. *
  33226. * @type {?Node}
  33227. * @default null
  33228. */
  33229. this.environmentNode = null;
  33230. /**
  33231. * A reference to the current fog node.
  33232. *
  33233. * @type {?Node}
  33234. * @default null
  33235. */
  33236. this.fogNode = null;
  33237. /**
  33238. * The current clipping context.
  33239. *
  33240. * @type {?ClippingContext}
  33241. */
  33242. this.clippingContext = null;
  33243. /**
  33244. * The generated vertex shader.
  33245. *
  33246. * @type {?string}
  33247. */
  33248. this.vertexShader = null;
  33249. /**
  33250. * The generated fragment shader.
  33251. *
  33252. * @type {?string}
  33253. */
  33254. this.fragmentShader = null;
  33255. /**
  33256. * The generated compute shader.
  33257. *
  33258. * @type {?string}
  33259. */
  33260. this.computeShader = null;
  33261. /**
  33262. * Nodes used in the primary flow of code generation.
  33263. *
  33264. * @type {Object<string,Array<Node>>}
  33265. */
  33266. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  33267. /**
  33268. * Nodes code from `.flowNodes`.
  33269. *
  33270. * @type {Object<string,string>}
  33271. */
  33272. this.flowCode = { vertex: '', fragment: '', compute: '' };
  33273. /**
  33274. * This dictionary holds the node uniforms of the builder.
  33275. * The uniforms are maintained in an array for each shader stage.
  33276. *
  33277. * @type {Object}
  33278. */
  33279. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  33280. /**
  33281. * This dictionary holds the output structs of the builder.
  33282. * The structs are maintained in an array for each shader stage.
  33283. *
  33284. * @type {Object}
  33285. */
  33286. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  33287. /**
  33288. * This dictionary holds the types of the builder.
  33289. *
  33290. * @type {Object}
  33291. */
  33292. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  33293. /**
  33294. * This dictionary holds the bindings for each shader stage.
  33295. *
  33296. * @type {Object}
  33297. */
  33298. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  33299. /**
  33300. * This dictionary maintains the binding indices per bind group.
  33301. *
  33302. * @type {Object}
  33303. */
  33304. this.bindingsIndexes = {};
  33305. /**
  33306. * Reference to the array of bind groups.
  33307. *
  33308. * @type {?Array<BindGroup>}
  33309. */
  33310. this.bindGroups = null;
  33311. /**
  33312. * This array holds the node attributes of this builder
  33313. * created via {@link AttributeNode}.
  33314. *
  33315. * @type {Array<NodeAttribute>}
  33316. */
  33317. this.attributes = [];
  33318. /**
  33319. * This array holds the node attributes of this builder
  33320. * created via {@link BufferAttributeNode}.
  33321. *
  33322. * @type {Array<NodeAttribute>}
  33323. */
  33324. this.bufferAttributes = [];
  33325. /**
  33326. * This array holds the node varyings of this builder.
  33327. *
  33328. * @type {Array<NodeVarying>}
  33329. */
  33330. this.varyings = [];
  33331. /**
  33332. * This dictionary holds the (native) node codes of this builder.
  33333. * The codes are maintained in an array for each shader stage.
  33334. *
  33335. * @type {Object<string,Array<NodeCode>>}
  33336. */
  33337. this.codes = {};
  33338. /**
  33339. * This dictionary holds the node variables of this builder.
  33340. * The variables are maintained in an array for each shader stage.
  33341. * This dictionary is also used to count the number of variables
  33342. * according to their type (const, vars).
  33343. *
  33344. * @type {Object<string,Array<NodeVar>|number>}
  33345. */
  33346. this.vars = {};
  33347. /**
  33348. * This dictionary holds the declarations for each shader stage.
  33349. *
  33350. * @type {Object}
  33351. */
  33352. this.declarations = {};
  33353. /**
  33354. * Current code flow.
  33355. * All code generated in this stack will be stored in `.flow`.
  33356. *
  33357. * @type {{code: string}}
  33358. */
  33359. this.flow = { code: '' };
  33360. /**
  33361. * A chain of nodes.
  33362. * Used to check recursive calls in node-graph.
  33363. *
  33364. * @type {Array<Node>}
  33365. */
  33366. this.chaining = [];
  33367. /**
  33368. * The current stack.
  33369. * This reflects the current process in the code block hierarchy,
  33370. * it is useful to know if the current process is inside a conditional for example.
  33371. *
  33372. * @type {StackNode}
  33373. */
  33374. this.stack = stack();
  33375. /**
  33376. * List of stack nodes.
  33377. * The current stack hierarchy is stored in an array.
  33378. *
  33379. * @type {Array<StackNode>}
  33380. */
  33381. this.stacks = [];
  33382. /**
  33383. * A tab value. Used for shader string generation.
  33384. *
  33385. * @type {string}
  33386. * @default '\t'
  33387. */
  33388. this.tab = '\t';
  33389. /**
  33390. * Reference to the current function node.
  33391. *
  33392. * @type {?FunctionNode}
  33393. * @default null
  33394. */
  33395. this.currentFunctionNode = null;
  33396. /**
  33397. * The builder's context.
  33398. *
  33399. * @type {Object}
  33400. */
  33401. this.context = {
  33402. material: this.material
  33403. };
  33404. /**
  33405. * The builder's cache.
  33406. *
  33407. * @type {NodeCache}
  33408. */
  33409. this.cache = new NodeCache();
  33410. /**
  33411. * Since the {@link NodeBuilder#cache} might be temporarily
  33412. * overwritten by other caches, this member retains the reference
  33413. * to the builder's own cache.
  33414. *
  33415. * @type {NodeCache}
  33416. * @default this.cache
  33417. */
  33418. this.globalCache = this.cache;
  33419. this.flowsData = new WeakMap();
  33420. /**
  33421. * The current shader stage.
  33422. *
  33423. * @type {?('vertex'|'fragment'|'compute'|'any')}
  33424. */
  33425. this.shaderStage = null;
  33426. /**
  33427. * The current build stage.
  33428. *
  33429. * @type {?('setup'|'analyze'|'generate')}
  33430. */
  33431. this.buildStage = null;
  33432. /**
  33433. * The sub-build layers.
  33434. *
  33435. * @type {Array<SubBuildNode>}
  33436. * @default []
  33437. */
  33438. this.subBuildLayers = [];
  33439. /**
  33440. * The current stack of nodes.
  33441. *
  33442. * @type {?StackNode}
  33443. * @default null
  33444. */
  33445. this.currentStack = null;
  33446. /**
  33447. * The current sub-build TSL function(Fn).
  33448. *
  33449. * @type {?string}
  33450. * @default null
  33451. */
  33452. this.subBuildFn = null;
  33453. }
  33454. /**
  33455. * Returns the bind groups of the current renderer.
  33456. *
  33457. * @return {ChainMap} The cache.
  33458. */
  33459. getBindGroupsCache() {
  33460. let bindGroupsCache = rendererCache.get( this.renderer );
  33461. if ( bindGroupsCache === undefined ) {
  33462. bindGroupsCache = new ChainMap();
  33463. rendererCache.set( this.renderer, bindGroupsCache );
  33464. }
  33465. return bindGroupsCache;
  33466. }
  33467. /**
  33468. * Factory method for creating an instance of {@link RenderTarget} with the given
  33469. * dimensions and options.
  33470. *
  33471. * @param {number} width - The width of the render target.
  33472. * @param {number} height - The height of the render target.
  33473. * @param {Object} options - The options of the render target.
  33474. * @return {RenderTarget} The render target.
  33475. */
  33476. createRenderTarget( width, height, options ) {
  33477. return new RenderTarget( width, height, options );
  33478. }
  33479. /**
  33480. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  33481. * dimensions and options.
  33482. *
  33483. * @param {number} size - The size of the cube render target.
  33484. * @param {Object} options - The options of the cube render target.
  33485. * @return {CubeRenderTarget} The cube render target.
  33486. */
  33487. createCubeRenderTarget( size, options ) {
  33488. return new CubeRenderTarget( size, options );
  33489. }
  33490. /**
  33491. * Whether the given node is included in the internal array of nodes or not.
  33492. *
  33493. * @param {Node} node - The node to test.
  33494. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  33495. */
  33496. includes( node ) {
  33497. return this.nodes.includes( node );
  33498. }
  33499. /**
  33500. * Returns the output struct name which is required by
  33501. * {@link OutputStructNode}.
  33502. *
  33503. * @abstract
  33504. * @return {string} The name of the output struct.
  33505. */
  33506. getOutputStructName() {}
  33507. /**
  33508. * Returns a bind group for the given group name and binding.
  33509. *
  33510. * @private
  33511. * @param {string} groupName - The group name.
  33512. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  33513. * @return {BindGroup} The bind group
  33514. */
  33515. _getBindGroup( groupName, bindings ) {
  33516. const bindGroupsCache = this.getBindGroupsCache();
  33517. //
  33518. const bindingsArray = [];
  33519. let sharedGroup = true;
  33520. for ( const binding of bindings ) {
  33521. bindingsArray.push( binding );
  33522. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  33523. }
  33524. //
  33525. let bindGroup;
  33526. if ( sharedGroup ) {
  33527. bindGroup = bindGroupsCache.get( bindingsArray );
  33528. if ( bindGroup === undefined ) {
  33529. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  33530. bindGroupsCache.set( bindingsArray, bindGroup );
  33531. }
  33532. } else {
  33533. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  33534. }
  33535. return bindGroup;
  33536. }
  33537. /**
  33538. * Returns an array of node uniform groups for the given group name and shader stage.
  33539. *
  33540. * @param {string} groupName - The group name.
  33541. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33542. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  33543. */
  33544. getBindGroupArray( groupName, shaderStage ) {
  33545. const bindings = this.bindings[ shaderStage ];
  33546. let bindGroup = bindings[ groupName ];
  33547. if ( bindGroup === undefined ) {
  33548. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  33549. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  33550. }
  33551. bindings[ groupName ] = bindGroup = [];
  33552. }
  33553. return bindGroup;
  33554. }
  33555. /**
  33556. * Returns a list bindings of all shader stages separated by groups.
  33557. *
  33558. * @return {Array<BindGroup>} The list of bindings.
  33559. */
  33560. getBindings() {
  33561. let bindingsGroups = this.bindGroups;
  33562. if ( bindingsGroups === null ) {
  33563. const groups = {};
  33564. const bindings = this.bindings;
  33565. for ( const shaderStage of shaderStages ) {
  33566. for ( const groupName in bindings[ shaderStage ] ) {
  33567. const uniforms = bindings[ shaderStage ][ groupName ];
  33568. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  33569. groupUniforms.push( ...uniforms );
  33570. }
  33571. }
  33572. bindingsGroups = [];
  33573. for ( const groupName in groups ) {
  33574. const group = groups[ groupName ];
  33575. const bindingsGroup = this._getBindGroup( groupName, group );
  33576. bindingsGroups.push( bindingsGroup );
  33577. }
  33578. this.bindGroups = bindingsGroups;
  33579. }
  33580. return bindingsGroups;
  33581. }
  33582. /**
  33583. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  33584. */
  33585. sortBindingGroups() {
  33586. const bindingsGroups = this.getBindings();
  33587. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  33588. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  33589. const bindingGroup = bindingsGroups[ i ];
  33590. this.bindingsIndexes[ bindingGroup.name ].group = i;
  33591. bindingGroup.index = i;
  33592. }
  33593. }
  33594. /**
  33595. * The builder maintains each node in a hash-based dictionary.
  33596. * This method sets the given node (value) with the given hash (key) into this dictionary.
  33597. *
  33598. * @param {Node} node - The node to add.
  33599. * @param {number} hash - The hash of the node.
  33600. */
  33601. setHashNode( node, hash ) {
  33602. this.hashNodes[ hash ] = node;
  33603. }
  33604. /**
  33605. * Adds a node to this builder.
  33606. *
  33607. * @param {Node} node - The node to add.
  33608. */
  33609. addNode( node ) {
  33610. if ( this.nodes.includes( node ) === false ) {
  33611. this.nodes.push( node );
  33612. this.setHashNode( node, node.getHash( this ) );
  33613. }
  33614. }
  33615. /**
  33616. * It is used to add Nodes that will be used as FRAME and RENDER events,
  33617. * and need to follow a certain sequence in the calls to work correctly.
  33618. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  33619. *
  33620. * @param {Node} node - The node to add.
  33621. */
  33622. addSequentialNode( node ) {
  33623. if ( this.sequentialNodes.includes( node ) === false ) {
  33624. this.sequentialNodes.push( node );
  33625. }
  33626. }
  33627. /**
  33628. * Checks the update types of nodes
  33629. */
  33630. buildUpdateNodes() {
  33631. for ( const node of this.nodes ) {
  33632. const updateType = node.getUpdateType();
  33633. if ( updateType !== NodeUpdateType.NONE ) {
  33634. this.updateNodes.push( node.getSelf() );
  33635. }
  33636. }
  33637. for ( const node of this.sequentialNodes ) {
  33638. const updateBeforeType = node.getUpdateBeforeType();
  33639. const updateAfterType = node.getUpdateAfterType();
  33640. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  33641. this.updateBeforeNodes.push( node.getSelf() );
  33642. }
  33643. if ( updateAfterType !== NodeUpdateType.NONE ) {
  33644. this.updateAfterNodes.push( node.getSelf() );
  33645. }
  33646. }
  33647. }
  33648. /**
  33649. * A reference the current node which is the
  33650. * last node in the chain of nodes.
  33651. *
  33652. * @type {Node}
  33653. */
  33654. get currentNode() {
  33655. return this.chaining[ this.chaining.length - 1 ];
  33656. }
  33657. /**
  33658. * Whether the given texture is filtered or not.
  33659. *
  33660. * @param {Texture} texture - The texture to check.
  33661. * @return {boolean} Whether the given texture is filtered or not.
  33662. */
  33663. isFilteredTexture( texture ) {
  33664. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  33665. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  33666. }
  33667. /**
  33668. * Adds the given node to the internal node chain.
  33669. * This is used to check recursive calls in node-graph.
  33670. *
  33671. * @param {Node} node - The node to add.
  33672. */
  33673. addChain( node ) {
  33674. /*
  33675. if ( this.chaining.indexOf( node ) !== - 1 ) {
  33676. console.warn( 'Recursive node: ', node );
  33677. }
  33678. */
  33679. this.chaining.push( node );
  33680. }
  33681. /**
  33682. * Removes the given node from the internal node chain.
  33683. *
  33684. * @param {Node} node - The node to remove.
  33685. */
  33686. removeChain( node ) {
  33687. const lastChain = this.chaining.pop();
  33688. if ( lastChain !== node ) {
  33689. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  33690. }
  33691. }
  33692. /**
  33693. * Returns the native shader method name for a given generic name. E.g.
  33694. * the method name `textureDimensions` matches the WGSL name but must be
  33695. * resolved to `textureSize` in GLSL.
  33696. *
  33697. * @abstract
  33698. * @param {string} method - The method name to resolve.
  33699. * @return {string} The resolved method name.
  33700. */
  33701. getMethod( method ) {
  33702. return method;
  33703. }
  33704. /**
  33705. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  33706. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  33707. *
  33708. * @abstract
  33709. * @param {string} condSnippet - The condition determining which expression gets resolved.
  33710. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  33711. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  33712. * @return {string} The resolved method name.
  33713. */
  33714. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  33715. return null;
  33716. }
  33717. /**
  33718. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  33719. *
  33720. * @param {number} hash - The hash of the node.
  33721. * @return {Node} The found node.
  33722. */
  33723. getNodeFromHash( hash ) {
  33724. return this.hashNodes[ hash ];
  33725. }
  33726. /**
  33727. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  33728. *
  33729. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  33730. * @param {Node} node - The node to add.
  33731. * @return {Node} The node.
  33732. */
  33733. addFlow( shaderStage, node ) {
  33734. this.flowNodes[ shaderStage ].push( node );
  33735. return node;
  33736. }
  33737. /**
  33738. * Sets builder's context.
  33739. *
  33740. * @param {Object} context - The context to set.
  33741. */
  33742. setContext( context ) {
  33743. this.context = context;
  33744. }
  33745. /**
  33746. * Returns the builder's current context.
  33747. *
  33748. * @return {Object} The builder's current context.
  33749. */
  33750. getContext() {
  33751. return this.context;
  33752. }
  33753. /**
  33754. * Gets a context used in shader construction that can be shared across different materials.
  33755. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  33756. *
  33757. * @return {Object} The builder's current context without material.
  33758. */
  33759. getSharedContext() {
  33760. ({ ...this.context });
  33761. return this.context;
  33762. }
  33763. /**
  33764. * Sets builder's cache.
  33765. *
  33766. * @param {NodeCache} cache - The cache to set.
  33767. */
  33768. setCache( cache ) {
  33769. this.cache = cache;
  33770. }
  33771. /**
  33772. * Returns the builder's current cache.
  33773. *
  33774. * @return {NodeCache} The builder's current cache.
  33775. */
  33776. getCache() {
  33777. return this.cache;
  33778. }
  33779. /**
  33780. * Returns a cache for the given node.
  33781. *
  33782. * @param {Node} node - The node.
  33783. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  33784. * @return {NodeCache} The cache.
  33785. */
  33786. getCacheFromNode( node, parent = true ) {
  33787. const data = this.getDataFromNode( node );
  33788. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  33789. return data.cache;
  33790. }
  33791. /**
  33792. * Whether the requested feature is available or not.
  33793. *
  33794. * @abstract
  33795. * @param {string} name - The requested feature.
  33796. * @return {boolean} Whether the requested feature is supported or not.
  33797. */
  33798. isAvailable( /*name*/ ) {
  33799. return false;
  33800. }
  33801. /**
  33802. * Returns the vertexIndex input variable as a native shader string.
  33803. *
  33804. * @abstract
  33805. * @return {string} The instanceIndex shader string.
  33806. */
  33807. getVertexIndex() {
  33808. console.warn( 'Abstract function.' );
  33809. }
  33810. /**
  33811. * Returns the instanceIndex input variable as a native shader string.
  33812. *
  33813. * @abstract
  33814. * @return {string} The instanceIndex shader string.
  33815. */
  33816. getInstanceIndex() {
  33817. console.warn( 'Abstract function.' );
  33818. }
  33819. /**
  33820. * Returns the drawIndex input variable as a native shader string.
  33821. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  33822. *
  33823. * @abstract
  33824. * @return {?string} The drawIndex shader string.
  33825. */
  33826. getDrawIndex() {
  33827. console.warn( 'Abstract function.' );
  33828. }
  33829. /**
  33830. * Returns the frontFacing input variable as a native shader string.
  33831. *
  33832. * @abstract
  33833. * @return {string} The frontFacing shader string.
  33834. */
  33835. getFrontFacing() {
  33836. console.warn( 'Abstract function.' );
  33837. }
  33838. /**
  33839. * Returns the fragCoord input variable as a native shader string.
  33840. *
  33841. * @abstract
  33842. * @return {string} The fragCoord shader string.
  33843. */
  33844. getFragCoord() {
  33845. console.warn( 'Abstract function.' );
  33846. }
  33847. /**
  33848. * Whether to flip texture data along its vertical axis or not. WebGL needs
  33849. * this method evaluate to `true`, WebGPU to `false`.
  33850. *
  33851. * @abstract
  33852. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  33853. */
  33854. isFlipY() {
  33855. return false;
  33856. }
  33857. /**
  33858. * Calling this method increases the usage count for the given node by one.
  33859. *
  33860. * @param {Node} node - The node to increase the usage count for.
  33861. * @return {number} The updated usage count.
  33862. */
  33863. increaseUsage( node ) {
  33864. const nodeData = this.getDataFromNode( node );
  33865. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  33866. return nodeData.usageCount;
  33867. }
  33868. /**
  33869. * Generates a texture sample shader string for the given texture data.
  33870. *
  33871. * @abstract
  33872. * @param {Texture} texture - The texture.
  33873. * @param {string} textureProperty - The texture property name.
  33874. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  33875. * @return {string} The generated shader string.
  33876. */
  33877. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  33878. console.warn( 'Abstract function.' );
  33879. }
  33880. /**
  33881. * Generates a texture LOD shader string for the given texture data.
  33882. *
  33883. * @abstract
  33884. * @param {Texture} texture - The texture.
  33885. * @param {string} textureProperty - The texture property name.
  33886. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  33887. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  33888. * @param {string} levelSnippet - Snippet defining the mip level.
  33889. * @return {string} The generated shader string.
  33890. */
  33891. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  33892. console.warn( 'Abstract function.' );
  33893. }
  33894. /**
  33895. * Generates the array declaration string.
  33896. *
  33897. * @param {string} type - The type.
  33898. * @param {?number} [count] - The count.
  33899. * @return {string} The generated value as a shader string.
  33900. */
  33901. generateArrayDeclaration( type, count ) {
  33902. return this.getType( type ) + '[ ' + count + ' ]';
  33903. }
  33904. /**
  33905. * Generates the array shader string for the given type and value.
  33906. *
  33907. * @param {string} type - The type.
  33908. * @param {?number} [count] - The count.
  33909. * @param {?Array<Node>} [values=null] - The default values.
  33910. * @return {string} The generated value as a shader string.
  33911. */
  33912. generateArray( type, count, values = null ) {
  33913. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  33914. for ( let i = 0; i < count; i ++ ) {
  33915. const value = values ? values[ i ] : null;
  33916. if ( value !== null ) {
  33917. snippet += value.build( this, type );
  33918. } else {
  33919. snippet += this.generateConst( type );
  33920. }
  33921. if ( i < count - 1 ) snippet += ', ';
  33922. }
  33923. snippet += ' )';
  33924. return snippet;
  33925. }
  33926. /**
  33927. * Generates the struct shader string.
  33928. *
  33929. * @param {string} type - The type.
  33930. * @param {Array<Object>} [membersLayout] - The count.
  33931. * @param {?Array<Node>} [values=null] - The default values.
  33932. * @return {string} The generated value as a shader string.
  33933. */
  33934. generateStruct( type, membersLayout, values = null ) {
  33935. const snippets = [];
  33936. for ( const member of membersLayout ) {
  33937. const { name, type } = member;
  33938. if ( values && values[ name ] && values[ name ].isNode ) {
  33939. snippets.push( values[ name ].build( this, type ) );
  33940. } else {
  33941. snippets.push( this.generateConst( type ) );
  33942. }
  33943. }
  33944. return type + '( ' + snippets.join( ', ' ) + ' )';
  33945. }
  33946. /**
  33947. * Generates the shader string for the given type and value.
  33948. *
  33949. * @param {string} type - The type.
  33950. * @param {?any} [value=null] - The value.
  33951. * @return {string} The generated value as a shader string.
  33952. */
  33953. generateConst( type, value = null ) {
  33954. if ( value === null ) {
  33955. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  33956. else if ( type === 'bool' ) value = false;
  33957. else if ( type === 'color' ) value = new Color();
  33958. else if ( type === 'vec2' ) value = new Vector2();
  33959. else if ( type === 'vec3' ) value = new Vector3();
  33960. else if ( type === 'vec4' ) value = new Vector4();
  33961. }
  33962. if ( type === 'float' ) return toFloat( value );
  33963. if ( type === 'int' ) return `${ Math.round( value ) }`;
  33964. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  33965. if ( type === 'bool' ) return value ? 'true' : 'false';
  33966. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  33967. const typeLength = this.getTypeLength( type );
  33968. const componentType = this.getComponentType( type );
  33969. const generateConst = value => this.generateConst( componentType, value );
  33970. if ( typeLength === 2 ) {
  33971. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  33972. } else if ( typeLength === 3 ) {
  33973. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  33974. } else if ( typeLength === 4 && type !== 'mat2' ) {
  33975. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  33976. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  33977. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  33978. } else if ( typeLength > 4 ) {
  33979. return `${ this.getType( type ) }()`;
  33980. }
  33981. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  33982. }
  33983. /**
  33984. * It might be necessary to convert certain data types to different ones
  33985. * so this method can be used to hide the conversion.
  33986. *
  33987. * @param {string} type - The type.
  33988. * @return {string} The updated type.
  33989. */
  33990. getType( type ) {
  33991. if ( type === 'color' ) return 'vec3';
  33992. return type;
  33993. }
  33994. /**
  33995. * Whether the given attribute name is defined in the geometry or not.
  33996. *
  33997. * @param {string} name - The attribute name.
  33998. * @return {boolean} Whether the given attribute name is defined in the geometry.
  33999. */
  34000. hasGeometryAttribute( name ) {
  34001. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  34002. }
  34003. /**
  34004. * Returns a node attribute for the given name and type.
  34005. *
  34006. * @param {string} name - The attribute's name.
  34007. * @param {string} type - The attribute's type.
  34008. * @return {NodeAttribute} The node attribute.
  34009. */
  34010. getAttribute( name, type ) {
  34011. const attributes = this.attributes;
  34012. // find attribute
  34013. for ( const attribute of attributes ) {
  34014. if ( attribute.name === name ) {
  34015. return attribute;
  34016. }
  34017. }
  34018. // create a new if no exist
  34019. const attribute = new NodeAttribute( name, type );
  34020. this.registerDeclaration( attribute );
  34021. attributes.push( attribute );
  34022. return attribute;
  34023. }
  34024. /**
  34025. * Returns for the given node and shader stage the property name for the shader.
  34026. *
  34027. * @param {Node} node - The node.
  34028. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34029. * @return {string} The property name.
  34030. */
  34031. getPropertyName( node/*, shaderStage*/ ) {
  34032. return node.name;
  34033. }
  34034. /**
  34035. * Whether the given type is a vector type or not.
  34036. *
  34037. * @param {string} type - The type to check.
  34038. * @return {boolean} Whether the given type is a vector type or not.
  34039. */
  34040. isVector( type ) {
  34041. return /vec\d/.test( type );
  34042. }
  34043. /**
  34044. * Whether the given type is a matrix type or not.
  34045. *
  34046. * @param {string} type - The type to check.
  34047. * @return {boolean} Whether the given type is a matrix type or not.
  34048. */
  34049. isMatrix( type ) {
  34050. return /mat\d/.test( type );
  34051. }
  34052. /**
  34053. * Whether the given type is a reference type or not.
  34054. *
  34055. * @param {string} type - The type to check.
  34056. * @return {boolean} Whether the given type is a reference type or not.
  34057. */
  34058. isReference( type ) {
  34059. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  34060. }
  34061. /**
  34062. * Checks if the given texture requires a manual conversion to the working color space.
  34063. *
  34064. * @abstract
  34065. * @param {Texture} texture - The texture to check.
  34066. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  34067. */
  34068. needsToWorkingColorSpace( /*texture*/ ) {
  34069. return false;
  34070. }
  34071. /**
  34072. * Returns the component type of a given texture.
  34073. *
  34074. * @param {Texture} texture - The texture.
  34075. * @return {string} The component type.
  34076. */
  34077. getComponentTypeFromTexture( texture ) {
  34078. const type = texture.type;
  34079. if ( texture.isDataTexture ) {
  34080. if ( type === IntType ) return 'int';
  34081. if ( type === UnsignedIntType ) return 'uint';
  34082. }
  34083. return 'float';
  34084. }
  34085. /**
  34086. * Returns the element type for a given type.
  34087. *
  34088. * @param {string} type - The type.
  34089. * @return {string} The element type.
  34090. */
  34091. getElementType( type ) {
  34092. if ( type === 'mat2' ) return 'vec2';
  34093. if ( type === 'mat3' ) return 'vec3';
  34094. if ( type === 'mat4' ) return 'vec4';
  34095. return this.getComponentType( type );
  34096. }
  34097. /**
  34098. * Returns the component type for a given type.
  34099. *
  34100. * @param {string} type - The type.
  34101. * @return {string} The component type.
  34102. */
  34103. getComponentType( type ) {
  34104. type = this.getVectorType( type );
  34105. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  34106. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  34107. if ( componentType === null ) return null;
  34108. if ( componentType[ 1 ] === 'b' ) return 'bool';
  34109. if ( componentType[ 1 ] === 'i' ) return 'int';
  34110. if ( componentType[ 1 ] === 'u' ) return 'uint';
  34111. return 'float';
  34112. }
  34113. /**
  34114. * Returns the vector type for a given type.
  34115. *
  34116. * @param {string} type - The type.
  34117. * @return {string} The vector type.
  34118. */
  34119. getVectorType( type ) {
  34120. if ( type === 'color' ) return 'vec3';
  34121. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  34122. return type;
  34123. }
  34124. /**
  34125. * Returns the data type for the given the length and component type.
  34126. *
  34127. * @param {number} length - The length.
  34128. * @param {string} [componentType='float'] - The component type.
  34129. * @return {string} The type.
  34130. */
  34131. getTypeFromLength( length, componentType = 'float' ) {
  34132. if ( length === 1 ) return componentType;
  34133. let baseType = getTypeFromLength( length );
  34134. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  34135. // fix edge case for mat2x2 being same size as vec4
  34136. if ( /mat2/.test( componentType ) === true ) {
  34137. baseType = baseType.replace( 'vec', 'mat' );
  34138. }
  34139. return prefix + baseType;
  34140. }
  34141. /**
  34142. * Returns the type for a given typed array.
  34143. *
  34144. * @param {TypedArray} array - The typed array.
  34145. * @return {string} The type.
  34146. */
  34147. getTypeFromArray( array ) {
  34148. return typeFromArray.get( array.constructor );
  34149. }
  34150. /**
  34151. * Returns the type is an integer type.
  34152. *
  34153. * @param {string} type - The type.
  34154. * @return {boolean} Whether the type is an integer type or not.
  34155. */
  34156. isInteger( type ) {
  34157. return /int|uint|(i|u)vec/.test( type );
  34158. }
  34159. /**
  34160. * Returns the type for a given buffer attribute.
  34161. *
  34162. * @param {BufferAttribute} attribute - The buffer attribute.
  34163. * @return {string} The type.
  34164. */
  34165. getTypeFromAttribute( attribute ) {
  34166. let dataAttribute = attribute;
  34167. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  34168. const array = dataAttribute.array;
  34169. const itemSize = attribute.itemSize;
  34170. const normalized = attribute.normalized;
  34171. let arrayType;
  34172. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  34173. arrayType = this.getTypeFromArray( array );
  34174. }
  34175. return this.getTypeFromLength( itemSize, arrayType );
  34176. }
  34177. /**
  34178. * Returns the length for the given data type.
  34179. *
  34180. * @param {string} type - The data type.
  34181. * @return {number} The length.
  34182. */
  34183. getTypeLength( type ) {
  34184. const vecType = this.getVectorType( type );
  34185. const vecNum = /vec([2-4])/.exec( vecType );
  34186. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  34187. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  34188. if ( /mat2/.test( type ) === true ) return 4;
  34189. if ( /mat3/.test( type ) === true ) return 9;
  34190. if ( /mat4/.test( type ) === true ) return 16;
  34191. return 0;
  34192. }
  34193. /**
  34194. * Returns the vector type for a given matrix type.
  34195. *
  34196. * @param {string} type - The matrix type.
  34197. * @return {string} The vector type.
  34198. */
  34199. getVectorFromMatrix( type ) {
  34200. return type.replace( 'mat', 'vec' );
  34201. }
  34202. /**
  34203. * For a given type this method changes the component type to the
  34204. * given value. E.g. `vec4` should be changed to the new component type
  34205. * `uint` which results in `uvec4`.
  34206. *
  34207. * @param {string} type - The type.
  34208. * @param {string} newComponentType - The new component type.
  34209. * @return {string} The new type.
  34210. */
  34211. changeComponentType( type, newComponentType ) {
  34212. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  34213. }
  34214. /**
  34215. * Returns the integer type pendant for the given type.
  34216. *
  34217. * @param {string} type - The type.
  34218. * @return {string} The integer type.
  34219. */
  34220. getIntegerType( type ) {
  34221. const componentType = this.getComponentType( type );
  34222. if ( componentType === 'int' || componentType === 'uint' ) return type;
  34223. return this.changeComponentType( type, 'int' );
  34224. }
  34225. /**
  34226. * Adds a stack node to the internal stack.
  34227. *
  34228. * @return {StackNode} The added stack node.
  34229. */
  34230. addStack() {
  34231. this.stack = stack( this.stack );
  34232. this.stacks.push( getCurrentStack() || this.stack );
  34233. setCurrentStack( this.stack );
  34234. return this.stack;
  34235. }
  34236. /**
  34237. * Removes the last stack node from the internal stack.
  34238. *
  34239. * @return {StackNode} The removed stack node.
  34240. */
  34241. removeStack() {
  34242. const lastStack = this.stack;
  34243. this.stack = lastStack.parent;
  34244. setCurrentStack( this.stacks.pop() );
  34245. return lastStack;
  34246. }
  34247. /**
  34248. * The builder maintains (cached) data for each node during the building process. This method
  34249. * can be used to get these data for a specific shader stage and cache.
  34250. *
  34251. * @param {Node} node - The node to get the data for.
  34252. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34253. * @param {?NodeCache} cache - An optional cache.
  34254. * @return {Object} The node data.
  34255. */
  34256. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  34257. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  34258. let nodeData = cache.getData( node );
  34259. if ( nodeData === undefined ) {
  34260. nodeData = {};
  34261. cache.setData( node, nodeData );
  34262. }
  34263. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  34264. //
  34265. let data = nodeData[ shaderStage ];
  34266. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  34267. const subBuild = this.getClosestSubBuild( subBuilds );
  34268. if ( subBuild ) {
  34269. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  34270. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  34271. data.subBuilds = subBuilds;
  34272. }
  34273. return data;
  34274. }
  34275. /**
  34276. * Returns the properties for the given node and shader stage.
  34277. *
  34278. * @param {Node} node - The node to get the properties for.
  34279. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  34280. * @return {Object} The node properties.
  34281. */
  34282. getNodeProperties( node, shaderStage = 'any' ) {
  34283. const nodeData = this.getDataFromNode( node, shaderStage );
  34284. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  34285. }
  34286. /**
  34287. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  34288. *
  34289. * @param {BufferAttributeNode} node - The buffer attribute node.
  34290. * @param {string} type - The node type.
  34291. * @return {NodeAttribute} The node attribute.
  34292. */
  34293. getBufferAttributeFromNode( node, type ) {
  34294. const nodeData = this.getDataFromNode( node );
  34295. let bufferAttribute = nodeData.bufferAttribute;
  34296. if ( bufferAttribute === undefined ) {
  34297. const index = this.uniforms.index ++;
  34298. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  34299. this.bufferAttributes.push( bufferAttribute );
  34300. nodeData.bufferAttribute = bufferAttribute;
  34301. }
  34302. return bufferAttribute;
  34303. }
  34304. /**
  34305. * Returns an instance of {@link StructType} for the given struct name and shader stage
  34306. * or null if not found.
  34307. *
  34308. * @param {string} name - The name of the struct.
  34309. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34310. * @return {?StructType} The struct type or null if not found.
  34311. */
  34312. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  34313. return this.types[ shaderStage ][ name ] || null;
  34314. }
  34315. /**
  34316. * Returns an instance of {@link StructType} for the given output struct node.
  34317. *
  34318. * @param {OutputStructNode} node - The output struct node.
  34319. * @param {Array<Object>} membersLayout - The output struct types.
  34320. * @param {?string} [name=null] - The name of the struct.
  34321. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34322. * @return {StructType} The struct type attribute.
  34323. */
  34324. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  34325. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34326. let structType = nodeData.structType;
  34327. if ( structType === undefined ) {
  34328. const index = this.structs.index ++;
  34329. if ( name === null ) name = 'StructType' + index;
  34330. structType = new StructType( name, membersLayout );
  34331. this.structs[ shaderStage ].push( structType );
  34332. this.types[ shaderStage ][ name ] = node;
  34333. nodeData.structType = structType;
  34334. }
  34335. return structType;
  34336. }
  34337. /**
  34338. * Returns an instance of {@link StructType} for the given output struct node.
  34339. *
  34340. * @param {OutputStructNode} node - The output struct node.
  34341. * @param {Array<Object>} membersLayout - The output struct types.
  34342. * @return {StructType} The struct type attribute.
  34343. */
  34344. getOutputStructTypeFromNode( node, membersLayout ) {
  34345. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  34346. structType.output = true;
  34347. return structType;
  34348. }
  34349. /**
  34350. * Returns an instance of {@link NodeUniform} for the given uniform node.
  34351. *
  34352. * @param {UniformNode} node - The uniform node.
  34353. * @param {string} type - The uniform type.
  34354. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34355. * @param {?string} name - The name of the uniform.
  34356. * @return {NodeUniform} The node uniform.
  34357. */
  34358. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  34359. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34360. let nodeUniform = nodeData.uniform;
  34361. if ( nodeUniform === undefined ) {
  34362. const index = this.uniforms.index ++;
  34363. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  34364. this.uniforms[ shaderStage ].push( nodeUniform );
  34365. this.registerDeclaration( nodeUniform );
  34366. nodeData.uniform = nodeUniform;
  34367. }
  34368. return nodeUniform;
  34369. }
  34370. /**
  34371. * Returns an instance of {@link NodeVar} for the given variable node.
  34372. *
  34373. * @param {VarNode} node - The variable node.
  34374. * @param {?string} name - The variable's name.
  34375. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  34376. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34377. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  34378. *
  34379. * @return {NodeVar} The node variable.
  34380. */
  34381. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  34382. const nodeData = this.getDataFromNode( node, shaderStage );
  34383. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  34384. let nodeVar = nodeData[ subBuildVariable ];
  34385. if ( nodeVar === undefined ) {
  34386. const idNS = readOnly ? '_const' : '_var';
  34387. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  34388. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  34389. if ( name === null ) {
  34390. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  34391. this.vars[ idNS ] ++;
  34392. }
  34393. //
  34394. if ( subBuildVariable !== 'variable' ) {
  34395. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  34396. }
  34397. //
  34398. const count = node.getArrayCount( this );
  34399. nodeVar = new NodeVar( name, type, readOnly, count );
  34400. if ( ! readOnly ) {
  34401. vars.push( nodeVar );
  34402. }
  34403. this.registerDeclaration( nodeVar );
  34404. nodeData[ subBuildVariable ] = nodeVar;
  34405. }
  34406. return nodeVar;
  34407. }
  34408. /**
  34409. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  34410. *
  34411. * @param {Node} node - The varying node.
  34412. * @return {boolean} Returns true if deterministic.
  34413. */
  34414. isDeterministic( node ) {
  34415. if ( node.isMathNode ) {
  34416. return this.isDeterministic( node.aNode ) &&
  34417. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  34418. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  34419. } else if ( node.isOperatorNode ) {
  34420. return this.isDeterministic( node.aNode ) &&
  34421. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  34422. } else if ( node.isArrayNode ) {
  34423. if ( node.values !== null ) {
  34424. for ( const n of node.values ) {
  34425. if ( ! this.isDeterministic( n ) ) {
  34426. return false;
  34427. }
  34428. }
  34429. }
  34430. return true;
  34431. } else if ( node.isConstNode ) {
  34432. return true;
  34433. }
  34434. return false;
  34435. }
  34436. /**
  34437. * Returns an instance of {@link NodeVarying} for the given varying node.
  34438. *
  34439. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  34440. * @param {?string} name - The varying's name.
  34441. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  34442. * @param {?string} interpolationType - The interpolation type of the varying.
  34443. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34444. * @return {NodeVar} The node varying.
  34445. */
  34446. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  34447. const nodeData = this.getDataFromNode( node, 'any' );
  34448. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  34449. let nodeVarying = nodeData[ subBuildVarying ];
  34450. if ( nodeVarying === undefined ) {
  34451. const varyings = this.varyings;
  34452. const index = varyings.length;
  34453. if ( name === null ) name = 'nodeVarying' + index;
  34454. //
  34455. if ( subBuildVarying !== 'varying' ) {
  34456. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  34457. }
  34458. //
  34459. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  34460. varyings.push( nodeVarying );
  34461. this.registerDeclaration( nodeVarying );
  34462. nodeData[ subBuildVarying ] = nodeVarying;
  34463. }
  34464. return nodeVarying;
  34465. }
  34466. /**
  34467. * Registers a node declaration in the current shader stage.
  34468. *
  34469. * @param {Object} node - The node to be registered.
  34470. */
  34471. registerDeclaration( node ) {
  34472. const shaderStage = this.shaderStage;
  34473. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  34474. const property = this.getPropertyName( node );
  34475. let index = 1;
  34476. let name = property;
  34477. // Automatically renames the property if the name is already in use.
  34478. while ( declarations[ name ] !== undefined ) {
  34479. name = property + '_' + index ++;
  34480. }
  34481. if ( index > 1 ) {
  34482. node.name = name;
  34483. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  34484. }
  34485. declarations[ name ] = node;
  34486. }
  34487. /**
  34488. * Returns an instance of {@link NodeCode} for the given code node.
  34489. *
  34490. * @param {CodeNode} node - The code node.
  34491. * @param {string} type - The node type.
  34492. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34493. * @return {NodeCode} The node code.
  34494. */
  34495. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  34496. const nodeData = this.getDataFromNode( node );
  34497. let nodeCode = nodeData.code;
  34498. if ( nodeCode === undefined ) {
  34499. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  34500. const index = codes.length;
  34501. nodeCode = new NodeCode( 'nodeCode' + index, type );
  34502. codes.push( nodeCode );
  34503. nodeData.code = nodeCode;
  34504. }
  34505. return nodeCode;
  34506. }
  34507. /**
  34508. * Adds a code flow based on the code-block hierarchy.
  34509. * This is used so that code-blocks like If,Else create their variables locally if the Node
  34510. * is only used inside one of these conditionals in the current shader stage.
  34511. *
  34512. * @param {Node} node - The node to add.
  34513. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  34514. */
  34515. addFlowCodeHierarchy( node, nodeBlock ) {
  34516. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  34517. let needsFlowCode = true;
  34518. let nodeBlockHierarchy = nodeBlock;
  34519. while ( nodeBlockHierarchy ) {
  34520. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  34521. needsFlowCode = false;
  34522. break;
  34523. }
  34524. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  34525. }
  34526. if ( needsFlowCode ) {
  34527. for ( const flowCode of flowCodes ) {
  34528. this.addLineFlowCode( flowCode );
  34529. }
  34530. }
  34531. }
  34532. /**
  34533. * Add a inline-code to the current flow code-block.
  34534. *
  34535. * @param {Node} node - The node to add.
  34536. * @param {string} code - The code to add.
  34537. * @param {Node} nodeBlock - Current ConditionalNode
  34538. */
  34539. addLineFlowCodeBlock( node, code, nodeBlock ) {
  34540. const nodeData = this.getDataFromNode( node );
  34541. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  34542. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  34543. flowCodes.push( code );
  34544. codeBlock.set( nodeBlock, true );
  34545. }
  34546. /**
  34547. * Add a inline-code to the current flow.
  34548. *
  34549. * @param {string} code - The code to add.
  34550. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  34551. * @return {NodeBuilder} A reference to this node builder.
  34552. */
  34553. addLineFlowCode( code, node = null ) {
  34554. if ( code === '' ) return this;
  34555. if ( node !== null && this.context.nodeBlock ) {
  34556. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  34557. }
  34558. code = this.tab + code;
  34559. if ( ! /;\s*$/.test( code ) ) {
  34560. code = code + ';\n';
  34561. }
  34562. this.flow.code += code;
  34563. return this;
  34564. }
  34565. /**
  34566. * Adds a code to the current code flow.
  34567. *
  34568. * @param {string} code - Shader code.
  34569. * @return {NodeBuilder} A reference to this node builder.
  34570. */
  34571. addFlowCode( code ) {
  34572. this.flow.code += code;
  34573. return this;
  34574. }
  34575. /**
  34576. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  34577. * Typically used in codes with If,Else.
  34578. *
  34579. * @return {NodeBuilder} A reference to this node builder.
  34580. */
  34581. addFlowTab() {
  34582. this.tab += '\t';
  34583. return this;
  34584. }
  34585. /**
  34586. * Removes a tab.
  34587. *
  34588. * @return {NodeBuilder} A reference to this node builder.
  34589. */
  34590. removeFlowTab() {
  34591. this.tab = this.tab.slice( 0, -1 );
  34592. return this;
  34593. }
  34594. /**
  34595. * Gets the current flow data based on a Node.
  34596. *
  34597. * @param {Node} node - Node that the flow was started.
  34598. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34599. * @return {Object} The flow data.
  34600. */
  34601. getFlowData( node/*, shaderStage*/ ) {
  34602. return this.flowsData.get( node );
  34603. }
  34604. /**
  34605. * Executes the node flow based on a root node to generate the final shader code.
  34606. *
  34607. * @param {Node} node - The node to execute.
  34608. * @return {Object} The code flow.
  34609. */
  34610. flowNode( node ) {
  34611. const output = node.getNodeType( this );
  34612. const flowData = this.flowChildNode( node, output );
  34613. this.flowsData.set( node, flowData );
  34614. return flowData;
  34615. }
  34616. /**
  34617. * Includes a node in the current function node.
  34618. *
  34619. * @param {Node} node - The node to include.
  34620. * @returns {void}
  34621. */
  34622. addInclude( node ) {
  34623. if ( this.currentFunctionNode !== null ) {
  34624. this.currentFunctionNode.includes.push( node );
  34625. }
  34626. }
  34627. /**
  34628. * Returns the native shader operator name for a given generic name.
  34629. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  34630. *
  34631. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  34632. * @return {FunctionNode} The build function node.
  34633. */
  34634. buildFunctionNode( shaderNode ) {
  34635. const fn = new FunctionNode();
  34636. const previous = this.currentFunctionNode;
  34637. this.currentFunctionNode = fn;
  34638. fn.code = this.buildFunctionCode( shaderNode );
  34639. this.currentFunctionNode = previous;
  34640. return fn;
  34641. }
  34642. /**
  34643. * Generates a code flow based on a TSL function: Fn().
  34644. *
  34645. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  34646. * @return {Object}
  34647. */
  34648. flowShaderNode( shaderNode ) {
  34649. const layout = shaderNode.layout;
  34650. const inputs = {
  34651. [ Symbol.iterator ]() {
  34652. let index = 0;
  34653. const values = Object.values( this );
  34654. return {
  34655. next: () => ( {
  34656. value: values[ index ],
  34657. done: index ++ >= values.length
  34658. } )
  34659. };
  34660. }
  34661. };
  34662. for ( const input of layout.inputs ) {
  34663. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  34664. }
  34665. //
  34666. shaderNode.layout = null;
  34667. const callNode = shaderNode.call( inputs );
  34668. const flowData = this.flowStagesNode( callNode, layout.type );
  34669. shaderNode.layout = layout;
  34670. return flowData;
  34671. }
  34672. /**
  34673. * Executes the node in a specific build stage.
  34674. *
  34675. * @param {Node} node - The node to execute.
  34676. * @param {string} buildStage - The build stage to execute the node in.
  34677. * @param {Node|string|null} output - Expected output type. For example 'vec3'.
  34678. * @return {Node|string|null} The result of the node build.
  34679. */
  34680. flowBuildStage( node, buildStage, output = null ) {
  34681. const previousBuildStage = this.getBuildStage();
  34682. this.setBuildStage( buildStage );
  34683. const result = node.build( this, output );
  34684. this.setBuildStage( previousBuildStage );
  34685. return result;
  34686. }
  34687. /**
  34688. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  34689. *
  34690. * @param {Node} node - The node to execute.
  34691. * @param {?string} output - Expected output type. For example 'vec3'.
  34692. * @return {Object}
  34693. */
  34694. flowStagesNode( node, output = null ) {
  34695. const previousFlow = this.flow;
  34696. const previousVars = this.vars;
  34697. const previousDeclarations = this.declarations;
  34698. const previousCache = this.cache;
  34699. const previousBuildStage = this.buildStage;
  34700. const previousStack = this.stack;
  34701. const flow = {
  34702. code: ''
  34703. };
  34704. this.flow = flow;
  34705. this.vars = {};
  34706. this.declarations = {};
  34707. this.cache = new NodeCache();
  34708. this.stack = stack();
  34709. for ( const buildStage of defaultBuildStages ) {
  34710. this.setBuildStage( buildStage );
  34711. flow.result = node.build( this, output );
  34712. }
  34713. flow.vars = this.getVars( this.shaderStage );
  34714. this.flow = previousFlow;
  34715. this.vars = previousVars;
  34716. this.declarations = previousDeclarations;
  34717. this.cache = previousCache;
  34718. this.stack = previousStack;
  34719. this.setBuildStage( previousBuildStage );
  34720. return flow;
  34721. }
  34722. /**
  34723. * Returns the native shader operator name for a given generic name.
  34724. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  34725. *
  34726. * @abstract
  34727. * @param {string} op - The operator name to resolve.
  34728. * @return {?string} The resolved operator name.
  34729. */
  34730. getFunctionOperator( /* op */ ) {
  34731. return null;
  34732. }
  34733. /**
  34734. * Builds the given shader node.
  34735. *
  34736. * @abstract
  34737. * @param {ShaderNodeInternal} shaderNode - The shader node.
  34738. * @return {string} The function code.
  34739. */
  34740. buildFunctionCode( /* shaderNode */ ) {
  34741. console.warn( 'Abstract function.' );
  34742. }
  34743. /**
  34744. * Generates a code flow based on a child Node.
  34745. *
  34746. * @param {Node} node - The node to execute.
  34747. * @param {?string} output - Expected output type. For example 'vec3'.
  34748. * @return {Object} The code flow.
  34749. */
  34750. flowChildNode( node, output = null ) {
  34751. const previousFlow = this.flow;
  34752. const flow = {
  34753. code: ''
  34754. };
  34755. this.flow = flow;
  34756. flow.result = node.build( this, output );
  34757. this.flow = previousFlow;
  34758. return flow;
  34759. }
  34760. /**
  34761. * Executes a flow of code in a different stage.
  34762. *
  34763. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  34764. * return the value in fragment-stage even if it is being executed in an input fragment.
  34765. *
  34766. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34767. * @param {Node} node - The node to execute.
  34768. * @param {?string} output - Expected output type. For example 'vec3'.
  34769. * @param {?string} propertyName - The property name to assign the result.
  34770. * @return {Object|Node|null} The code flow or node.build() result.
  34771. */
  34772. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  34773. const previousTab = this.tab;
  34774. const previousCache = this.cache;
  34775. const previousShaderStage = this.shaderStage;
  34776. const previousContext = this.context;
  34777. this.setShaderStage( shaderStage );
  34778. const context = { ...this.context };
  34779. delete context.nodeBlock;
  34780. this.cache = this.globalCache;
  34781. this.tab = '\t';
  34782. this.context = context;
  34783. let result = null;
  34784. if ( this.buildStage === 'generate' ) {
  34785. const flowData = this.flowChildNode( node, output );
  34786. if ( propertyName !== null ) {
  34787. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  34788. }
  34789. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  34790. result = flowData;
  34791. } else {
  34792. result = node.build( this );
  34793. }
  34794. this.setShaderStage( previousShaderStage );
  34795. this.cache = previousCache;
  34796. this.tab = previousTab;
  34797. this.context = previousContext;
  34798. return result;
  34799. }
  34800. /**
  34801. * Returns an array holding all node attributes of this node builder.
  34802. *
  34803. * @return {Array<NodeAttribute>} The node attributes of this builder.
  34804. */
  34805. getAttributesArray() {
  34806. return this.attributes.concat( this.bufferAttributes );
  34807. }
  34808. /**
  34809. * Returns the attribute definitions as a shader string for the given shader stage.
  34810. *
  34811. * @abstract
  34812. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34813. * @return {string} The attribute code section.
  34814. */
  34815. getAttributes( /*shaderStage*/ ) {
  34816. console.warn( 'Abstract function.' );
  34817. }
  34818. /**
  34819. * Returns the varying definitions as a shader string for the given shader stage.
  34820. *
  34821. * @abstract
  34822. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34823. * @return {string} The varying code section.
  34824. */
  34825. getVaryings( /*shaderStage*/ ) {
  34826. console.warn( 'Abstract function.' );
  34827. }
  34828. /**
  34829. * Returns a single variable definition as a shader string for the given variable type and name.
  34830. *
  34831. * @param {string} type - The variable's type.
  34832. * @param {string} name - The variable's name.
  34833. * @param {?number} [count=null] - The array length.
  34834. * @return {string} The shader string.
  34835. */
  34836. getVar( type, name, count = null ) {
  34837. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  34838. }
  34839. /**
  34840. * Returns the variable definitions as a shader string for the given shader stage.
  34841. *
  34842. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34843. * @return {string} The variable code section.
  34844. */
  34845. getVars( shaderStage ) {
  34846. let snippet = '';
  34847. const vars = this.vars[ shaderStage ];
  34848. if ( vars !== undefined ) {
  34849. for ( const variable of vars ) {
  34850. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  34851. }
  34852. }
  34853. return snippet;
  34854. }
  34855. /**
  34856. * Returns the uniform definitions as a shader string for the given shader stage.
  34857. *
  34858. * @abstract
  34859. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34860. * @return {string} The uniform code section.
  34861. */
  34862. getUniforms( /*shaderStage*/ ) {
  34863. console.warn( 'Abstract function.' );
  34864. }
  34865. /**
  34866. * Returns the native code definitions as a shader string for the given shader stage.
  34867. *
  34868. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34869. * @return {string} The native code section.
  34870. */
  34871. getCodes( shaderStage ) {
  34872. const codes = this.codes[ shaderStage ];
  34873. let code = '';
  34874. if ( codes !== undefined ) {
  34875. for ( const nodeCode of codes ) {
  34876. code += nodeCode.code + '\n';
  34877. }
  34878. }
  34879. return code;
  34880. }
  34881. /**
  34882. * Returns the hash of this node builder.
  34883. *
  34884. * @return {string} The hash.
  34885. */
  34886. getHash() {
  34887. return this.vertexShader + this.fragmentShader + this.computeShader;
  34888. }
  34889. /**
  34890. * Sets the current shader stage.
  34891. *
  34892. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  34893. */
  34894. setShaderStage( shaderStage ) {
  34895. this.shaderStage = shaderStage;
  34896. }
  34897. /**
  34898. * Returns the current shader stage.
  34899. *
  34900. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  34901. */
  34902. getShaderStage() {
  34903. return this.shaderStage;
  34904. }
  34905. /**
  34906. * Sets the current build stage.
  34907. *
  34908. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  34909. */
  34910. setBuildStage( buildStage ) {
  34911. this.buildStage = buildStage;
  34912. }
  34913. /**
  34914. * Returns the current build stage.
  34915. *
  34916. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  34917. */
  34918. getBuildStage() {
  34919. return this.buildStage;
  34920. }
  34921. /**
  34922. * Controls the code build of the shader stages.
  34923. *
  34924. * @abstract
  34925. */
  34926. buildCode() {
  34927. console.warn( 'Abstract function.' );
  34928. }
  34929. /**
  34930. * Returns the current sub-build layer.
  34931. *
  34932. * @return {SubBuildNode} The current sub-build layers.
  34933. */
  34934. get subBuild() {
  34935. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  34936. }
  34937. /**
  34938. * Adds a sub-build layer to the node builder.
  34939. *
  34940. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  34941. */
  34942. addSubBuild( subBuild ) {
  34943. this.subBuildLayers.push( subBuild );
  34944. }
  34945. /**
  34946. * Removes the last sub-build layer from the node builder.
  34947. *
  34948. * @return {SubBuildNode} The removed sub-build layer.
  34949. */
  34950. removeSubBuild() {
  34951. return this.subBuildLayers.pop();
  34952. }
  34953. /**
  34954. * Returns the closest sub-build layer for the given data.
  34955. *
  34956. * @param {Node|Set|Array} data - The data to get the closest sub-build layer from.
  34957. * @return {?string} The closest sub-build name or null if none found.
  34958. */
  34959. getClosestSubBuild( data ) {
  34960. let subBuilds;
  34961. if ( data && data.isNode ) {
  34962. if ( data.isShaderCallNodeInternal ) {
  34963. subBuilds = data.shaderNode.subBuilds;
  34964. } else if ( data.isStackNode ) {
  34965. subBuilds = [ data.subBuild ];
  34966. } else {
  34967. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  34968. }
  34969. } else if ( data instanceof Set ) {
  34970. subBuilds = [ ...data ];
  34971. } else {
  34972. subBuilds = data;
  34973. }
  34974. if ( ! subBuilds ) return null;
  34975. const subBuildLayers = this.subBuildLayers;
  34976. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  34977. const subBuild = subBuilds[ i ];
  34978. if ( subBuildLayers.includes( subBuild ) ) {
  34979. return subBuild;
  34980. }
  34981. }
  34982. return null;
  34983. }
  34984. /**
  34985. * Returns the output node of a sub-build layer.
  34986. *
  34987. * @param {Node} node - The node to get the output from.
  34988. * @return {string} The output node name.
  34989. */
  34990. getSubBuildOutput( node ) {
  34991. return this.getSubBuildProperty( 'outputNode', node );
  34992. }
  34993. /**
  34994. * Returns the sub-build property name for the given property and node.
  34995. *
  34996. * @param {string} [property=''] - The property name.
  34997. * @param {?Node} [node=null] - The node to get the sub-build from.
  34998. * @return {string} The sub-build property name.
  34999. */
  35000. getSubBuildProperty( property = '', node = null ) {
  35001. let subBuild;
  35002. if ( node !== null ) {
  35003. subBuild = this.getClosestSubBuild( node );
  35004. } else {
  35005. subBuild = this.subBuildFn;
  35006. }
  35007. let result;
  35008. if ( subBuild ) {
  35009. result = property ? ( subBuild + '_' + property ) : subBuild;
  35010. } else {
  35011. result = property;
  35012. }
  35013. return result;
  35014. }
  35015. /**
  35016. * Central build method which controls the build for the given object.
  35017. *
  35018. * @return {NodeBuilder} A reference to this node builder.
  35019. */
  35020. build() {
  35021. const { object, material, renderer } = this;
  35022. if ( material !== null ) {
  35023. let nodeMaterial = renderer.library.fromMaterial( material );
  35024. if ( nodeMaterial === null ) {
  35025. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  35026. nodeMaterial = new NodeMaterial();
  35027. }
  35028. nodeMaterial.build( this );
  35029. } else {
  35030. this.addFlow( 'compute', object );
  35031. }
  35032. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  35033. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  35034. // generate() -> stage 3: generate shader
  35035. for ( const buildStage of defaultBuildStages ) {
  35036. this.setBuildStage( buildStage );
  35037. if ( this.context.vertex && this.context.vertex.isNode ) {
  35038. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  35039. }
  35040. for ( const shaderStage of shaderStages ) {
  35041. this.setShaderStage( shaderStage );
  35042. const flowNodes = this.flowNodes[ shaderStage ];
  35043. for ( const node of flowNodes ) {
  35044. if ( buildStage === 'generate' ) {
  35045. this.flowNode( node );
  35046. } else {
  35047. node.build( this );
  35048. }
  35049. }
  35050. }
  35051. }
  35052. this.setBuildStage( null );
  35053. this.setShaderStage( null );
  35054. // stage 4: build code for a specific output
  35055. this.buildCode();
  35056. this.buildUpdateNodes();
  35057. return this;
  35058. }
  35059. /**
  35060. * Returns a uniform representation which is later used for UBO generation and rendering.
  35061. *
  35062. * @param {NodeUniform} uniformNode - The uniform node.
  35063. * @param {string} type - The requested type.
  35064. * @return {Uniform} The uniform.
  35065. */
  35066. getNodeUniform( uniformNode, type ) {
  35067. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  35068. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  35069. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  35070. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  35071. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  35072. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  35073. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  35074. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  35075. throw new Error( `Uniform "${type}" not declared.` );
  35076. }
  35077. /**
  35078. * Formats the given shader snippet from a given type into another one. E.g.
  35079. * this method might be used to convert a simple float string `"1.0"` into a
  35080. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  35081. *
  35082. * @param {string} snippet - The shader snippet.
  35083. * @param {string} fromType - The source type.
  35084. * @param {string} toType - The target type.
  35085. * @return {string} The updated shader string.
  35086. */
  35087. format( snippet, fromType, toType ) {
  35088. fromType = this.getVectorType( fromType );
  35089. toType = this.getVectorType( toType );
  35090. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  35091. return snippet;
  35092. }
  35093. const fromTypeLength = this.getTypeLength( fromType );
  35094. const toTypeLength = this.getTypeLength( toType );
  35095. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  35096. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  35097. }
  35098. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  35099. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  35100. }
  35101. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  35102. // @TODO: ignore for now
  35103. return snippet;
  35104. }
  35105. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  35106. // @TODO: ignore for now
  35107. return snippet;
  35108. }
  35109. if ( fromTypeLength === toTypeLength ) {
  35110. return `${ this.getType( toType ) }( ${ snippet } )`;
  35111. }
  35112. if ( fromTypeLength > toTypeLength ) {
  35113. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  35114. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  35115. }
  35116. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  35117. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  35118. }
  35119. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  35120. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  35121. }
  35122. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  35123. // convert a number value to vector type, e.g:
  35124. // vec3( 1u ) -> vec3( float( 1u ) )
  35125. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  35126. }
  35127. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  35128. }
  35129. /**
  35130. * Returns a signature with the engine's current revision.
  35131. *
  35132. * @return {string} The signature.
  35133. */
  35134. getSignature() {
  35135. return `// Three.js r${ REVISION } - Node System\n`;
  35136. }
  35137. }
  35138. /**
  35139. * Management class for updating nodes. The module tracks metrics like
  35140. * the elapsed time, delta time, the render and frame ID to correctly
  35141. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  35142. * and {@link Node#updateAfter} depending on the node's configuration.
  35143. */
  35144. class NodeFrame {
  35145. /**
  35146. * Constructs a new node fame.
  35147. */
  35148. constructor() {
  35149. /**
  35150. * The elapsed time in seconds.
  35151. *
  35152. * @type {number}
  35153. * @default 0
  35154. */
  35155. this.time = 0;
  35156. /**
  35157. * The delta time in seconds.
  35158. *
  35159. * @type {number}
  35160. * @default 0
  35161. */
  35162. this.deltaTime = 0;
  35163. /**
  35164. * The frame ID.
  35165. *
  35166. * @type {number}
  35167. * @default 0
  35168. */
  35169. this.frameId = 0;
  35170. /**
  35171. * The render ID.
  35172. *
  35173. * @type {number}
  35174. * @default 0
  35175. */
  35176. this.renderId = 0;
  35177. /**
  35178. * Used to control the {@link Node#update} call.
  35179. *
  35180. * @type {WeakMap<Node, Object>}
  35181. */
  35182. this.updateMap = new WeakMap();
  35183. /**
  35184. * Used to control the {@link Node#updateBefore} call.
  35185. *
  35186. * @type {WeakMap<Node, Object>}
  35187. */
  35188. this.updateBeforeMap = new WeakMap();
  35189. /**
  35190. * Used to control the {@link Node#updateAfter} call.
  35191. *
  35192. * @type {WeakMap<Node, Object>}
  35193. */
  35194. this.updateAfterMap = new WeakMap();
  35195. /**
  35196. * A reference to the current renderer.
  35197. *
  35198. * @type {?Renderer}
  35199. * @default null
  35200. */
  35201. this.renderer = null;
  35202. /**
  35203. * A reference to the current material.
  35204. *
  35205. * @type {?Material}
  35206. * @default null
  35207. */
  35208. this.material = null;
  35209. /**
  35210. * A reference to the current camera.
  35211. *
  35212. * @type {?Camera}
  35213. * @default null
  35214. */
  35215. this.camera = null;
  35216. /**
  35217. * A reference to the current 3D object.
  35218. *
  35219. * @type {?Object3D}
  35220. * @default null
  35221. */
  35222. this.object = null;
  35223. /**
  35224. * A reference to the current scene.
  35225. *
  35226. * @type {?Scene}
  35227. * @default null
  35228. */
  35229. this.scene = null;
  35230. }
  35231. /**
  35232. * Returns a dictionary for a given node and update map which
  35233. * is used to correctly call node update methods per frame or render.
  35234. *
  35235. * @private
  35236. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  35237. * @param {Node} nodeRef - The reference to the current node.
  35238. * @return {Object<string,WeakMap>} The dictionary.
  35239. */
  35240. _getMaps( referenceMap, nodeRef ) {
  35241. let maps = referenceMap.get( nodeRef );
  35242. if ( maps === undefined ) {
  35243. maps = {
  35244. renderMap: new WeakMap(),
  35245. frameMap: new WeakMap()
  35246. };
  35247. referenceMap.set( nodeRef, maps );
  35248. }
  35249. return maps;
  35250. }
  35251. /**
  35252. * This method executes the {@link Node#updateBefore} for the given node.
  35253. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  35254. * is only executed once per frame, render or object depending on the update
  35255. * type.
  35256. *
  35257. * @param {Node} node - The node that should be updated.
  35258. */
  35259. updateBeforeNode( node ) {
  35260. const updateType = node.getUpdateBeforeType();
  35261. const reference = node.updateReference( this );
  35262. if ( updateType === NodeUpdateType.FRAME ) {
  35263. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  35264. if ( frameMap.get( reference ) !== this.frameId ) {
  35265. if ( node.updateBefore( this ) !== false ) {
  35266. frameMap.set( reference, this.frameId );
  35267. }
  35268. }
  35269. } else if ( updateType === NodeUpdateType.RENDER ) {
  35270. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  35271. if ( renderMap.get( reference ) !== this.renderId ) {
  35272. if ( node.updateBefore( this ) !== false ) {
  35273. renderMap.set( reference, this.renderId );
  35274. }
  35275. }
  35276. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35277. node.updateBefore( this );
  35278. }
  35279. }
  35280. /**
  35281. * This method executes the {@link Node#updateAfter} for the given node.
  35282. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  35283. * is only executed once per frame, render or object depending on the update
  35284. * type.
  35285. *
  35286. * @param {Node} node - The node that should be updated.
  35287. */
  35288. updateAfterNode( node ) {
  35289. const updateType = node.getUpdateAfterType();
  35290. const reference = node.updateReference( this );
  35291. if ( updateType === NodeUpdateType.FRAME ) {
  35292. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  35293. if ( frameMap.get( reference ) !== this.frameId ) {
  35294. if ( node.updateAfter( this ) !== false ) {
  35295. frameMap.set( reference, this.frameId );
  35296. }
  35297. }
  35298. } else if ( updateType === NodeUpdateType.RENDER ) {
  35299. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  35300. if ( renderMap.get( reference ) !== this.renderId ) {
  35301. if ( node.updateAfter( this ) !== false ) {
  35302. renderMap.set( reference, this.renderId );
  35303. }
  35304. }
  35305. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35306. node.updateAfter( this );
  35307. }
  35308. }
  35309. /**
  35310. * This method executes the {@link Node#update} for the given node.
  35311. * It makes sure {@link Node#updateType} is honored meaning the update
  35312. * is only executed once per frame, render or object depending on the update
  35313. * type.
  35314. *
  35315. * @param {Node} node - The node that should be updated.
  35316. */
  35317. updateNode( node ) {
  35318. const updateType = node.getUpdateType();
  35319. const reference = node.updateReference( this );
  35320. if ( updateType === NodeUpdateType.FRAME ) {
  35321. const { frameMap } = this._getMaps( this.updateMap, reference );
  35322. if ( frameMap.get( reference ) !== this.frameId ) {
  35323. if ( node.update( this ) !== false ) {
  35324. frameMap.set( reference, this.frameId );
  35325. }
  35326. }
  35327. } else if ( updateType === NodeUpdateType.RENDER ) {
  35328. const { renderMap } = this._getMaps( this.updateMap, reference );
  35329. if ( renderMap.get( reference ) !== this.renderId ) {
  35330. if ( node.update( this ) !== false ) {
  35331. renderMap.set( reference, this.renderId );
  35332. }
  35333. }
  35334. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35335. node.update( this );
  35336. }
  35337. }
  35338. /**
  35339. * Updates the internal state of the node frame. This method is
  35340. * called by the renderer in its internal animation loop.
  35341. */
  35342. update() {
  35343. this.frameId ++;
  35344. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  35345. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  35346. this.lastTime = performance.now();
  35347. this.time += this.deltaTime;
  35348. }
  35349. }
  35350. /**
  35351. * Describes the input of a {@link NodeFunction}.
  35352. */
  35353. class NodeFunctionInput {
  35354. /**
  35355. * Constructs a new node function input.
  35356. *
  35357. * @param {string} type - The input type.
  35358. * @param {string} name - The input name.
  35359. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  35360. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  35361. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  35362. */
  35363. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  35364. /**
  35365. * The input type.
  35366. *
  35367. * @type {string}
  35368. */
  35369. this.type = type;
  35370. /**
  35371. * The input name.
  35372. *
  35373. * @type {string}
  35374. */
  35375. this.name = name;
  35376. /**
  35377. * If the input is an Array, count will be the length.
  35378. *
  35379. * @type {?number}
  35380. * @default null
  35381. */
  35382. this.count = count;
  35383. /**
  35384. *The parameter qualifier (only relevant for GLSL).
  35385. *
  35386. * @type {('in'|'out'|'inout')}
  35387. * @default ''
  35388. */
  35389. this.qualifier = qualifier;
  35390. /**
  35391. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  35392. *
  35393. * @type {boolean}
  35394. * @default false
  35395. */
  35396. this.isConst = isConst;
  35397. }
  35398. }
  35399. NodeFunctionInput.isNodeFunctionInput = true;
  35400. /**
  35401. * Module for representing directional lights as nodes.
  35402. *
  35403. * @augments AnalyticLightNode
  35404. */
  35405. class DirectionalLightNode extends AnalyticLightNode {
  35406. static get type() {
  35407. return 'DirectionalLightNode';
  35408. }
  35409. /**
  35410. * Constructs a new directional light node.
  35411. *
  35412. * @param {?DirectionalLight} [light=null] - The directional light source.
  35413. */
  35414. constructor( light = null ) {
  35415. super( light );
  35416. }
  35417. setupDirect() {
  35418. const lightColor = this.colorNode;
  35419. const lightDirection = lightTargetDirection( this.light );
  35420. return { lightDirection, lightColor };
  35421. }
  35422. }
  35423. const _matrix41 = /*@__PURE__*/ new Matrix4();
  35424. const _matrix42 = /*@__PURE__*/ new Matrix4();
  35425. let _ltcLib = null;
  35426. /**
  35427. * Module for representing rect area lights as nodes.
  35428. *
  35429. * @augments AnalyticLightNode
  35430. */
  35431. class RectAreaLightNode extends AnalyticLightNode {
  35432. static get type() {
  35433. return 'RectAreaLightNode';
  35434. }
  35435. /**
  35436. * Constructs a new rect area light node.
  35437. *
  35438. * @param {?RectAreaLight} [light=null] - The rect area light source.
  35439. */
  35440. constructor( light = null ) {
  35441. super( light );
  35442. /**
  35443. * Uniform node representing the half height of the are light.
  35444. *
  35445. * @type {UniformNode<vec3>}
  35446. */
  35447. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  35448. /**
  35449. * Uniform node representing the half width of the are light.
  35450. *
  35451. * @type {UniformNode<vec3>}
  35452. */
  35453. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  35454. /**
  35455. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  35456. * relies on `viewMatrix` which might vary per render call.
  35457. *
  35458. * @type {string}
  35459. * @default 'render'
  35460. */
  35461. this.updateType = NodeUpdateType.RENDER;
  35462. }
  35463. /**
  35464. * Overwritten to updated rect area light specific uniforms.
  35465. *
  35466. * @param {NodeFrame} frame - A reference to the current node frame.
  35467. */
  35468. update( frame ) {
  35469. super.update( frame );
  35470. const { light } = this;
  35471. const viewMatrix = frame.camera.matrixWorldInverse;
  35472. _matrix42.identity();
  35473. _matrix41.copy( light.matrixWorld );
  35474. _matrix41.premultiply( viewMatrix );
  35475. _matrix42.extractRotation( _matrix41 );
  35476. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  35477. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  35478. this.halfWidth.value.applyMatrix4( _matrix42 );
  35479. this.halfHeight.value.applyMatrix4( _matrix42 );
  35480. }
  35481. setupDirectRectArea( builder ) {
  35482. let ltc_1, ltc_2;
  35483. if ( builder.isAvailable( 'float32Filterable' ) ) {
  35484. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  35485. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  35486. } else {
  35487. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  35488. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  35489. }
  35490. const { colorNode, light } = this;
  35491. const lightPosition = lightViewPosition( light );
  35492. return {
  35493. lightColor: colorNode,
  35494. lightPosition,
  35495. halfWidth: this.halfWidth,
  35496. halfHeight: this.halfHeight,
  35497. ltc_1,
  35498. ltc_2
  35499. };
  35500. }
  35501. /**
  35502. * Used to configure the internal BRDF approximation texture data.
  35503. *
  35504. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  35505. */
  35506. static setLTC( ltc ) {
  35507. _ltcLib = ltc;
  35508. }
  35509. }
  35510. /**
  35511. * Module for representing spot lights as nodes.
  35512. *
  35513. * @augments AnalyticLightNode
  35514. */
  35515. class SpotLightNode extends AnalyticLightNode {
  35516. static get type() {
  35517. return 'SpotLightNode';
  35518. }
  35519. /**
  35520. * Constructs a new spot light node.
  35521. *
  35522. * @param {?SpotLight} [light=null] - The spot light source.
  35523. */
  35524. constructor( light = null ) {
  35525. super( light );
  35526. /**
  35527. * Uniform node representing the cone cosine.
  35528. *
  35529. * @type {UniformNode<float>}
  35530. */
  35531. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  35532. /**
  35533. * Uniform node representing the penumbra cosine.
  35534. *
  35535. * @type {UniformNode<float>}
  35536. */
  35537. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  35538. /**
  35539. * Uniform node representing the cutoff distance.
  35540. *
  35541. * @type {UniformNode<float>}
  35542. */
  35543. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  35544. /**
  35545. * Uniform node representing the decay exponent.
  35546. *
  35547. * @type {UniformNode<float>}
  35548. */
  35549. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  35550. /**
  35551. * Uniform node representing the light color.
  35552. *
  35553. * @type {UniformNode<Color>}
  35554. */
  35555. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  35556. }
  35557. /**
  35558. * Overwritten to updated spot light specific uniforms.
  35559. *
  35560. * @param {NodeFrame} frame - A reference to the current node frame.
  35561. */
  35562. update( frame ) {
  35563. super.update( frame );
  35564. const { light } = this;
  35565. this.coneCosNode.value = Math.cos( light.angle );
  35566. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  35567. this.cutoffDistanceNode.value = light.distance;
  35568. this.decayExponentNode.value = light.decay;
  35569. }
  35570. /**
  35571. * Computes the spot attenuation for the given angle.
  35572. *
  35573. * @param {NodeBuilder} builder - The node builder.
  35574. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  35575. * @return {Node<float>} The spot attenuation.
  35576. */
  35577. getSpotAttenuation( builder, angleCosine ) {
  35578. const { coneCosNode, penumbraCosNode } = this;
  35579. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  35580. }
  35581. getLightCoord( builder ) {
  35582. const properties = builder.getNodeProperties( this );
  35583. let projectionUV = properties.projectionUV;
  35584. if ( projectionUV === undefined ) {
  35585. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  35586. properties.projectionUV = projectionUV;
  35587. }
  35588. return projectionUV;
  35589. }
  35590. setupDirect( builder ) {
  35591. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  35592. const lightVector = this.getLightVector( builder );
  35593. const lightDirection = lightVector.normalize();
  35594. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  35595. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  35596. const lightDistance = lightVector.length();
  35597. const lightAttenuation = getDistanceAttenuation( {
  35598. lightDistance,
  35599. cutoffDistance: cutoffDistanceNode,
  35600. decayExponent: decayExponentNode
  35601. } );
  35602. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  35603. let projected, lightCoord;
  35604. if ( light.colorNode ) {
  35605. lightCoord = this.getLightCoord( builder );
  35606. projected = light.colorNode( lightCoord );
  35607. } else if ( light.map ) {
  35608. lightCoord = this.getLightCoord( builder );
  35609. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  35610. }
  35611. if ( projected ) {
  35612. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  35613. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  35614. }
  35615. return { lightColor, lightDirection };
  35616. }
  35617. }
  35618. /**
  35619. * An IES version of the default spot light node.
  35620. *
  35621. * @augments SpotLightNode
  35622. */
  35623. class IESSpotLightNode extends SpotLightNode {
  35624. static get type() {
  35625. return 'IESSpotLightNode';
  35626. }
  35627. /**
  35628. * Overwrites the default implementation to compute an IES conform spot attenuation.
  35629. *
  35630. * @param {NodeBuilder} builder - The node builder.
  35631. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  35632. * @return {Node<float>} The spot attenuation.
  35633. */
  35634. getSpotAttenuation( builder, angleCosine ) {
  35635. const iesMap = this.light.iesMap;
  35636. let spotAttenuation = null;
  35637. if ( iesMap && iesMap.isTexture === true ) {
  35638. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  35639. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  35640. } else {
  35641. spotAttenuation = super.getSpotAttenuation( angleCosine );
  35642. }
  35643. return spotAttenuation;
  35644. }
  35645. }
  35646. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  35647. const d = p.abs().sub( b );
  35648. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  35649. } );
  35650. /**
  35651. * An implementation of a projector light node.
  35652. *
  35653. * @augments SpotLightNode
  35654. */
  35655. class ProjectorLightNode extends SpotLightNode {
  35656. static get type() {
  35657. return 'ProjectorLightNode';
  35658. }
  35659. update( frame ) {
  35660. super.update( frame );
  35661. const light = this.light;
  35662. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  35663. if ( light.aspect === null ) {
  35664. let aspect = 1;
  35665. if ( light.map !== null ) {
  35666. aspect = light.map.width / light.map.height;
  35667. }
  35668. light.shadow.aspect = aspect;
  35669. } else {
  35670. light.shadow.aspect = light.aspect;
  35671. }
  35672. }
  35673. /**
  35674. * Overwrites the default implementation to compute projection attenuation.
  35675. *
  35676. * @param {NodeBuilder} builder - The node builder.
  35677. * @return {Node<float>} The spot attenuation.
  35678. */
  35679. getSpotAttenuation( builder ) {
  35680. const attenuation = float( 0 );
  35681. const penumbraCos = this.penumbraCosNode;
  35682. // compute the fragment's position in the light's clip space
  35683. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  35684. // the sign of w determines whether the current fragment is in front or behind the light.
  35685. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  35686. If( spotLightCoord.w.greaterThan( 0 ), () => {
  35687. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  35688. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  35689. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  35690. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  35691. } );
  35692. return attenuation;
  35693. }
  35694. }
  35695. /**
  35696. * Module for representing ambient lights as nodes.
  35697. *
  35698. * @augments AnalyticLightNode
  35699. */
  35700. class AmbientLightNode extends AnalyticLightNode {
  35701. static get type() {
  35702. return 'AmbientLightNode';
  35703. }
  35704. /**
  35705. * Constructs a new ambient light node.
  35706. *
  35707. * @param {?AmbientLight} [light=null] - The ambient light source.
  35708. */
  35709. constructor( light = null ) {
  35710. super( light );
  35711. }
  35712. setup( { context } ) {
  35713. context.irradiance.addAssign( this.colorNode );
  35714. }
  35715. }
  35716. /**
  35717. * Module for representing hemisphere lights as nodes.
  35718. *
  35719. * @augments AnalyticLightNode
  35720. */
  35721. class HemisphereLightNode extends AnalyticLightNode {
  35722. static get type() {
  35723. return 'HemisphereLightNode';
  35724. }
  35725. /**
  35726. * Constructs a new hemisphere light node.
  35727. *
  35728. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  35729. */
  35730. constructor( light = null ) {
  35731. super( light );
  35732. /**
  35733. * Uniform node representing the light's position.
  35734. *
  35735. * @type {UniformNode<vec3>}
  35736. */
  35737. this.lightPositionNode = lightPosition( light );
  35738. /**
  35739. * A node representing the light's direction.
  35740. *
  35741. * @type {Node<vec3>}
  35742. */
  35743. this.lightDirectionNode = this.lightPositionNode.normalize();
  35744. /**
  35745. * Uniform node representing the light's ground color.
  35746. *
  35747. * @type {UniformNode<vec3>}
  35748. */
  35749. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  35750. }
  35751. /**
  35752. * Overwritten to updated hemisphere light specific uniforms.
  35753. *
  35754. * @param {NodeFrame} frame - A reference to the current node frame.
  35755. */
  35756. update( frame ) {
  35757. const { light } = this;
  35758. super.update( frame );
  35759. this.lightPositionNode.object3d = light;
  35760. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  35761. }
  35762. setup( builder ) {
  35763. const { colorNode, groundColorNode, lightDirectionNode } = this;
  35764. const dotNL = normalWorld.dot( lightDirectionNode );
  35765. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  35766. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  35767. builder.context.irradiance.addAssign( irradiance );
  35768. }
  35769. }
  35770. /**
  35771. * Module for representing light probes as nodes.
  35772. *
  35773. * @augments AnalyticLightNode
  35774. */
  35775. class LightProbeNode extends AnalyticLightNode {
  35776. static get type() {
  35777. return 'LightProbeNode';
  35778. }
  35779. /**
  35780. * Constructs a new light probe node.
  35781. *
  35782. * @param {?LightProbe} [light=null] - The light probe.
  35783. */
  35784. constructor( light = null ) {
  35785. super( light );
  35786. const array = [];
  35787. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  35788. /**
  35789. * Light probe represented as a uniform of spherical harmonics.
  35790. *
  35791. * @type {UniformArrayNode}
  35792. */
  35793. this.lightProbe = uniformArray( array );
  35794. }
  35795. /**
  35796. * Overwritten to updated light probe specific uniforms.
  35797. *
  35798. * @param {NodeFrame} frame - A reference to the current node frame.
  35799. */
  35800. update( frame ) {
  35801. const { light } = this;
  35802. super.update( frame );
  35803. //
  35804. for ( let i = 0; i < 9; i ++ ) {
  35805. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  35806. }
  35807. }
  35808. setup( builder ) {
  35809. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  35810. builder.context.irradiance.addAssign( irradiance );
  35811. }
  35812. }
  35813. /**
  35814. * Base class for node parsers. A derived parser must be implemented
  35815. * for each supported native shader language.
  35816. */
  35817. class NodeParser {
  35818. /**
  35819. * The method parses the given native code an returns a node function.
  35820. *
  35821. * @abstract
  35822. * @param {string} source - The native shader code.
  35823. * @return {NodeFunction} A node function.
  35824. */
  35825. parseFunction( /*source*/ ) {
  35826. console.warn( 'Abstract function.' );
  35827. }
  35828. }
  35829. /**
  35830. * Base class for node functions. A derived module must be implemented
  35831. * for each supported native shader language. Similar to other `Node*` modules,
  35832. * this class is only relevant during the building process and not used
  35833. * in user-level code.
  35834. */
  35835. class NodeFunction {
  35836. /**
  35837. * Constructs a new node function.
  35838. *
  35839. * @param {string} type - The node type. This type is the return type of the node function.
  35840. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  35841. * @param {string} [name=''] - The function's name.
  35842. * @param {string} [precision=''] - The precision qualifier.
  35843. */
  35844. constructor( type, inputs, name = '', precision = '' ) {
  35845. /**
  35846. * The node type. This type is the return type of the node function.
  35847. *
  35848. * @type {string}
  35849. */
  35850. this.type = type;
  35851. /**
  35852. * The function's inputs.
  35853. *
  35854. * @type {Array<NodeFunctionInput>}
  35855. */
  35856. this.inputs = inputs;
  35857. /**
  35858. * The name of the uniform.
  35859. *
  35860. * @type {string}
  35861. * @default ''
  35862. */
  35863. this.name = name;
  35864. /**
  35865. * The precision qualifier.
  35866. *
  35867. * @type {string}
  35868. * @default ''
  35869. */
  35870. this.precision = precision;
  35871. }
  35872. /**
  35873. * This method returns the native code of the node function.
  35874. *
  35875. * @abstract
  35876. * @param {string} name - The function's name.
  35877. * @return {string} A shader code.
  35878. */
  35879. getCode( /*name = this.name*/ ) {
  35880. console.warn( 'Abstract function.' );
  35881. }
  35882. }
  35883. NodeFunction.isNodeFunction = true;
  35884. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  35885. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  35886. const pragmaMain = '#pragma main';
  35887. const parse$1 = ( source ) => {
  35888. source = source.trim();
  35889. const pragmaMainIndex = source.indexOf( pragmaMain );
  35890. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  35891. const declaration = mainCode.match( declarationRegexp$1 );
  35892. if ( declaration !== null && declaration.length === 5 ) {
  35893. // tokenizer
  35894. const inputsCode = declaration[ 4 ];
  35895. const propsMatches = [];
  35896. let nameMatch = null;
  35897. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  35898. propsMatches.push( nameMatch );
  35899. }
  35900. // parser
  35901. const inputs = [];
  35902. let i = 0;
  35903. while ( i < propsMatches.length ) {
  35904. const isConst = propsMatches[ i ][ 0 ] === 'const';
  35905. if ( isConst === true ) {
  35906. i ++;
  35907. }
  35908. let qualifier = propsMatches[ i ][ 0 ];
  35909. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  35910. i ++;
  35911. } else {
  35912. qualifier = '';
  35913. }
  35914. const type = propsMatches[ i ++ ][ 0 ];
  35915. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  35916. if ( Number.isNaN( count ) === false ) i ++;
  35917. else count = null;
  35918. const name = propsMatches[ i ++ ][ 0 ];
  35919. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  35920. }
  35921. //
  35922. const blockCode = mainCode.substring( declaration[ 0 ].length );
  35923. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  35924. const type = declaration[ 2 ];
  35925. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  35926. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  35927. return {
  35928. type,
  35929. inputs,
  35930. name,
  35931. precision,
  35932. inputsCode,
  35933. blockCode,
  35934. headerCode
  35935. };
  35936. } else {
  35937. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  35938. }
  35939. };
  35940. /**
  35941. * This class represents a GLSL node function.
  35942. *
  35943. * @augments NodeFunction
  35944. */
  35945. class GLSLNodeFunction extends NodeFunction {
  35946. /**
  35947. * Constructs a new GLSL node function.
  35948. *
  35949. * @param {string} source - The GLSL source.
  35950. */
  35951. constructor( source ) {
  35952. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  35953. super( type, inputs, name, precision );
  35954. this.inputsCode = inputsCode;
  35955. this.blockCode = blockCode;
  35956. this.headerCode = headerCode;
  35957. }
  35958. /**
  35959. * This method returns the GLSL code of the node function.
  35960. *
  35961. * @param {string} [name=this.name] - The function's name.
  35962. * @return {string} The shader code.
  35963. */
  35964. getCode( name = this.name ) {
  35965. let code;
  35966. const blockCode = this.blockCode;
  35967. if ( blockCode !== '' ) {
  35968. const { type, inputsCode, headerCode, precision } = this;
  35969. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  35970. if ( precision !== '' ) {
  35971. declarationCode = `${ precision } ${ declarationCode }`;
  35972. }
  35973. code = headerCode + declarationCode + blockCode;
  35974. } else {
  35975. // interface function
  35976. code = '';
  35977. }
  35978. return code;
  35979. }
  35980. }
  35981. /**
  35982. * A GLSL node parser.
  35983. *
  35984. * @augments NodeParser
  35985. */
  35986. class GLSLNodeParser extends NodeParser {
  35987. /**
  35988. * The method parses the given GLSL code an returns a node function.
  35989. *
  35990. * @param {string} source - The GLSL code.
  35991. * @return {GLSLNodeFunction} A node function.
  35992. */
  35993. parseFunction( source ) {
  35994. return new GLSLNodeFunction( source );
  35995. }
  35996. }
  35997. const _outputNodeMap = new WeakMap();
  35998. const _chainKeys$2 = [];
  35999. const _cacheKeyValues = [];
  36000. /**
  36001. * This renderer module manages node-related objects and is the
  36002. * primary interface between the renderer and the node system.
  36003. *
  36004. * @private
  36005. * @augments DataMap
  36006. */
  36007. class Nodes extends DataMap {
  36008. /**
  36009. * Constructs a new nodes management component.
  36010. *
  36011. * @param {Renderer} renderer - The renderer.
  36012. * @param {Backend} backend - The renderer's backend.
  36013. */
  36014. constructor( renderer, backend ) {
  36015. super();
  36016. /**
  36017. * The renderer.
  36018. *
  36019. * @type {Renderer}
  36020. */
  36021. this.renderer = renderer;
  36022. /**
  36023. * The renderer's backend.
  36024. *
  36025. * @type {Backend}
  36026. */
  36027. this.backend = backend;
  36028. /**
  36029. * The node frame.
  36030. *
  36031. * @type {Renderer}
  36032. */
  36033. this.nodeFrame = new NodeFrame();
  36034. /**
  36035. * A cache for managing node builder states.
  36036. *
  36037. * @type {Map<number,NodeBuilderState>}
  36038. */
  36039. this.nodeBuilderCache = new Map();
  36040. /**
  36041. * A cache for managing data cache key data.
  36042. *
  36043. * @type {ChainMap}
  36044. */
  36045. this.callHashCache = new ChainMap();
  36046. /**
  36047. * A cache for managing node uniforms group data.
  36048. *
  36049. * @type {ChainMap}
  36050. */
  36051. this.groupsData = new ChainMap();
  36052. /**
  36053. * A cache for managing node objects of
  36054. * scene properties like fog or environments.
  36055. *
  36056. * @type {Object<string,WeakMap>}
  36057. */
  36058. this.cacheLib = {};
  36059. }
  36060. /**
  36061. * Returns `true` if the given node uniforms group must be updated or not.
  36062. *
  36063. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  36064. * @return {boolean} Whether the node uniforms group requires an update or not.
  36065. */
  36066. updateGroup( nodeUniformsGroup ) {
  36067. const groupNode = nodeUniformsGroup.groupNode;
  36068. const name = groupNode.name;
  36069. // objectGroup is always updated
  36070. if ( name === objectGroup.name ) return true;
  36071. // renderGroup is updated once per render/compute call
  36072. if ( name === renderGroup.name ) {
  36073. const uniformsGroupData = this.get( nodeUniformsGroup );
  36074. const renderId = this.nodeFrame.renderId;
  36075. if ( uniformsGroupData.renderId !== renderId ) {
  36076. uniformsGroupData.renderId = renderId;
  36077. return true;
  36078. }
  36079. return false;
  36080. }
  36081. // frameGroup is updated once per frame
  36082. if ( name === frameGroup.name ) {
  36083. const uniformsGroupData = this.get( nodeUniformsGroup );
  36084. const frameId = this.nodeFrame.frameId;
  36085. if ( uniformsGroupData.frameId !== frameId ) {
  36086. uniformsGroupData.frameId = frameId;
  36087. return true;
  36088. }
  36089. return false;
  36090. }
  36091. // other groups are updated just when groupNode.needsUpdate is true
  36092. _chainKeys$2[ 0 ] = groupNode;
  36093. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  36094. let groupData = this.groupsData.get( _chainKeys$2 );
  36095. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  36096. _chainKeys$2.length = 0;
  36097. if ( groupData.version !== groupNode.version ) {
  36098. groupData.version = groupNode.version;
  36099. return true;
  36100. }
  36101. return false;
  36102. }
  36103. /**
  36104. * Returns the cache key for the given render object.
  36105. *
  36106. * @param {RenderObject} renderObject - The render object.
  36107. * @return {number} The cache key.
  36108. */
  36109. getForRenderCacheKey( renderObject ) {
  36110. return renderObject.initialCacheKey;
  36111. }
  36112. /**
  36113. * Returns a node builder state for the given render object.
  36114. *
  36115. * @param {RenderObject} renderObject - The render object.
  36116. * @return {NodeBuilderState} The node builder state.
  36117. */
  36118. getForRender( renderObject ) {
  36119. const renderObjectData = this.get( renderObject );
  36120. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36121. if ( nodeBuilderState === undefined ) {
  36122. const { nodeBuilderCache } = this;
  36123. const cacheKey = this.getForRenderCacheKey( renderObject );
  36124. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36125. if ( nodeBuilderState === undefined ) {
  36126. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36127. nodeBuilder.scene = renderObject.scene;
  36128. nodeBuilder.material = renderObject.material;
  36129. nodeBuilder.camera = renderObject.camera;
  36130. nodeBuilder.context.material = renderObject.material;
  36131. nodeBuilder.lightsNode = renderObject.lightsNode;
  36132. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36133. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36134. nodeBuilder.clippingContext = renderObject.clippingContext;
  36135. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  36136. nodeBuilder.enableMultiview();
  36137. }
  36138. nodeBuilder.build();
  36139. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36140. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  36141. }
  36142. nodeBuilderState.usedTimes ++;
  36143. renderObjectData.nodeBuilderState = nodeBuilderState;
  36144. }
  36145. return nodeBuilderState;
  36146. }
  36147. /**
  36148. * Deletes the given object from the internal data map
  36149. *
  36150. * @param {any} object - The object to delete.
  36151. * @return {?Object} The deleted dictionary.
  36152. */
  36153. delete( object ) {
  36154. if ( object.isRenderObject ) {
  36155. const nodeBuilderState = this.get( object ).nodeBuilderState;
  36156. nodeBuilderState.usedTimes --;
  36157. if ( nodeBuilderState.usedTimes === 0 ) {
  36158. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  36159. }
  36160. }
  36161. return super.delete( object );
  36162. }
  36163. /**
  36164. * Returns a node builder state for the given compute node.
  36165. *
  36166. * @param {Node} computeNode - The compute node.
  36167. * @return {NodeBuilderState} The node builder state.
  36168. */
  36169. getForCompute( computeNode ) {
  36170. const computeData = this.get( computeNode );
  36171. let nodeBuilderState = computeData.nodeBuilderState;
  36172. if ( nodeBuilderState === undefined ) {
  36173. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  36174. nodeBuilder.build();
  36175. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36176. computeData.nodeBuilderState = nodeBuilderState;
  36177. }
  36178. return nodeBuilderState;
  36179. }
  36180. /**
  36181. * Creates a node builder state for the given node builder.
  36182. *
  36183. * @private
  36184. * @param {NodeBuilder} nodeBuilder - The node builder.
  36185. * @return {NodeBuilderState} The node builder state.
  36186. */
  36187. _createNodeBuilderState( nodeBuilder ) {
  36188. return new NodeBuilderState(
  36189. nodeBuilder.vertexShader,
  36190. nodeBuilder.fragmentShader,
  36191. nodeBuilder.computeShader,
  36192. nodeBuilder.getAttributesArray(),
  36193. nodeBuilder.getBindings(),
  36194. nodeBuilder.updateNodes,
  36195. nodeBuilder.updateBeforeNodes,
  36196. nodeBuilder.updateAfterNodes,
  36197. nodeBuilder.observer,
  36198. nodeBuilder.transforms
  36199. );
  36200. }
  36201. /**
  36202. * Returns an environment node for the current configured
  36203. * scene environment.
  36204. *
  36205. * @param {Scene} scene - The scene.
  36206. * @return {Node} A node representing the current scene environment.
  36207. */
  36208. getEnvironmentNode( scene ) {
  36209. this.updateEnvironment( scene );
  36210. let environmentNode = null;
  36211. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  36212. environmentNode = scene.environmentNode;
  36213. } else {
  36214. const sceneData = this.get( scene );
  36215. if ( sceneData.environmentNode ) {
  36216. environmentNode = sceneData.environmentNode;
  36217. }
  36218. }
  36219. return environmentNode;
  36220. }
  36221. /**
  36222. * Returns a background node for the current configured
  36223. * scene background.
  36224. *
  36225. * @param {Scene} scene - The scene.
  36226. * @return {Node} A node representing the current scene background.
  36227. */
  36228. getBackgroundNode( scene ) {
  36229. this.updateBackground( scene );
  36230. let backgroundNode = null;
  36231. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  36232. backgroundNode = scene.backgroundNode;
  36233. } else {
  36234. const sceneData = this.get( scene );
  36235. if ( sceneData.backgroundNode ) {
  36236. backgroundNode = sceneData.backgroundNode;
  36237. }
  36238. }
  36239. return backgroundNode;
  36240. }
  36241. /**
  36242. * Returns a fog node for the current configured scene fog.
  36243. *
  36244. * @param {Scene} scene - The scene.
  36245. * @return {Node} A node representing the current scene fog.
  36246. */
  36247. getFogNode( scene ) {
  36248. this.updateFog( scene );
  36249. return scene.fogNode || this.get( scene ).fogNode || null;
  36250. }
  36251. /**
  36252. * Returns a cache key for the given scene and lights node.
  36253. * This key is used by `RenderObject` as a part of the dynamic
  36254. * cache key (a key that must be checked every time the render
  36255. * objects is drawn).
  36256. *
  36257. * @param {Scene} scene - The scene.
  36258. * @param {LightsNode} lightsNode - The lights node.
  36259. * @return {number} The cache key.
  36260. */
  36261. getCacheKey( scene, lightsNode ) {
  36262. _chainKeys$2[ 0 ] = scene;
  36263. _chainKeys$2[ 1 ] = lightsNode;
  36264. const callId = this.renderer.info.calls;
  36265. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  36266. if ( cacheKeyData.callId !== callId ) {
  36267. const environmentNode = this.getEnvironmentNode( scene );
  36268. const fogNode = this.getFogNode( scene );
  36269. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  36270. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  36271. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  36272. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  36273. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  36274. cacheKeyData.callId = callId;
  36275. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  36276. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  36277. _cacheKeyValues.length = 0;
  36278. }
  36279. _chainKeys$2.length = 0;
  36280. return cacheKeyData.cacheKey;
  36281. }
  36282. /**
  36283. * A boolean that indicates whether tone mapping should be enabled
  36284. * or not.
  36285. *
  36286. * @type {boolean}
  36287. */
  36288. get isToneMappingState() {
  36289. return this.renderer.getRenderTarget() ? false : true;
  36290. }
  36291. /**
  36292. * If a scene background is configured, this method makes sure to
  36293. * represent the background with a corresponding node-based implementation.
  36294. *
  36295. * @param {Scene} scene - The scene.
  36296. */
  36297. updateBackground( scene ) {
  36298. const sceneData = this.get( scene );
  36299. const background = scene.background;
  36300. if ( background ) {
  36301. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  36302. if ( sceneData.background !== background || forceUpdate ) {
  36303. const backgroundNode = this.getCacheNode( 'background', background, () => {
  36304. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  36305. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  36306. return pmremTexture( background );
  36307. } else {
  36308. let envMap;
  36309. if ( background.isCubeTexture === true ) {
  36310. envMap = cubeTexture( background );
  36311. } else {
  36312. envMap = texture( background );
  36313. }
  36314. return cubeMapNode( envMap );
  36315. }
  36316. } else if ( background.isTexture === true ) {
  36317. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  36318. } else if ( background.isColor !== true ) {
  36319. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  36320. }
  36321. }, forceUpdate );
  36322. sceneData.backgroundNode = backgroundNode;
  36323. sceneData.background = background;
  36324. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  36325. }
  36326. } else if ( sceneData.backgroundNode ) {
  36327. delete sceneData.backgroundNode;
  36328. delete sceneData.background;
  36329. }
  36330. }
  36331. /**
  36332. * This method is part of the caching of nodes which are used to represents the
  36333. * scene's background, fog or environment.
  36334. *
  36335. * @param {string} type - The type of object to cache.
  36336. * @param {Object} object - The object.
  36337. * @param {Function} callback - A callback that produces a node representation for the given object.
  36338. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  36339. * @return {Node} The node representation.
  36340. */
  36341. getCacheNode( type, object, callback, forceUpdate = false ) {
  36342. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  36343. let node = nodeCache.get( object );
  36344. if ( node === undefined || forceUpdate ) {
  36345. node = callback();
  36346. nodeCache.set( object, node );
  36347. }
  36348. return node;
  36349. }
  36350. /**
  36351. * If a scene fog is configured, this method makes sure to
  36352. * represent the fog with a corresponding node-based implementation.
  36353. *
  36354. * @param {Scene} scene - The scene.
  36355. */
  36356. updateFog( scene ) {
  36357. const sceneData = this.get( scene );
  36358. const sceneFog = scene.fog;
  36359. if ( sceneFog ) {
  36360. if ( sceneData.fog !== sceneFog ) {
  36361. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  36362. if ( sceneFog.isFogExp2 ) {
  36363. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36364. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  36365. return fog( color, densityFogFactor( density ) );
  36366. } else if ( sceneFog.isFog ) {
  36367. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36368. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  36369. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  36370. return fog( color, rangeFogFactor( near, far ) );
  36371. } else {
  36372. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  36373. }
  36374. } );
  36375. sceneData.fogNode = fogNode;
  36376. sceneData.fog = sceneFog;
  36377. }
  36378. } else {
  36379. delete sceneData.fogNode;
  36380. delete sceneData.fog;
  36381. }
  36382. }
  36383. /**
  36384. * If a scene environment is configured, this method makes sure to
  36385. * represent the environment with a corresponding node-based implementation.
  36386. *
  36387. * @param {Scene} scene - The scene.
  36388. */
  36389. updateEnvironment( scene ) {
  36390. const sceneData = this.get( scene );
  36391. const environment = scene.environment;
  36392. if ( environment ) {
  36393. if ( sceneData.environment !== environment ) {
  36394. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  36395. if ( environment.isCubeTexture === true ) {
  36396. return cubeTexture( environment );
  36397. } else if ( environment.isTexture === true ) {
  36398. return texture( environment );
  36399. } else {
  36400. console.error( 'Nodes: Unsupported environment configuration.', environment );
  36401. }
  36402. } );
  36403. sceneData.environmentNode = environmentNode;
  36404. sceneData.environment = environment;
  36405. }
  36406. } else if ( sceneData.environmentNode ) {
  36407. delete sceneData.environmentNode;
  36408. delete sceneData.environment;
  36409. }
  36410. }
  36411. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  36412. const nodeFrame = this.nodeFrame;
  36413. nodeFrame.renderer = renderer;
  36414. nodeFrame.scene = scene;
  36415. nodeFrame.object = object;
  36416. nodeFrame.camera = camera;
  36417. nodeFrame.material = material;
  36418. return nodeFrame;
  36419. }
  36420. getNodeFrameForRender( renderObject ) {
  36421. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  36422. }
  36423. /**
  36424. * Returns the current output cache key.
  36425. *
  36426. * @return {string} The output cache key.
  36427. */
  36428. getOutputCacheKey() {
  36429. const renderer = this.renderer;
  36430. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  36431. }
  36432. /**
  36433. * Checks if the output configuration (tone mapping and color space) for
  36434. * the given target has changed.
  36435. *
  36436. * @param {Texture} outputTarget - The output target.
  36437. * @return {boolean} Whether the output configuration has changed or not.
  36438. */
  36439. hasOutputChange( outputTarget ) {
  36440. const cacheKey = _outputNodeMap.get( outputTarget );
  36441. return cacheKey !== this.getOutputCacheKey();
  36442. }
  36443. /**
  36444. * Returns a node that represents the output configuration (tone mapping and
  36445. * color space) for the current target.
  36446. *
  36447. * @param {Texture} outputTarget - The output target.
  36448. * @return {Node} The output node.
  36449. */
  36450. getOutputNode( outputTarget ) {
  36451. const renderer = this.renderer;
  36452. const cacheKey = this.getOutputCacheKey();
  36453. const output = outputTarget.isArrayTexture ?
  36454. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  36455. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  36456. _outputNodeMap.set( outputTarget, cacheKey );
  36457. return output;
  36458. }
  36459. /**
  36460. * Triggers the call of `updateBefore()` methods
  36461. * for all nodes of the given render object.
  36462. *
  36463. * @param {RenderObject} renderObject - The render object.
  36464. */
  36465. updateBefore( renderObject ) {
  36466. const nodeBuilder = renderObject.getNodeBuilderState();
  36467. for ( const node of nodeBuilder.updateBeforeNodes ) {
  36468. // update frame state for each node
  36469. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  36470. }
  36471. }
  36472. /**
  36473. * Triggers the call of `updateAfter()` methods
  36474. * for all nodes of the given render object.
  36475. *
  36476. * @param {RenderObject} renderObject - The render object.
  36477. */
  36478. updateAfter( renderObject ) {
  36479. const nodeBuilder = renderObject.getNodeBuilderState();
  36480. for ( const node of nodeBuilder.updateAfterNodes ) {
  36481. // update frame state for each node
  36482. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  36483. }
  36484. }
  36485. /**
  36486. * Triggers the call of `update()` methods
  36487. * for all nodes of the given compute node.
  36488. *
  36489. * @param {Node} computeNode - The compute node.
  36490. */
  36491. updateForCompute( computeNode ) {
  36492. const nodeFrame = this.getNodeFrame();
  36493. const nodeBuilder = this.getForCompute( computeNode );
  36494. for ( const node of nodeBuilder.updateNodes ) {
  36495. nodeFrame.updateNode( node );
  36496. }
  36497. }
  36498. /**
  36499. * Triggers the call of `update()` methods
  36500. * for all nodes of the given compute node.
  36501. *
  36502. * @param {RenderObject} renderObject - The render object.
  36503. */
  36504. updateForRender( renderObject ) {
  36505. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36506. const nodeBuilder = renderObject.getNodeBuilderState();
  36507. for ( const node of nodeBuilder.updateNodes ) {
  36508. nodeFrame.updateNode( node );
  36509. }
  36510. }
  36511. /**
  36512. * Returns `true` if the given render object requires a refresh.
  36513. *
  36514. * @param {RenderObject} renderObject - The render object.
  36515. * @return {boolean} Whether the given render object requires a refresh or not.
  36516. */
  36517. needsRefresh( renderObject ) {
  36518. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36519. const monitor = renderObject.getMonitor();
  36520. return monitor.needsRefresh( renderObject, nodeFrame );
  36521. }
  36522. /**
  36523. * Frees the internal resources.
  36524. */
  36525. dispose() {
  36526. super.dispose();
  36527. this.nodeFrame = new NodeFrame();
  36528. this.nodeBuilderCache = new Map();
  36529. this.cacheLib = {};
  36530. }
  36531. }
  36532. const _plane = /*@__PURE__*/ new Plane();
  36533. /**
  36534. * Represents the state that is used to perform clipping via clipping planes.
  36535. * There is a default clipping context for each render context. When the
  36536. * scene holds instances of `ClippingGroup`, there will be a context for each
  36537. * group.
  36538. *
  36539. * @private
  36540. */
  36541. class ClippingContext {
  36542. /**
  36543. * Constructs a new clipping context.
  36544. *
  36545. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  36546. */
  36547. constructor( parentContext = null ) {
  36548. /**
  36549. * The clipping context's version.
  36550. *
  36551. * @type {number}
  36552. * @readonly
  36553. */
  36554. this.version = 0;
  36555. /**
  36556. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  36557. *
  36558. * @type {?boolean}
  36559. * @default null
  36560. */
  36561. this.clipIntersection = null;
  36562. /**
  36563. * The clipping context's cache key.
  36564. *
  36565. * @type {string}
  36566. */
  36567. this.cacheKey = '';
  36568. /**
  36569. * Whether the shadow pass is active or not.
  36570. *
  36571. * @type {boolean}
  36572. * @default false
  36573. */
  36574. this.shadowPass = false;
  36575. /**
  36576. * The view normal matrix.
  36577. *
  36578. * @type {Matrix3}
  36579. */
  36580. this.viewNormalMatrix = new Matrix3();
  36581. /**
  36582. * Internal cache for maintaining clipping contexts.
  36583. *
  36584. * @type {WeakMap<ClippingGroup,ClippingContext>}
  36585. */
  36586. this.clippingGroupContexts = new WeakMap();
  36587. /**
  36588. * The intersection planes.
  36589. *
  36590. * @type {Array<Vector4>}
  36591. */
  36592. this.intersectionPlanes = [];
  36593. /**
  36594. * The intersection planes.
  36595. *
  36596. * @type {Array<Vector4>}
  36597. */
  36598. this.unionPlanes = [];
  36599. /**
  36600. * The version of the clipping context's parent context.
  36601. *
  36602. * @type {?number}
  36603. * @readonly
  36604. */
  36605. this.parentVersion = null;
  36606. if ( parentContext !== null ) {
  36607. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  36608. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  36609. this.shadowPass = parentContext.shadowPass;
  36610. this.viewMatrix = parentContext.viewMatrix;
  36611. }
  36612. }
  36613. /**
  36614. * Projects the given source clipping planes and writes the result into the
  36615. * destination array.
  36616. *
  36617. * @param {Array<Plane>} source - The source clipping planes.
  36618. * @param {Array<Vector4>} destination - The destination.
  36619. * @param {number} offset - The offset.
  36620. */
  36621. projectPlanes( source, destination, offset ) {
  36622. const l = source.length;
  36623. for ( let i = 0; i < l; i ++ ) {
  36624. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  36625. const v = destination[ offset + i ];
  36626. const normal = _plane.normal;
  36627. v.x = - normal.x;
  36628. v.y = - normal.y;
  36629. v.z = - normal.z;
  36630. v.w = _plane.constant;
  36631. }
  36632. }
  36633. /**
  36634. * Updates the root clipping context of a scene.
  36635. *
  36636. * @param {Scene} scene - The scene.
  36637. * @param {Camera} camera - The camera that is used to render the scene.
  36638. */
  36639. updateGlobal( scene, camera ) {
  36640. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  36641. this.viewMatrix = camera.matrixWorldInverse;
  36642. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  36643. }
  36644. /**
  36645. * Updates the clipping context.
  36646. *
  36647. * @param {ClippingContext} parentContext - The parent context.
  36648. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  36649. */
  36650. update( parentContext, clippingGroup ) {
  36651. let update = false;
  36652. if ( parentContext.version !== this.parentVersion ) {
  36653. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  36654. this.unionPlanes = Array.from( parentContext.unionPlanes );
  36655. this.parentVersion = parentContext.version;
  36656. }
  36657. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  36658. this.clipIntersection = clippingGroup.clipIntersection;
  36659. if ( this.clipIntersection ) {
  36660. this.unionPlanes.length = parentContext.unionPlanes.length;
  36661. } else {
  36662. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  36663. }
  36664. }
  36665. const srcClippingPlanes = clippingGroup.clippingPlanes;
  36666. const l = srcClippingPlanes.length;
  36667. let dstClippingPlanes;
  36668. let offset;
  36669. if ( this.clipIntersection ) {
  36670. dstClippingPlanes = this.intersectionPlanes;
  36671. offset = parentContext.intersectionPlanes.length;
  36672. } else {
  36673. dstClippingPlanes = this.unionPlanes;
  36674. offset = parentContext.unionPlanes.length;
  36675. }
  36676. if ( dstClippingPlanes.length !== offset + l ) {
  36677. dstClippingPlanes.length = offset + l;
  36678. for ( let i = 0; i < l; i ++ ) {
  36679. dstClippingPlanes[ offset + i ] = new Vector4();
  36680. }
  36681. update = true;
  36682. }
  36683. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  36684. if ( update ) {
  36685. this.version ++;
  36686. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  36687. }
  36688. }
  36689. /**
  36690. * Returns a clipping context for the given clipping group.
  36691. *
  36692. * @param {ClippingGroup} clippingGroup - The clipping group.
  36693. * @return {ClippingContext} The clipping context.
  36694. */
  36695. getGroupContext( clippingGroup ) {
  36696. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  36697. let context = this.clippingGroupContexts.get( clippingGroup );
  36698. if ( context === undefined ) {
  36699. context = new ClippingContext( this );
  36700. this.clippingGroupContexts.set( clippingGroup, context );
  36701. }
  36702. context.update( this, clippingGroup );
  36703. return context;
  36704. }
  36705. /**
  36706. * The count of union clipping planes.
  36707. *
  36708. * @type {number}
  36709. * @readonly
  36710. */
  36711. get unionClippingCount() {
  36712. return this.unionPlanes.length;
  36713. }
  36714. }
  36715. /**
  36716. * This module is used to represent render bundles inside the renderer
  36717. * for further processing.
  36718. *
  36719. * @private
  36720. */
  36721. class RenderBundle {
  36722. /**
  36723. * Constructs a new bundle group.
  36724. *
  36725. * @param {BundleGroup} bundleGroup - The bundle group.
  36726. * @param {Camera} camera - The camera the bundle group is rendered with.
  36727. */
  36728. constructor( bundleGroup, camera ) {
  36729. this.bundleGroup = bundleGroup;
  36730. this.camera = camera;
  36731. }
  36732. }
  36733. const _chainKeys$1 = [];
  36734. /**
  36735. * This renderer module manages render bundles.
  36736. *
  36737. * @private
  36738. */
  36739. class RenderBundles {
  36740. /**
  36741. * Constructs a new render bundle management component.
  36742. */
  36743. constructor() {
  36744. /**
  36745. * A chain map for maintaining the render bundles.
  36746. *
  36747. * @type {ChainMap}
  36748. */
  36749. this.bundles = new ChainMap();
  36750. }
  36751. /**
  36752. * Returns a render bundle for the given bundle group and camera.
  36753. *
  36754. * @param {BundleGroup} bundleGroup - The bundle group.
  36755. * @param {Camera} camera - The camera the bundle group is rendered with.
  36756. * @return {RenderBundle} The render bundle.
  36757. */
  36758. get( bundleGroup, camera ) {
  36759. const bundles = this.bundles;
  36760. _chainKeys$1[ 0 ] = bundleGroup;
  36761. _chainKeys$1[ 1 ] = camera;
  36762. let bundle = bundles.get( _chainKeys$1 );
  36763. if ( bundle === undefined ) {
  36764. bundle = new RenderBundle( bundleGroup, camera );
  36765. bundles.set( _chainKeys$1, bundle );
  36766. }
  36767. _chainKeys$1.length = 0;
  36768. return bundle;
  36769. }
  36770. /**
  36771. * Frees all internal resources.
  36772. */
  36773. dispose() {
  36774. this.bundles = new ChainMap();
  36775. }
  36776. }
  36777. /**
  36778. * The purpose of a node library is to assign node implementations
  36779. * to existing library features. In `WebGPURenderer` lights, materials
  36780. * which are not based on `NodeMaterial` as well as tone mapping techniques
  36781. * are implemented with node-based modules.
  36782. *
  36783. * @private
  36784. */
  36785. class NodeLibrary {
  36786. /**
  36787. * Constructs a new node library.
  36788. */
  36789. constructor() {
  36790. /**
  36791. * A weak map that maps lights to light nodes.
  36792. *
  36793. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  36794. */
  36795. this.lightNodes = new WeakMap();
  36796. /**
  36797. * A map that maps materials to node materials.
  36798. *
  36799. * @type {Map<string,NodeMaterial.constructor>}
  36800. */
  36801. this.materialNodes = new Map();
  36802. /**
  36803. * A map that maps tone mapping techniques (constants)
  36804. * to tone mapping node functions.
  36805. *
  36806. * @type {Map<number,Function>}
  36807. */
  36808. this.toneMappingNodes = new Map();
  36809. }
  36810. /**
  36811. * Returns a matching node material instance for the given material object.
  36812. *
  36813. * This method also assigns/copies the properties of the given material object
  36814. * to the node material. This is done to make sure the current material
  36815. * configuration carries over to the node version.
  36816. *
  36817. * @param {Material} material - A material.
  36818. * @return {NodeMaterial} The corresponding node material.
  36819. */
  36820. fromMaterial( material ) {
  36821. if ( material.isNodeMaterial ) return material;
  36822. let nodeMaterial = null;
  36823. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  36824. if ( nodeMaterialClass !== null ) {
  36825. nodeMaterial = new nodeMaterialClass();
  36826. for ( const key in material ) {
  36827. nodeMaterial[ key ] = material[ key ];
  36828. }
  36829. }
  36830. return nodeMaterial;
  36831. }
  36832. /**
  36833. * Adds a tone mapping node function for a tone mapping technique (constant).
  36834. *
  36835. * @param {Function} toneMappingNode - The tone mapping node function.
  36836. * @param {number} toneMapping - The tone mapping.
  36837. */
  36838. addToneMapping( toneMappingNode, toneMapping ) {
  36839. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  36840. }
  36841. /**
  36842. * Returns a tone mapping node function for a tone mapping technique (constant).
  36843. *
  36844. * @param {number} toneMapping - The tone mapping.
  36845. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  36846. */
  36847. getToneMappingFunction( toneMapping ) {
  36848. return this.toneMappingNodes.get( toneMapping ) || null;
  36849. }
  36850. /**
  36851. * Returns a node material class definition for a material type.
  36852. *
  36853. * @param {string} materialType - The material type.
  36854. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  36855. */
  36856. getMaterialNodeClass( materialType ) {
  36857. return this.materialNodes.get( materialType ) || null;
  36858. }
  36859. /**
  36860. * Adds a node material class definition for a given material type.
  36861. *
  36862. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  36863. * @param {string} materialClassType - The material type.
  36864. */
  36865. addMaterial( materialNodeClass, materialClassType ) {
  36866. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  36867. }
  36868. /**
  36869. * Returns a light node class definition for a light class definition.
  36870. *
  36871. * @param {Light.constructor} light - The light class definition.
  36872. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  36873. */
  36874. getLightNodeClass( light ) {
  36875. return this.lightNodes.get( light ) || null;
  36876. }
  36877. /**
  36878. * Adds a light node class definition for a given light class definition.
  36879. *
  36880. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  36881. * @param {Light.constructor} lightClass - The light class definition.
  36882. */
  36883. addLight( lightNodeClass, lightClass ) {
  36884. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  36885. }
  36886. /**
  36887. * Adds a node class definition for the given type to the provided type library.
  36888. *
  36889. * @param {any} nodeClass - The node class definition.
  36890. * @param {number|string} type - The object type.
  36891. * @param {Map} library - The type library.
  36892. */
  36893. addType( nodeClass, type, library ) {
  36894. if ( library.has( type ) ) {
  36895. console.warn( `Redefinition of node ${ type }` );
  36896. return;
  36897. }
  36898. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  36899. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  36900. library.set( type, nodeClass );
  36901. }
  36902. /**
  36903. * Adds a node class definition for the given class definition to the provided type library.
  36904. *
  36905. * @param {any} nodeClass - The node class definition.
  36906. * @param {any} baseClass - The class definition.
  36907. * @param {WeakMap} library - The type library.
  36908. */
  36909. addClass( nodeClass, baseClass, library ) {
  36910. if ( library.has( baseClass ) ) {
  36911. console.warn( `Redefinition of node ${ baseClass.name }` );
  36912. return;
  36913. }
  36914. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  36915. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  36916. library.set( baseClass, nodeClass );
  36917. }
  36918. }
  36919. const _defaultLights = /*@__PURE__*/ new LightsNode();
  36920. const _chainKeys = [];
  36921. /**
  36922. * This renderer module manages the lights nodes which are unique
  36923. * per scene and camera combination.
  36924. *
  36925. * The lights node itself is later configured in the render list
  36926. * with the actual lights from the scene.
  36927. *
  36928. * @private
  36929. * @augments ChainMap
  36930. */
  36931. class Lighting extends ChainMap {
  36932. /**
  36933. * Constructs a lighting management component.
  36934. */
  36935. constructor() {
  36936. super();
  36937. }
  36938. /**
  36939. * Creates a new lights node for the given array of lights.
  36940. *
  36941. * @param {Array<Light>} lights - The render object.
  36942. * @return {LightsNode} The lights node.
  36943. */
  36944. createNode( lights = [] ) {
  36945. return new LightsNode().setLights( lights );
  36946. }
  36947. /**
  36948. * Returns a lights node for the given scene and camera.
  36949. *
  36950. * @param {Scene} scene - The scene.
  36951. * @param {Camera} camera - The camera.
  36952. * @return {LightsNode} The lights node.
  36953. */
  36954. getNode( scene, camera ) {
  36955. // ignore post-processing
  36956. if ( scene.isQuadMesh ) return _defaultLights;
  36957. _chainKeys[ 0 ] = scene;
  36958. _chainKeys[ 1 ] = camera;
  36959. let node = this.get( _chainKeys );
  36960. if ( node === undefined ) {
  36961. node = this.createNode();
  36962. this.set( _chainKeys, node );
  36963. }
  36964. _chainKeys.length = 0;
  36965. return node;
  36966. }
  36967. }
  36968. /**
  36969. * A special type of render target that is used when rendering
  36970. * with the WebXR Device API.
  36971. *
  36972. * @private
  36973. * @augments RenderTarget
  36974. */
  36975. class XRRenderTarget extends RenderTarget {
  36976. /**
  36977. * Constructs a new XR render target.
  36978. *
  36979. * @param {number} [width=1] - The width of the render target.
  36980. * @param {number} [height=1] - The height of the render target.
  36981. * @param {Object} [options={}] - The configuration options.
  36982. */
  36983. constructor( width = 1, height = 1, options = {} ) {
  36984. super( width, height, options );
  36985. /**
  36986. * This flag can be used for type testing.
  36987. *
  36988. * @type {boolean}
  36989. * @readonly
  36990. * @default true
  36991. */
  36992. this.isXRRenderTarget = true;
  36993. /**
  36994. * Whether the attachments of the render target
  36995. * are defined by external textures. This flag is
  36996. * set to `true` when using the WebXR Layers API.
  36997. *
  36998. * @private
  36999. * @type {boolean}
  37000. * @default false
  37001. */
  37002. this._hasExternalTextures = false;
  37003. /**
  37004. * Whether a depth buffer should automatically be allocated
  37005. * for this XR render target or not.
  37006. *
  37007. * Allocating a depth buffer is the default behavior of XR render
  37008. * targets. However, when using the WebXR Layers API, this flag
  37009. * must be set to `false` when the `ignoreDepthValues` property of
  37010. * the projection layers evaluates to `false`.
  37011. *
  37012. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  37013. *
  37014. * @private
  37015. * @type {boolean}
  37016. * @default true
  37017. */
  37018. this._autoAllocateDepthBuffer = true;
  37019. /**
  37020. * Whether this render target is associated with a XRWebGLLayer.
  37021. *
  37022. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  37023. * this means that you don't have access to its bound color,
  37024. * stencil and depth buffers. We need to handle this framebuffer
  37025. * differently since its textures are always bound.
  37026. *
  37027. * @private
  37028. * @type {boolean}
  37029. * @default false
  37030. * */
  37031. this._isOpaqueFramebuffer = false;
  37032. }
  37033. copy( source ) {
  37034. super.copy( source );
  37035. this._hasExternalTextures = source._hasExternalTextures;
  37036. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  37037. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  37038. return this;
  37039. }
  37040. }
  37041. const _cameraLPos = /*@__PURE__*/ new Vector3();
  37042. const _cameraRPos = /*@__PURE__*/ new Vector3();
  37043. /**
  37044. * The XR manager is built on top of the WebXR Device API to
  37045. * manage XR sessions with `WebGPURenderer`.
  37046. *
  37047. * XR is currently only supported with a WebGL 2 backend.
  37048. *
  37049. * @augments EventDispatcher
  37050. */
  37051. class XRManager extends EventDispatcher {
  37052. /**
  37053. * Constructs a new XR manager.
  37054. *
  37055. * @param {Renderer} renderer - The renderer.
  37056. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  37057. */
  37058. constructor( renderer, multiview = false ) {
  37059. super();
  37060. /**
  37061. * This flag globally enables XR rendering.
  37062. *
  37063. * @type {boolean}
  37064. * @default false
  37065. */
  37066. this.enabled = false;
  37067. /**
  37068. * Whether the XR device is currently presenting or not.
  37069. *
  37070. * @type {boolean}
  37071. * @default false
  37072. * @readonly
  37073. */
  37074. this.isPresenting = false;
  37075. /**
  37076. * Whether the XR camera should automatically be updated or not.
  37077. *
  37078. * @type {boolean}
  37079. * @default true
  37080. */
  37081. this.cameraAutoUpdate = true;
  37082. /**
  37083. * The renderer.
  37084. *
  37085. * @private
  37086. * @type {Renderer}
  37087. */
  37088. this._renderer = renderer;
  37089. // camera
  37090. /**
  37091. * Represents the camera for the left eye.
  37092. *
  37093. * @private
  37094. * @type {PerspectiveCamera}
  37095. */
  37096. this._cameraL = new PerspectiveCamera();
  37097. this._cameraL.viewport = new Vector4();
  37098. /**
  37099. * Represents the camera for the right eye.
  37100. *
  37101. * @private
  37102. * @type {PerspectiveCamera}
  37103. */
  37104. this._cameraR = new PerspectiveCamera();
  37105. this._cameraR.viewport = new Vector4();
  37106. /**
  37107. * A list of cameras used for rendering the XR views.
  37108. *
  37109. * @private
  37110. * @type {Array<Camera>}
  37111. */
  37112. this._cameras = [ this._cameraL, this._cameraR ];
  37113. /**
  37114. * The main XR camera.
  37115. *
  37116. * @private
  37117. * @type {ArrayCamera}
  37118. */
  37119. this._cameraXR = new ArrayCamera();
  37120. /**
  37121. * The current near value of the XR camera.
  37122. *
  37123. * @private
  37124. * @type {?number}
  37125. * @default null
  37126. */
  37127. this._currentDepthNear = null;
  37128. /**
  37129. * The current far value of the XR camera.
  37130. *
  37131. * @private
  37132. * @type {?number}
  37133. * @default null
  37134. */
  37135. this._currentDepthFar = null;
  37136. /**
  37137. * A list of WebXR controllers requested by the application.
  37138. *
  37139. * @private
  37140. * @type {Array<WebXRController>}
  37141. */
  37142. this._controllers = [];
  37143. /**
  37144. * A list of XR input source. Each input source belongs to
  37145. * an instance of WebXRController.
  37146. *
  37147. * @private
  37148. * @type {Array<XRInputSource?>}
  37149. */
  37150. this._controllerInputSources = [];
  37151. /**
  37152. * The XR render target that represents the rendering destination
  37153. * during an active XR session.
  37154. *
  37155. * @private
  37156. * @type {?RenderTarget}
  37157. * @default null
  37158. */
  37159. this._xrRenderTarget = null;
  37160. /**
  37161. * An array holding all the non-projection layers
  37162. *
  37163. * @private
  37164. * @type {Array<Object>}
  37165. * @default []
  37166. */
  37167. this._layers = [];
  37168. /**
  37169. * Whether the device has support for all layer types.
  37170. *
  37171. * @type {boolean}
  37172. * @default false
  37173. */
  37174. this._supportsLayers = false;
  37175. /**
  37176. * Whether the device supports binding gl objects.
  37177. *
  37178. * @private
  37179. * @type {boolean}
  37180. * @readonly
  37181. */
  37182. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  37183. this._frameBufferTargets = null;
  37184. /**
  37185. * Helper function to create native WebXR Layer.
  37186. *
  37187. * @private
  37188. * @type {Function}
  37189. */
  37190. this._createXRLayer = createXRLayer.bind( this );
  37191. /**
  37192. * The current WebGL context.
  37193. *
  37194. * @private
  37195. * @type {?WebGL2RenderingContext}
  37196. * @default null
  37197. */
  37198. this._gl = null;
  37199. /**
  37200. * The current animation context.
  37201. *
  37202. * @private
  37203. * @type {?Window}
  37204. * @default null
  37205. */
  37206. this._currentAnimationContext = null;
  37207. /**
  37208. * The current animation loop.
  37209. *
  37210. * @private
  37211. * @type {?Function}
  37212. * @default null
  37213. */
  37214. this._currentAnimationLoop = null;
  37215. /**
  37216. * The current pixel ratio.
  37217. *
  37218. * @private
  37219. * @type {?number}
  37220. * @default null
  37221. */
  37222. this._currentPixelRatio = null;
  37223. /**
  37224. * The current size of the renderer's canvas
  37225. * in logical pixel unit.
  37226. *
  37227. * @private
  37228. * @type {Vector2}
  37229. */
  37230. this._currentSize = new Vector2();
  37231. /**
  37232. * The default event listener for handling events inside a XR session.
  37233. *
  37234. * @private
  37235. * @type {Function}
  37236. */
  37237. this._onSessionEvent = onSessionEvent.bind( this );
  37238. /**
  37239. * The event listener for handling the end of a XR session.
  37240. *
  37241. * @private
  37242. * @type {Function}
  37243. */
  37244. this._onSessionEnd = onSessionEnd.bind( this );
  37245. /**
  37246. * The event listener for handling the `inputsourceschange` event.
  37247. *
  37248. * @private
  37249. * @type {Function}
  37250. */
  37251. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  37252. /**
  37253. * The animation loop which is used as a replacement for the default
  37254. * animation loop of the application. It is only used when a XR session
  37255. * is active.
  37256. *
  37257. * @private
  37258. * @type {Function}
  37259. */
  37260. this._onAnimationFrame = onAnimationFrame.bind( this );
  37261. /**
  37262. * The current XR reference space.
  37263. *
  37264. * @private
  37265. * @type {?XRReferenceSpace}
  37266. * @default null
  37267. */
  37268. this._referenceSpace = null;
  37269. /**
  37270. * The current XR reference space type.
  37271. *
  37272. * @private
  37273. * @type {XRReferenceSpaceType}
  37274. * @default 'local-floor'
  37275. */
  37276. this._referenceSpaceType = 'local-floor';
  37277. /**
  37278. * A custom reference space defined by the application.
  37279. *
  37280. * @private
  37281. * @type {?XRReferenceSpace}
  37282. * @default null
  37283. */
  37284. this._customReferenceSpace = null;
  37285. /**
  37286. * The framebuffer scale factor.
  37287. *
  37288. * @private
  37289. * @type {number}
  37290. * @default 1
  37291. */
  37292. this._framebufferScaleFactor = 1;
  37293. /**
  37294. * The foveation factor.
  37295. *
  37296. * @private
  37297. * @type {number}
  37298. * @default 1
  37299. */
  37300. this._foveation = 1.0;
  37301. /**
  37302. * A reference to the current XR session.
  37303. *
  37304. * @private
  37305. * @type {?XRSession}
  37306. * @default null
  37307. */
  37308. this._session = null;
  37309. /**
  37310. * A reference to the current XR base layer.
  37311. *
  37312. * @private
  37313. * @type {?XRWebGLLayer}
  37314. * @default null
  37315. */
  37316. this._glBaseLayer = null;
  37317. /**
  37318. * A reference to the current XR binding.
  37319. *
  37320. * @private
  37321. * @type {?XRWebGLBinding}
  37322. * @default null
  37323. */
  37324. this._glBinding = null;
  37325. /**
  37326. * A reference to the current XR projection layer.
  37327. *
  37328. * @private
  37329. * @type {?XRProjectionLayer}
  37330. * @default null
  37331. */
  37332. this._glProjLayer = null;
  37333. /**
  37334. * A reference to the current XR frame.
  37335. *
  37336. * @private
  37337. * @type {?XRFrame}
  37338. * @default null
  37339. */
  37340. this._xrFrame = null;
  37341. /**
  37342. * Whether to use the WebXR Layers API or not.
  37343. *
  37344. * @private
  37345. * @type {boolean}
  37346. * @readonly
  37347. */
  37348. this._useLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  37349. /**
  37350. * Whether the usage of multiview has been requested by the application or not.
  37351. *
  37352. * @private
  37353. * @type {boolean}
  37354. * @default false
  37355. * @readonly
  37356. */
  37357. this._useMultiviewIfPossible = multiview;
  37358. /**
  37359. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  37360. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  37361. *
  37362. * @private
  37363. * @type {boolean}
  37364. * @readonly
  37365. */
  37366. this._useMultiview = false;
  37367. }
  37368. /**
  37369. * Returns an instance of `THREE.Group` that represents the transformation
  37370. * of a XR controller in target ray space. The requested controller is defined
  37371. * by the given index.
  37372. *
  37373. * @param {number} index - The index of the XR controller.
  37374. * @return {Group} A group that represents the controller's transformation.
  37375. */
  37376. getController( index ) {
  37377. const controller = this._getController( index );
  37378. return controller.getTargetRaySpace();
  37379. }
  37380. /**
  37381. * Returns an instance of `THREE.Group` that represents the transformation
  37382. * of a XR controller in grip space. The requested controller is defined
  37383. * by the given index.
  37384. *
  37385. * @param {number} index - The index of the XR controller.
  37386. * @return {Group} A group that represents the controller's transformation.
  37387. */
  37388. getControllerGrip( index ) {
  37389. const controller = this._getController( index );
  37390. return controller.getGripSpace();
  37391. }
  37392. /**
  37393. * Returns an instance of `THREE.Group` that represents the transformation
  37394. * of a XR controller in hand space. The requested controller is defined
  37395. * by the given index.
  37396. *
  37397. * @param {number} index - The index of the XR controller.
  37398. * @return {Group} A group that represents the controller's transformation.
  37399. */
  37400. getHand( index ) {
  37401. const controller = this._getController( index );
  37402. return controller.getHandSpace();
  37403. }
  37404. /**
  37405. * Returns the foveation value.
  37406. *
  37407. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  37408. */
  37409. getFoveation() {
  37410. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  37411. return undefined;
  37412. }
  37413. return this._foveation;
  37414. }
  37415. /**
  37416. * Sets the foveation value.
  37417. *
  37418. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  37419. * and `1` means maximum foveation (the edges render at lower resolution).
  37420. */
  37421. setFoveation( foveation ) {
  37422. this._foveation = foveation;
  37423. if ( this._glProjLayer !== null ) {
  37424. this._glProjLayer.fixedFoveation = foveation;
  37425. }
  37426. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  37427. this._glBaseLayer.fixedFoveation = foveation;
  37428. }
  37429. }
  37430. /**
  37431. * Returns the framebuffer scale factor.
  37432. *
  37433. * @return {number} The framebuffer scale factor.
  37434. */
  37435. getFramebufferScaleFactor() {
  37436. return this._framebufferScaleFactor;
  37437. }
  37438. /**
  37439. * Sets the framebuffer scale factor.
  37440. *
  37441. * This method can not be used during a XR session.
  37442. *
  37443. * @param {number} factor - The framebuffer scale factor.
  37444. */
  37445. setFramebufferScaleFactor( factor ) {
  37446. this._framebufferScaleFactor = factor;
  37447. if ( this.isPresenting === true ) {
  37448. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  37449. }
  37450. }
  37451. /**
  37452. * Returns the reference space type.
  37453. *
  37454. * @return {XRReferenceSpaceType} The reference space type.
  37455. */
  37456. getReferenceSpaceType() {
  37457. return this._referenceSpaceType;
  37458. }
  37459. /**
  37460. * Sets the reference space type.
  37461. *
  37462. * This method can not be used during a XR session.
  37463. *
  37464. * @param {XRReferenceSpaceType} type - The reference space type.
  37465. */
  37466. setReferenceSpaceType( type ) {
  37467. this._referenceSpaceType = type;
  37468. if ( this.isPresenting === true ) {
  37469. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  37470. }
  37471. }
  37472. /**
  37473. * Returns the XR reference space.
  37474. *
  37475. * @return {XRReferenceSpace} The XR reference space.
  37476. */
  37477. getReferenceSpace() {
  37478. return this._customReferenceSpace || this._referenceSpace;
  37479. }
  37480. /**
  37481. * Sets a custom XR reference space.
  37482. *
  37483. * @param {XRReferenceSpace} space - The XR reference space.
  37484. */
  37485. setReferenceSpace( space ) {
  37486. this._customReferenceSpace = space;
  37487. }
  37488. /**
  37489. * Returns the XR camera.
  37490. *
  37491. * @return {ArrayCamera} The XR camera.
  37492. */
  37493. getCamera() {
  37494. return this._cameraXR;
  37495. }
  37496. /**
  37497. * Returns the environment blend mode from the current XR session.
  37498. *
  37499. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  37500. */
  37501. getEnvironmentBlendMode() {
  37502. if ( this._session !== null ) {
  37503. return this._session.environmentBlendMode;
  37504. }
  37505. }
  37506. /**
  37507. * Returns the current XR frame.
  37508. *
  37509. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  37510. */
  37511. getFrame() {
  37512. return this._xrFrame;
  37513. }
  37514. /**
  37515. * Returns `true` if the engine renders to a multiview target.
  37516. *
  37517. * @return {boolean} Whether the engine renders to a multiview render target or not.
  37518. */
  37519. useMultiview() {
  37520. return this._useMultiview;
  37521. }
  37522. /**
  37523. * This method can be used in XR applications to create a quadratic layer that presents a separate
  37524. * rendered scene.
  37525. *
  37526. * @param {number} width - The width of the layer plane in world units.
  37527. * @param {number} height - The height of the layer plane in world units.
  37528. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  37529. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  37530. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  37531. * @param {number} pixelheight - The height of the layer's render target in pixels.
  37532. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  37533. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  37534. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  37535. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  37536. */
  37537. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  37538. const geometry = new PlaneGeometry( width, height );
  37539. const renderTarget = new XRRenderTarget(
  37540. pixelwidth,
  37541. pixelheight,
  37542. {
  37543. format: RGBAFormat,
  37544. type: UnsignedByteType,
  37545. depthTexture: new DepthTexture(
  37546. pixelwidth,
  37547. pixelheight,
  37548. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  37549. undefined,
  37550. undefined,
  37551. undefined,
  37552. undefined,
  37553. undefined,
  37554. undefined,
  37555. attributes.stencil ? DepthStencilFormat : DepthFormat
  37556. ),
  37557. stencilBuffer: attributes.stencil,
  37558. resolveDepthBuffer: false,
  37559. resolveStencilBuffer: false
  37560. } );
  37561. renderTarget._autoAllocateDepthBuffer = true;
  37562. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  37563. material.map = renderTarget.texture;
  37564. material.map.offset.y = 1;
  37565. material.map.repeat.y = -1;
  37566. const plane = new Mesh( geometry, material );
  37567. plane.position.copy( translation );
  37568. plane.quaternion.copy( quaternion );
  37569. const layer = {
  37570. type: 'quad',
  37571. width: width,
  37572. height: height,
  37573. translation: translation,
  37574. quaternion: quaternion,
  37575. pixelwidth: pixelwidth,
  37576. pixelheight: pixelheight,
  37577. plane: plane,
  37578. material: material,
  37579. rendercall: rendercall,
  37580. renderTarget: renderTarget };
  37581. this._layers.push( layer );
  37582. if ( this._session !== null ) {
  37583. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  37584. layer.plane.material.blending = CustomBlending;
  37585. layer.plane.material.blendEquation = AddEquation;
  37586. layer.plane.material.blendSrc = ZeroFactor;
  37587. layer.plane.material.blendDst = ZeroFactor;
  37588. layer.xrlayer = this._createXRLayer( layer );
  37589. const xrlayers = this._session.renderState.layers;
  37590. xrlayers.unshift( layer.xrlayer );
  37591. this._session.updateRenderState( { layers: xrlayers } );
  37592. } else {
  37593. renderTarget.isXRRenderTarget = false;
  37594. }
  37595. return plane;
  37596. }
  37597. /**
  37598. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  37599. * rendered scene.
  37600. *
  37601. * @param {number} radius - The radius of the cylinder in world units.
  37602. * @param {number} centralAngle - The central angle of the cylinder in radians.
  37603. * @param {number} aspectratio - The aspect ratio.
  37604. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  37605. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  37606. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  37607. * @param {number} pixelheight - The height of the layer's render target in pixels.
  37608. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  37609. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  37610. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  37611. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  37612. */
  37613. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  37614. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  37615. const renderTarget = new XRRenderTarget(
  37616. pixelwidth,
  37617. pixelheight,
  37618. {
  37619. format: RGBAFormat,
  37620. type: UnsignedByteType,
  37621. depthTexture: new DepthTexture(
  37622. pixelwidth,
  37623. pixelheight,
  37624. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  37625. undefined,
  37626. undefined,
  37627. undefined,
  37628. undefined,
  37629. undefined,
  37630. undefined,
  37631. attributes.stencil ? DepthStencilFormat : DepthFormat
  37632. ),
  37633. stencilBuffer: attributes.stencil,
  37634. resolveDepthBuffer: false,
  37635. resolveStencilBuffer: false
  37636. } );
  37637. renderTarget._autoAllocateDepthBuffer = true;
  37638. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  37639. material.map = renderTarget.texture;
  37640. material.map.offset.y = 1;
  37641. material.map.repeat.y = -1;
  37642. const plane = new Mesh( geometry, material );
  37643. plane.position.copy( translation );
  37644. plane.quaternion.copy( quaternion );
  37645. const layer = {
  37646. type: 'cylinder',
  37647. radius: radius,
  37648. centralAngle: centralAngle,
  37649. aspectratio: aspectratio,
  37650. translation: translation,
  37651. quaternion: quaternion,
  37652. pixelwidth: pixelwidth,
  37653. pixelheight: pixelheight,
  37654. plane: plane,
  37655. material: material,
  37656. rendercall: rendercall,
  37657. renderTarget: renderTarget };
  37658. this._layers.push( layer );
  37659. if ( this._session !== null ) {
  37660. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  37661. layer.plane.material.blending = CustomBlending;
  37662. layer.plane.material.blendEquation = AddEquation;
  37663. layer.plane.material.blendSrc = ZeroFactor;
  37664. layer.plane.material.blendDst = ZeroFactor;
  37665. layer.xrlayer = this._createXRLayer( layer );
  37666. const xrlayers = this._session.renderState.layers;
  37667. xrlayers.unshift( layer.xrlayer );
  37668. this._session.updateRenderState( { layers: xrlayers } );
  37669. } else {
  37670. renderTarget.isXRRenderTarget = false;
  37671. }
  37672. return plane;
  37673. }
  37674. /**
  37675. * Renders the XR layers that have been previously added to the scene.
  37676. *
  37677. * This method is usually called in your animation loop before rendering
  37678. * the actual scene via `renderer.render( scene, camera );`.
  37679. */
  37680. renderLayers( ) {
  37681. const translationObject = new Vector3();
  37682. const quaternionObject = new Quaternion();
  37683. const renderer = this._renderer;
  37684. const wasPresenting = this.isPresenting;
  37685. const rendererOutputTarget = renderer.getOutputRenderTarget();
  37686. const rendererFramebufferTarget = renderer._frameBufferTarget;
  37687. this.isPresenting = false;
  37688. const rendererSize = new Vector2();
  37689. renderer.getSize( rendererSize );
  37690. const rendererQuad = renderer._quad;
  37691. for ( const layer of this._layers ) {
  37692. layer.renderTarget.isXRRenderTarget = this._session !== null;
  37693. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  37694. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  37695. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  37696. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  37697. renderer.backend.setXRRenderTargetTextures(
  37698. layer.renderTarget,
  37699. glSubImage.colorTexture,
  37700. undefined );
  37701. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  37702. renderer.setOutputRenderTarget( layer.renderTarget );
  37703. renderer.setRenderTarget( null );
  37704. renderer._frameBufferTarget = null;
  37705. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  37706. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  37707. if ( ! frameBufferTarget ) {
  37708. renderer._quad = new QuadMesh( new NodeMaterial() );
  37709. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  37710. } else {
  37711. renderer._frameBufferTarget = frameBufferTarget;
  37712. renderer._quad = quad;
  37713. }
  37714. layer.rendercall();
  37715. renderer._frameBufferTarget = null;
  37716. } else {
  37717. renderer.setRenderTarget( layer.renderTarget );
  37718. layer.rendercall();
  37719. }
  37720. }
  37721. renderer.setRenderTarget( null );
  37722. renderer.setOutputRenderTarget( rendererOutputTarget );
  37723. renderer._frameBufferTarget = rendererFramebufferTarget;
  37724. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  37725. renderer._quad = rendererQuad;
  37726. this.isPresenting = wasPresenting;
  37727. }
  37728. /**
  37729. * Returns the current XR session.
  37730. *
  37731. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  37732. */
  37733. getSession() {
  37734. return this._session;
  37735. }
  37736. /**
  37737. * After a XR session has been requested usually with one of the `*Button` modules, it
  37738. * is injected into the renderer with this method. This method triggers the start of
  37739. * the actual XR rendering.
  37740. *
  37741. * @async
  37742. * @param {XRSession} session - The XR session to set.
  37743. * @return {Promise} A Promise that resolves when the session has been set.
  37744. */
  37745. async setSession( session ) {
  37746. const renderer = this._renderer;
  37747. const backend = renderer.backend;
  37748. this._gl = renderer.getContext();
  37749. const gl = this._gl;
  37750. const attributes = gl.getContextAttributes();
  37751. this._session = session;
  37752. if ( session !== null ) {
  37753. 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.' );
  37754. session.addEventListener( 'select', this._onSessionEvent );
  37755. session.addEventListener( 'selectstart', this._onSessionEvent );
  37756. session.addEventListener( 'selectend', this._onSessionEvent );
  37757. session.addEventListener( 'squeeze', this._onSessionEvent );
  37758. session.addEventListener( 'squeezestart', this._onSessionEvent );
  37759. session.addEventListener( 'squeezeend', this._onSessionEvent );
  37760. session.addEventListener( 'end', this._onSessionEnd );
  37761. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  37762. await backend.makeXRCompatible();
  37763. this._currentPixelRatio = renderer.getPixelRatio();
  37764. renderer.getSize( this._currentSize );
  37765. this._currentAnimationContext = renderer._animation.getContext();
  37766. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  37767. renderer._animation.stop();
  37768. //
  37769. if ( this._supportsGlBinding ) {
  37770. const glBinding = new XRWebGLBinding( session, gl );
  37771. this._glBinding = glBinding;
  37772. }
  37773. //
  37774. if ( this._useLayers === true ) {
  37775. // default path using XRProjectionLayer
  37776. let depthFormat = null;
  37777. let depthType = null;
  37778. let glDepthFormat = null;
  37779. if ( renderer.depth ) {
  37780. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  37781. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  37782. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  37783. }
  37784. const projectionlayerInit = {
  37785. colorFormat: gl.RGBA8,
  37786. depthFormat: glDepthFormat,
  37787. scaleFactor: this._framebufferScaleFactor,
  37788. clearOnAccess: false
  37789. };
  37790. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  37791. projectionlayerInit.textureType = 'texture-array';
  37792. this._useMultiview = true;
  37793. }
  37794. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  37795. const layersArray = [ glProjLayer ];
  37796. this._glProjLayer = glProjLayer;
  37797. renderer.setPixelRatio( 1 );
  37798. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  37799. const depth = this._useMultiview ? 2 : 1;
  37800. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  37801. this._xrRenderTarget = new XRRenderTarget(
  37802. glProjLayer.textureWidth,
  37803. glProjLayer.textureHeight,
  37804. {
  37805. format: RGBAFormat,
  37806. type: UnsignedByteType,
  37807. colorSpace: renderer.outputColorSpace,
  37808. depthTexture: depthTexture,
  37809. stencilBuffer: renderer.stencil,
  37810. samples: attributes.antialias ? 4 : 0,
  37811. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  37812. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  37813. depth: this._useMultiview ? 2 : 1,
  37814. multiview: this._useMultiview
  37815. } );
  37816. this._xrRenderTarget._hasExternalTextures = true;
  37817. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  37818. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  37819. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  37820. if ( this._supportsLayers ) {
  37821. // switch layers to native
  37822. for ( const layer of this._layers ) {
  37823. // change material so it "punches" out a hole to show the XR Layer.
  37824. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  37825. layer.plane.material.blending = CustomBlending;
  37826. layer.plane.material.blendEquation = AddEquation;
  37827. layer.plane.material.blendSrc = ZeroFactor;
  37828. layer.plane.material.blendDst = ZeroFactor;
  37829. layer.xrlayer = this._createXRLayer( layer );
  37830. layersArray.unshift( layer.xrlayer );
  37831. }
  37832. }
  37833. session.updateRenderState( { layers: layersArray } );
  37834. } else {
  37835. // fallback to XRWebGLLayer
  37836. const layerInit = {
  37837. antialias: renderer.samples > 0,
  37838. alpha: true,
  37839. depth: renderer.depth,
  37840. stencil: renderer.stencil,
  37841. framebufferScaleFactor: this.getFramebufferScaleFactor()
  37842. };
  37843. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  37844. this._glBaseLayer = glBaseLayer;
  37845. session.updateRenderState( { baseLayer: glBaseLayer } );
  37846. renderer.setPixelRatio( 1 );
  37847. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  37848. this._xrRenderTarget = new XRRenderTarget(
  37849. glBaseLayer.framebufferWidth,
  37850. glBaseLayer.framebufferHeight,
  37851. {
  37852. format: RGBAFormat,
  37853. type: UnsignedByteType,
  37854. colorSpace: renderer.outputColorSpace,
  37855. stencilBuffer: renderer.stencil,
  37856. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  37857. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  37858. }
  37859. );
  37860. this._xrRenderTarget._isOpaqueFramebuffer = true;
  37861. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  37862. }
  37863. //
  37864. this.setFoveation( this.getFoveation() );
  37865. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  37866. renderer._animation.setContext( session );
  37867. renderer._animation.start();
  37868. this.isPresenting = true;
  37869. this.dispatchEvent( { type: 'sessionstart' } );
  37870. }
  37871. }
  37872. /**
  37873. * This method is called by the renderer per frame and updates the XR camera
  37874. * and it sub cameras based on the given camera. The given camera is the "user"
  37875. * camera created on application level and used for non-XR rendering.
  37876. *
  37877. * @param {PerspectiveCamera} camera - The camera.
  37878. */
  37879. updateCamera( camera ) {
  37880. const session = this._session;
  37881. if ( session === null ) return;
  37882. const depthNear = camera.near;
  37883. const depthFar = camera.far;
  37884. const cameraXR = this._cameraXR;
  37885. const cameraL = this._cameraL;
  37886. const cameraR = this._cameraR;
  37887. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  37888. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  37889. cameraXR.isMultiViewCamera = this._useMultiview;
  37890. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  37891. // Note that the new renderState won't apply until the next frame. See #18320
  37892. session.updateRenderState( {
  37893. depthNear: cameraXR.near,
  37894. depthFar: cameraXR.far
  37895. } );
  37896. this._currentDepthNear = cameraXR.near;
  37897. this._currentDepthFar = cameraXR.far;
  37898. }
  37899. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  37900. cameraXR.layers.mask = camera.layers.mask | 0b110;
  37901. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  37902. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  37903. const parent = camera.parent;
  37904. const cameras = cameraXR.cameras;
  37905. updateCamera( cameraXR, parent );
  37906. for ( let i = 0; i < cameras.length; i ++ ) {
  37907. updateCamera( cameras[ i ], parent );
  37908. }
  37909. // update projection matrix for proper view frustum culling
  37910. if ( cameras.length === 2 ) {
  37911. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  37912. } else {
  37913. // assume single camera setup (AR)
  37914. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  37915. }
  37916. // update user camera and its children
  37917. updateUserCamera( camera, cameraXR, parent );
  37918. }
  37919. /**
  37920. * Returns a WebXR controller for the given controller index.
  37921. *
  37922. * @private
  37923. * @param {number} index - The controller index.
  37924. * @return {WebXRController} The XR controller.
  37925. */
  37926. _getController( index ) {
  37927. let controller = this._controllers[ index ];
  37928. if ( controller === undefined ) {
  37929. controller = new WebXRController();
  37930. this._controllers[ index ] = controller;
  37931. }
  37932. return controller;
  37933. }
  37934. }
  37935. /**
  37936. * Assumes 2 cameras that are parallel and share an X-axis, and that
  37937. * the cameras' projection and world matrices have already been set.
  37938. * And that near and far planes are identical for both cameras.
  37939. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  37940. *
  37941. * @param {ArrayCamera} camera - The camera to update.
  37942. * @param {PerspectiveCamera} cameraL - The left camera.
  37943. * @param {PerspectiveCamera} cameraR - The right camera.
  37944. */
  37945. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  37946. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  37947. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  37948. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  37949. const projL = cameraL.projectionMatrix.elements;
  37950. const projR = cameraR.projectionMatrix.elements;
  37951. // VR systems will have identical far and near planes, and
  37952. // most likely identical top and bottom frustum extents.
  37953. // Use the left camera for these values.
  37954. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  37955. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  37956. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  37957. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  37958. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  37959. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  37960. const left = near * leftFov;
  37961. const right = near * rightFov;
  37962. // Calculate the new camera's position offset from the
  37963. // left camera. xOffset should be roughly half `ipd`.
  37964. const zOffset = ipd / ( - leftFov + rightFov );
  37965. const xOffset = zOffset * - leftFov;
  37966. // TODO: Better way to apply this offset?
  37967. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  37968. camera.translateX( xOffset );
  37969. camera.translateZ( zOffset );
  37970. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  37971. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  37972. // Check if the projection uses an infinite far plane.
  37973. if ( projL[ 10 ] === -1 ) {
  37974. // Use the projection matrix from the left eye.
  37975. // The camera offset is sufficient to include the view volumes
  37976. // of both eyes (assuming symmetric projections).
  37977. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  37978. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  37979. } else {
  37980. // Find the union of the frustum values of the cameras and scale
  37981. // the values so that the near plane's position does not change in world space,
  37982. // although must now be relative to the new union camera.
  37983. const near2 = near + zOffset;
  37984. const far2 = far + zOffset;
  37985. const left2 = left - xOffset;
  37986. const right2 = right + ( ipd - xOffset );
  37987. const top2 = topFov * far / far2 * near2;
  37988. const bottom2 = bottomFov * far / far2 * near2;
  37989. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  37990. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  37991. }
  37992. }
  37993. /**
  37994. * Updates the world matrices for the given camera based on the parent 3D object.
  37995. *
  37996. * @inner
  37997. * @param {Camera} camera - The camera to update.
  37998. * @param {Object3D} parent - The parent 3D object.
  37999. */
  38000. function updateCamera( camera, parent ) {
  38001. if ( parent === null ) {
  38002. camera.matrixWorld.copy( camera.matrix );
  38003. } else {
  38004. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  38005. }
  38006. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38007. }
  38008. /**
  38009. * Updates the given camera with the transformation of the XR camera and parent object.
  38010. *
  38011. * @inner
  38012. * @param {Camera} camera - The camera to update.
  38013. * @param {ArrayCamera} cameraXR - The XR camera.
  38014. * @param {Object3D} parent - The parent 3D object.
  38015. */
  38016. function updateUserCamera( camera, cameraXR, parent ) {
  38017. if ( parent === null ) {
  38018. camera.matrix.copy( cameraXR.matrixWorld );
  38019. } else {
  38020. camera.matrix.copy( parent.matrixWorld );
  38021. camera.matrix.invert();
  38022. camera.matrix.multiply( cameraXR.matrixWorld );
  38023. }
  38024. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38025. camera.updateMatrixWorld( true );
  38026. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  38027. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  38028. if ( camera.isPerspectiveCamera ) {
  38029. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  38030. camera.zoom = 1;
  38031. }
  38032. }
  38033. function onSessionEvent( event ) {
  38034. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  38035. if ( controllerIndex === -1 ) {
  38036. return;
  38037. }
  38038. const controller = this._controllers[ controllerIndex ];
  38039. if ( controller !== undefined ) {
  38040. const referenceSpace = this.getReferenceSpace();
  38041. controller.update( event.inputSource, event.frame, referenceSpace );
  38042. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  38043. }
  38044. }
  38045. function onSessionEnd() {
  38046. const session = this._session;
  38047. const renderer = this._renderer;
  38048. session.removeEventListener( 'select', this._onSessionEvent );
  38049. session.removeEventListener( 'selectstart', this._onSessionEvent );
  38050. session.removeEventListener( 'selectend', this._onSessionEvent );
  38051. session.removeEventListener( 'squeeze', this._onSessionEvent );
  38052. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  38053. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  38054. session.removeEventListener( 'end', this._onSessionEnd );
  38055. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38056. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38057. const inputSource = this._controllerInputSources[ i ];
  38058. if ( inputSource === null ) continue;
  38059. this._controllerInputSources[ i ] = null;
  38060. this._controllers[ i ].disconnect( inputSource );
  38061. }
  38062. this._currentDepthNear = null;
  38063. this._currentDepthFar = null;
  38064. // restore framebuffer/rendering state
  38065. renderer._resetXRState();
  38066. this._session = null;
  38067. this._xrRenderTarget = null;
  38068. // switch layers back to emulated
  38069. if ( this._supportsLayers === true ) {
  38070. for ( const layer of this._layers ) {
  38071. // Recreate layer render target to reset state
  38072. layer.renderTarget = new XRRenderTarget(
  38073. layer.pixelwidth,
  38074. layer.pixelheight,
  38075. {
  38076. format: RGBAFormat,
  38077. type: UnsignedByteType,
  38078. depthTexture: new DepthTexture(
  38079. layer.pixelwidth,
  38080. layer.pixelheight,
  38081. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  38082. undefined,
  38083. undefined,
  38084. undefined,
  38085. undefined,
  38086. undefined,
  38087. undefined,
  38088. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  38089. ),
  38090. stencilBuffer: layer.stencilBuffer,
  38091. resolveDepthBuffer: false,
  38092. resolveStencilBuffer: false
  38093. } );
  38094. layer.renderTarget.isXRRenderTarget = false;
  38095. layer.plane.material = layer.material;
  38096. layer.material.map = layer.renderTarget.texture;
  38097. layer.material.map.offset.y = 1;
  38098. layer.material.map.repeat.y = -1;
  38099. delete layer.xrlayer;
  38100. }
  38101. }
  38102. //
  38103. this.isPresenting = false;
  38104. this._useMultiview = false;
  38105. renderer._animation.stop();
  38106. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  38107. renderer._animation.setContext( this._currentAnimationContext );
  38108. renderer._animation.start();
  38109. renderer.setPixelRatio( this._currentPixelRatio );
  38110. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  38111. this.dispatchEvent( { type: 'sessionend' } );
  38112. }
  38113. function onInputSourcesChange( event ) {
  38114. const controllers = this._controllers;
  38115. const controllerInputSources = this._controllerInputSources;
  38116. // Notify disconnected
  38117. for ( let i = 0; i < event.removed.length; i ++ ) {
  38118. const inputSource = event.removed[ i ];
  38119. const index = controllerInputSources.indexOf( inputSource );
  38120. if ( index >= 0 ) {
  38121. controllerInputSources[ index ] = null;
  38122. controllers[ index ].disconnect( inputSource );
  38123. }
  38124. }
  38125. // Notify connected
  38126. for ( let i = 0; i < event.added.length; i ++ ) {
  38127. const inputSource = event.added[ i ];
  38128. let controllerIndex = controllerInputSources.indexOf( inputSource );
  38129. if ( controllerIndex === -1 ) {
  38130. // Assign input source a controller that currently has no input source
  38131. for ( let i = 0; i < controllers.length; i ++ ) {
  38132. if ( i >= controllerInputSources.length ) {
  38133. controllerInputSources.push( inputSource );
  38134. controllerIndex = i;
  38135. break;
  38136. } else if ( controllerInputSources[ i ] === null ) {
  38137. controllerInputSources[ i ] = inputSource;
  38138. controllerIndex = i;
  38139. break;
  38140. }
  38141. }
  38142. // If all controllers do currently receive input we ignore new ones
  38143. if ( controllerIndex === -1 ) break;
  38144. }
  38145. const controller = controllers[ controllerIndex ];
  38146. if ( controller ) {
  38147. controller.connect( inputSource );
  38148. }
  38149. }
  38150. }
  38151. // Creation method for native WebXR layers
  38152. function createXRLayer( layer ) {
  38153. if ( layer.type === 'quad' ) {
  38154. return this._glBinding.createQuadLayer( {
  38155. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38156. width: layer.width / 2,
  38157. height: layer.height / 2,
  38158. space: this._referenceSpace,
  38159. viewPixelWidth: layer.pixelwidth,
  38160. viewPixelHeight: layer.pixelheight,
  38161. clearOnAccess: false
  38162. } );
  38163. } else {
  38164. return this._glBinding.createCylinderLayer( {
  38165. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38166. radius: layer.radius,
  38167. centralAngle: layer.centralAngle,
  38168. aspectRatio: layer.aspectRatio,
  38169. space: this._referenceSpace,
  38170. viewPixelWidth: layer.pixelwidth,
  38171. viewPixelHeight: layer.pixelheight,
  38172. clearOnAccess: false
  38173. } );
  38174. }
  38175. }
  38176. // Animation Loop
  38177. function onAnimationFrame( time, frame ) {
  38178. if ( frame === undefined ) return;
  38179. const cameraXR = this._cameraXR;
  38180. const renderer = this._renderer;
  38181. const backend = renderer.backend;
  38182. const glBaseLayer = this._glBaseLayer;
  38183. const referenceSpace = this.getReferenceSpace();
  38184. const pose = frame.getViewerPose( referenceSpace );
  38185. this._xrFrame = frame;
  38186. if ( pose !== null ) {
  38187. const views = pose.views;
  38188. if ( this._glBaseLayer !== null ) {
  38189. backend.setXRTarget( glBaseLayer.framebuffer );
  38190. }
  38191. let cameraXRNeedsUpdate = false;
  38192. // check if it's necessary to rebuild cameraXR's camera list
  38193. if ( views.length !== cameraXR.cameras.length ) {
  38194. cameraXR.cameras.length = 0;
  38195. cameraXRNeedsUpdate = true;
  38196. }
  38197. for ( let i = 0; i < views.length; i ++ ) {
  38198. const view = views[ i ];
  38199. let viewport;
  38200. if ( this._useLayers === true ) {
  38201. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  38202. viewport = glSubImage.viewport;
  38203. // For side-by-side projection, we only produce a single texture for both eyes.
  38204. if ( i === 0 ) {
  38205. backend.setXRRenderTargetTextures(
  38206. this._xrRenderTarget,
  38207. glSubImage.colorTexture,
  38208. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  38209. );
  38210. }
  38211. } else {
  38212. viewport = glBaseLayer.getViewport( view );
  38213. }
  38214. let camera = this._cameras[ i ];
  38215. if ( camera === undefined ) {
  38216. camera = new PerspectiveCamera();
  38217. camera.layers.enable( i );
  38218. camera.viewport = new Vector4();
  38219. this._cameras[ i ] = camera;
  38220. }
  38221. camera.matrix.fromArray( view.transform.matrix );
  38222. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38223. camera.projectionMatrix.fromArray( view.projectionMatrix );
  38224. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38225. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  38226. if ( i === 0 ) {
  38227. cameraXR.matrix.copy( camera.matrix );
  38228. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  38229. }
  38230. if ( cameraXRNeedsUpdate === true ) {
  38231. cameraXR.cameras.push( camera );
  38232. }
  38233. }
  38234. renderer.setOutputRenderTarget( this._xrRenderTarget );
  38235. }
  38236. //
  38237. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38238. const inputSource = this._controllerInputSources[ i ];
  38239. const controller = this._controllers[ i ];
  38240. if ( inputSource !== null && controller !== undefined ) {
  38241. controller.update( inputSource, frame, referenceSpace );
  38242. }
  38243. }
  38244. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  38245. if ( frame.detectedPlanes ) {
  38246. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  38247. }
  38248. this._xrFrame = null;
  38249. }
  38250. const _scene = /*@__PURE__*/ new Scene();
  38251. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  38252. const _screen = /*@__PURE__*/ new Vector4();
  38253. const _frustum = /*@__PURE__*/ new Frustum();
  38254. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  38255. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  38256. const _vector4 = /*@__PURE__*/ new Vector4();
  38257. /**
  38258. * Base class for renderers.
  38259. */
  38260. class Renderer {
  38261. /**
  38262. * Renderer options.
  38263. *
  38264. * @typedef {Object} Renderer~Options
  38265. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  38266. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  38267. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  38268. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  38269. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  38270. * @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
  38271. * to overwrite the default.
  38272. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  38273. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  38274. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  38275. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  38276. */
  38277. /**
  38278. * Constructs a new renderer.
  38279. *
  38280. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  38281. * @param {Renderer~Options} [parameters] - The configuration parameter.
  38282. */
  38283. constructor( backend, parameters = {} ) {
  38284. /**
  38285. * This flag can be used for type testing.
  38286. *
  38287. * @type {boolean}
  38288. * @readonly
  38289. * @default true
  38290. */
  38291. this.isRenderer = true;
  38292. //
  38293. const {
  38294. logarithmicDepthBuffer = false,
  38295. alpha = true,
  38296. depth = true,
  38297. stencil = false,
  38298. antialias = false,
  38299. samples = 0,
  38300. getFallback = null,
  38301. colorBufferType = HalfFloatType,
  38302. multiview = false
  38303. } = parameters;
  38304. /**
  38305. * A reference to the canvas element the renderer is drawing to.
  38306. * This value of this property will automatically be created by
  38307. * the renderer.
  38308. *
  38309. * @type {HTMLCanvasElement|OffscreenCanvas}
  38310. */
  38311. this.domElement = backend.getDomElement();
  38312. /**
  38313. * A reference to the current backend.
  38314. *
  38315. * @type {Backend}
  38316. */
  38317. this.backend = backend;
  38318. /**
  38319. * The number of MSAA samples.
  38320. *
  38321. * @type {number}
  38322. * @default 0
  38323. */
  38324. this.samples = samples || ( antialias === true ) ? 4 : 0;
  38325. /**
  38326. * Whether the renderer should automatically clear the current rendering target
  38327. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  38328. * or the current bound render target (custom framebuffer).
  38329. *
  38330. * @type {boolean}
  38331. * @default true
  38332. */
  38333. this.autoClear = true;
  38334. /**
  38335. * When `autoClear` is set to `true`, this property defines whether the renderer
  38336. * should clear the color buffer.
  38337. *
  38338. * @type {boolean}
  38339. * @default true
  38340. */
  38341. this.autoClearColor = true;
  38342. /**
  38343. * When `autoClear` is set to `true`, this property defines whether the renderer
  38344. * should clear the depth buffer.
  38345. *
  38346. * @type {boolean}
  38347. * @default true
  38348. */
  38349. this.autoClearDepth = true;
  38350. /**
  38351. * When `autoClear` is set to `true`, this property defines whether the renderer
  38352. * should clear the stencil buffer.
  38353. *
  38354. * @type {boolean}
  38355. * @default true
  38356. */
  38357. this.autoClearStencil = true;
  38358. /**
  38359. * Whether the default framebuffer should be transparent or opaque.
  38360. *
  38361. * @type {boolean}
  38362. * @default true
  38363. */
  38364. this.alpha = alpha;
  38365. /**
  38366. * Whether logarithmic depth buffer is enabled or not.
  38367. *
  38368. * @type {boolean}
  38369. * @default false
  38370. */
  38371. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  38372. /**
  38373. * Defines the output color space of the renderer.
  38374. *
  38375. * @type {string}
  38376. * @default SRGBColorSpace
  38377. */
  38378. this.outputColorSpace = SRGBColorSpace;
  38379. /**
  38380. * Defines the tone mapping of the renderer.
  38381. *
  38382. * @type {number}
  38383. * @default NoToneMapping
  38384. */
  38385. this.toneMapping = NoToneMapping;
  38386. /**
  38387. * Defines the tone mapping exposure.
  38388. *
  38389. * @type {number}
  38390. * @default 1
  38391. */
  38392. this.toneMappingExposure = 1.0;
  38393. /**
  38394. * Whether the renderer should sort its render lists or not.
  38395. *
  38396. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  38397. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  38398. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  38399. * e.g. manually determining each object's rendering order.
  38400. *
  38401. * @type {boolean}
  38402. * @default true
  38403. */
  38404. this.sortObjects = true;
  38405. /**
  38406. * Whether the default framebuffer should have a depth buffer or not.
  38407. *
  38408. * @type {boolean}
  38409. * @default true
  38410. */
  38411. this.depth = depth;
  38412. /**
  38413. * Whether the default framebuffer should have a stencil buffer or not.
  38414. *
  38415. * @type {boolean}
  38416. * @default false
  38417. */
  38418. this.stencil = stencil;
  38419. /**
  38420. * Holds a series of statistical information about the GPU memory
  38421. * and the rendering process. Useful for debugging and monitoring.
  38422. *
  38423. * @type {Info}
  38424. */
  38425. this.info = new Info();
  38426. /**
  38427. * Stores override nodes for specific transformations or calculations.
  38428. * These nodes can be used to replace default behavior in the rendering pipeline.
  38429. *
  38430. * @type {Object}
  38431. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  38432. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  38433. */
  38434. this.overrideNodes = {
  38435. modelViewMatrix: null,
  38436. modelNormalViewMatrix: null
  38437. };
  38438. /**
  38439. * The node library defines how certain library objects like materials, lights
  38440. * or tone mapping functions are mapped to node types. This is required since
  38441. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  38442. * be part of the scene graph, they are internally represented as nodes for
  38443. * further processing.
  38444. *
  38445. * @type {NodeLibrary}
  38446. */
  38447. this.library = new NodeLibrary();
  38448. /**
  38449. * A map-like data structure for managing lights.
  38450. *
  38451. * @type {Lighting}
  38452. */
  38453. this.lighting = new Lighting();
  38454. // internals
  38455. /**
  38456. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  38457. *
  38458. * @private
  38459. * @type {?Function}
  38460. */
  38461. this._getFallback = getFallback;
  38462. /**
  38463. * The renderer's pixel ratio.
  38464. *
  38465. * @private
  38466. * @type {number}
  38467. * @default 1
  38468. */
  38469. this._pixelRatio = 1;
  38470. /**
  38471. * The width of the renderer's default framebuffer in logical pixel unit.
  38472. *
  38473. * @private
  38474. * @type {number}
  38475. */
  38476. this._width = this.domElement.width;
  38477. /**
  38478. * The height of the renderer's default framebuffer in logical pixel unit.
  38479. *
  38480. * @private
  38481. * @type {number}
  38482. */
  38483. this._height = this.domElement.height;
  38484. /**
  38485. * The viewport of the renderer in logical pixel unit.
  38486. *
  38487. * @private
  38488. * @type {Vector4}
  38489. */
  38490. this._viewport = new Vector4( 0, 0, this._width, this._height );
  38491. /**
  38492. * The scissor rectangle of the renderer in logical pixel unit.
  38493. *
  38494. * @private
  38495. * @type {Vector4}
  38496. */
  38497. this._scissor = new Vector4( 0, 0, this._width, this._height );
  38498. /**
  38499. * Whether the scissor test should be enabled or not.
  38500. *
  38501. * @private
  38502. * @type {boolean}
  38503. */
  38504. this._scissorTest = false;
  38505. /**
  38506. * A reference to a renderer module for managing shader attributes.
  38507. *
  38508. * @private
  38509. * @type {?Attributes}
  38510. * @default null
  38511. */
  38512. this._attributes = null;
  38513. /**
  38514. * A reference to a renderer module for managing geometries.
  38515. *
  38516. * @private
  38517. * @type {?Geometries}
  38518. * @default null
  38519. */
  38520. this._geometries = null;
  38521. /**
  38522. * A reference to a renderer module for managing node related logic.
  38523. *
  38524. * @private
  38525. * @type {?Nodes}
  38526. * @default null
  38527. */
  38528. this._nodes = null;
  38529. /**
  38530. * A reference to a renderer module for managing the internal animation loop.
  38531. *
  38532. * @private
  38533. * @type {?Animation}
  38534. * @default null
  38535. */
  38536. this._animation = null;
  38537. /**
  38538. * A reference to a renderer module for managing shader program bindings.
  38539. *
  38540. * @private
  38541. * @type {?Bindings}
  38542. * @default null
  38543. */
  38544. this._bindings = null;
  38545. /**
  38546. * A reference to a renderer module for managing render objects.
  38547. *
  38548. * @private
  38549. * @type {?RenderObjects}
  38550. * @default null
  38551. */
  38552. this._objects = null;
  38553. /**
  38554. * A reference to a renderer module for managing render and compute pipelines.
  38555. *
  38556. * @private
  38557. * @type {?Pipelines}
  38558. * @default null
  38559. */
  38560. this._pipelines = null;
  38561. /**
  38562. * A reference to a renderer module for managing render bundles.
  38563. *
  38564. * @private
  38565. * @type {?RenderBundles}
  38566. * @default null
  38567. */
  38568. this._bundles = null;
  38569. /**
  38570. * A reference to a renderer module for managing render lists.
  38571. *
  38572. * @private
  38573. * @type {?RenderLists}
  38574. * @default null
  38575. */
  38576. this._renderLists = null;
  38577. /**
  38578. * A reference to a renderer module for managing render contexts.
  38579. *
  38580. * @private
  38581. * @type {?RenderContexts}
  38582. * @default null
  38583. */
  38584. this._renderContexts = null;
  38585. /**
  38586. * A reference to a renderer module for managing textures.
  38587. *
  38588. * @private
  38589. * @type {?Textures}
  38590. * @default null
  38591. */
  38592. this._textures = null;
  38593. /**
  38594. * A reference to a renderer module for backgrounds.
  38595. *
  38596. * @private
  38597. * @type {?Background}
  38598. * @default null
  38599. */
  38600. this._background = null;
  38601. /**
  38602. * This fullscreen quad is used for internal render passes
  38603. * like the tone mapping and color space output pass.
  38604. *
  38605. * @private
  38606. * @type {QuadMesh}
  38607. */
  38608. this._quad = new QuadMesh( new NodeMaterial() );
  38609. this._quad.material.name = 'Renderer_output';
  38610. /**
  38611. * A reference to the current render context.
  38612. *
  38613. * @private
  38614. * @type {?RenderContext}
  38615. * @default null
  38616. */
  38617. this._currentRenderContext = null;
  38618. /**
  38619. * A custom sort function for the opaque render list.
  38620. *
  38621. * @private
  38622. * @type {?Function}
  38623. * @default null
  38624. */
  38625. this._opaqueSort = null;
  38626. /**
  38627. * A custom sort function for the transparent render list.
  38628. *
  38629. * @private
  38630. * @type {?Function}
  38631. * @default null
  38632. */
  38633. this._transparentSort = null;
  38634. /**
  38635. * The framebuffer target.
  38636. *
  38637. * @private
  38638. * @type {?RenderTarget}
  38639. * @default null
  38640. */
  38641. this._frameBufferTarget = null;
  38642. const alphaClear = this.alpha === true ? 0 : 1;
  38643. /**
  38644. * The clear color value.
  38645. *
  38646. * @private
  38647. * @type {Color4}
  38648. */
  38649. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  38650. /**
  38651. * The clear depth value.
  38652. *
  38653. * @private
  38654. * @type {number}
  38655. * @default 1
  38656. */
  38657. this._clearDepth = 1;
  38658. /**
  38659. * The clear stencil value.
  38660. *
  38661. * @private
  38662. * @type {number}
  38663. * @default 0
  38664. */
  38665. this._clearStencil = 0;
  38666. /**
  38667. * The current render target.
  38668. *
  38669. * @private
  38670. * @type {?RenderTarget}
  38671. * @default null
  38672. */
  38673. this._renderTarget = null;
  38674. /**
  38675. * The active cube face.
  38676. *
  38677. * @private
  38678. * @type {number}
  38679. * @default 0
  38680. */
  38681. this._activeCubeFace = 0;
  38682. /**
  38683. * The active mipmap level.
  38684. *
  38685. * @private
  38686. * @type {number}
  38687. * @default 0
  38688. */
  38689. this._activeMipmapLevel = 0;
  38690. /**
  38691. * The current output render target.
  38692. *
  38693. * @private
  38694. * @type {?RenderTarget}
  38695. * @default null
  38696. */
  38697. this._outputRenderTarget = null;
  38698. /**
  38699. * The MRT setting.
  38700. *
  38701. * @private
  38702. * @type {?MRTNode}
  38703. * @default null
  38704. */
  38705. this._mrt = null;
  38706. /**
  38707. * This function defines how a render object is going
  38708. * to be rendered.
  38709. *
  38710. * @private
  38711. * @type {?Function}
  38712. * @default null
  38713. */
  38714. this._renderObjectFunction = null;
  38715. /**
  38716. * Used to keep track of the current render object function.
  38717. *
  38718. * @private
  38719. * @type {?Function}
  38720. * @default null
  38721. */
  38722. this._currentRenderObjectFunction = null;
  38723. /**
  38724. * Used to keep track of the current render bundle.
  38725. *
  38726. * @private
  38727. * @type {?RenderBundle}
  38728. * @default null
  38729. */
  38730. this._currentRenderBundle = null;
  38731. /**
  38732. * Next to `_renderObjectFunction()`, this function provides another hook
  38733. * for influencing the render process of a render object. It is meant for internal
  38734. * use and only relevant for `compileAsync()` right now. Instead of using
  38735. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  38736. * a different function might be used which performs no draw but just the node
  38737. * and pipeline updates.
  38738. *
  38739. * @private
  38740. * @type {?Function}
  38741. * @default null
  38742. */
  38743. this._handleObjectFunction = this._renderObjectDirect;
  38744. /**
  38745. * Indicates whether the device has been lost or not. In WebGL terms, the device
  38746. * lost is considered as a context lost. When this is set to `true`, rendering
  38747. * isn't possible anymore.
  38748. *
  38749. * @private
  38750. * @type {boolean}
  38751. * @default false
  38752. */
  38753. this._isDeviceLost = false;
  38754. /**
  38755. * A callback function that defines what should happen when a device/context lost occurs.
  38756. *
  38757. * @type {Function}
  38758. */
  38759. this.onDeviceLost = this._onDeviceLost;
  38760. /**
  38761. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  38762. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  38763. * This will reduce rendering quality though.
  38764. *
  38765. * @private
  38766. * @type {number}
  38767. * @default HalfFloatType
  38768. */
  38769. this._colorBufferType = colorBufferType;
  38770. /**
  38771. * Whether the renderer has been initialized or not.
  38772. *
  38773. * @private
  38774. * @type {boolean}
  38775. * @default false
  38776. */
  38777. this._initialized = false;
  38778. /**
  38779. * A reference to the promise which initializes the renderer.
  38780. *
  38781. * @private
  38782. * @type {?Promise<this>}
  38783. * @default null
  38784. */
  38785. this._initPromise = null;
  38786. /**
  38787. * An array of compilation promises which are used in `compileAsync()`.
  38788. *
  38789. * @private
  38790. * @type {?Array<Promise>}
  38791. * @default null
  38792. */
  38793. this._compilationPromises = null;
  38794. /**
  38795. * Whether the renderer should render transparent render objects or not.
  38796. *
  38797. * @type {boolean}
  38798. * @default true
  38799. */
  38800. this.transparent = true;
  38801. /**
  38802. * Whether the renderer should render opaque render objects or not.
  38803. *
  38804. * @type {boolean}
  38805. * @default true
  38806. */
  38807. this.opaque = true;
  38808. /**
  38809. * Shadow map configuration
  38810. * @typedef {Object} ShadowMapConfig
  38811. * @property {boolean} enabled - Whether to globally enable shadows or not.
  38812. * @property {number} type - The shadow map type.
  38813. */
  38814. /**
  38815. * The renderer's shadow configuration.
  38816. *
  38817. * @type {ShadowMapConfig}
  38818. */
  38819. this.shadowMap = {
  38820. enabled: false,
  38821. type: PCFShadowMap
  38822. };
  38823. /**
  38824. * XR configuration.
  38825. * @typedef {Object} XRConfig
  38826. * @property {boolean} enabled - Whether to globally enable XR or not.
  38827. */
  38828. /**
  38829. * The renderer's XR manager.
  38830. *
  38831. * @type {XRManager}
  38832. */
  38833. this.xr = new XRManager( this, multiview );
  38834. /**
  38835. * Debug configuration.
  38836. * @typedef {Object} DebugConfig
  38837. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  38838. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  38839. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  38840. */
  38841. /**
  38842. * The renderer's debug configuration.
  38843. *
  38844. * @type {DebugConfig}
  38845. */
  38846. this.debug = {
  38847. checkShaderErrors: true,
  38848. onShaderError: null,
  38849. getShaderAsync: async ( scene, camera, object ) => {
  38850. await this.compileAsync( scene, camera );
  38851. const renderList = this._renderLists.get( scene, camera );
  38852. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  38853. const material = scene.overrideMaterial || object.material;
  38854. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  38855. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  38856. return { fragmentShader, vertexShader };
  38857. }
  38858. };
  38859. }
  38860. /**
  38861. * Initializes the renderer so it is ready for usage.
  38862. *
  38863. * @async
  38864. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  38865. */
  38866. async init() {
  38867. if ( this._initialized ) {
  38868. throw new Error( 'Renderer: Backend has already been initialized.' );
  38869. }
  38870. if ( this._initPromise !== null ) {
  38871. return this._initPromise;
  38872. }
  38873. this._initPromise = new Promise( async ( resolve, reject ) => {
  38874. let backend = this.backend;
  38875. try {
  38876. await backend.init( this );
  38877. } catch ( error ) {
  38878. if ( this._getFallback !== null ) {
  38879. // try the fallback
  38880. try {
  38881. this.backend = backend = this._getFallback( error );
  38882. await backend.init( this );
  38883. } catch ( error ) {
  38884. reject( error );
  38885. return;
  38886. }
  38887. } else {
  38888. reject( error );
  38889. return;
  38890. }
  38891. }
  38892. this._nodes = new Nodes( this, backend );
  38893. this._animation = new Animation( this._nodes, this.info );
  38894. this._attributes = new Attributes( backend );
  38895. this._background = new Background( this, this._nodes );
  38896. this._geometries = new Geometries( this._attributes, this.info );
  38897. this._textures = new Textures( this, backend, this.info );
  38898. this._pipelines = new Pipelines( backend, this._nodes );
  38899. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  38900. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  38901. this._renderLists = new RenderLists( this.lighting );
  38902. this._bundles = new RenderBundles();
  38903. this._renderContexts = new RenderContexts();
  38904. //
  38905. this._animation.start();
  38906. this._initialized = true;
  38907. resolve( this );
  38908. } );
  38909. return this._initPromise;
  38910. }
  38911. /**
  38912. * The coordinate system of the renderer. The value of this property
  38913. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  38914. * `THREE.WebGPUCoordinateSystem`.
  38915. *
  38916. * @readonly
  38917. * @type {number}
  38918. */
  38919. get coordinateSystem() {
  38920. return this.backend.coordinateSystem;
  38921. }
  38922. /**
  38923. * Compiles all materials in the given scene. This can be useful to avoid a
  38924. * phenomenon which is called "shader compilation stutter", which occurs when
  38925. * rendering an object with a new shader for the first time.
  38926. *
  38927. * If you want to add a 3D object to an existing scene, use the third optional
  38928. * parameter for applying the target scene. Note that the (target) scene's lighting
  38929. * and environment must be configured before calling this method.
  38930. *
  38931. * @async
  38932. * @param {Object3D} scene - The scene or 3D object to precompile.
  38933. * @param {Camera} camera - The camera that is used to render the scene.
  38934. * @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.
  38935. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  38936. */
  38937. async compileAsync( scene, camera, targetScene = null ) {
  38938. if ( this._isDeviceLost === true ) return;
  38939. if ( this._initialized === false ) await this.init();
  38940. // preserve render tree
  38941. const nodeFrame = this._nodes.nodeFrame;
  38942. const previousRenderId = nodeFrame.renderId;
  38943. const previousRenderContext = this._currentRenderContext;
  38944. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38945. const previousCompilationPromises = this._compilationPromises;
  38946. //
  38947. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38948. if ( targetScene === null ) targetScene = scene;
  38949. const renderTarget = this._renderTarget;
  38950. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  38951. const activeMipmapLevel = this._activeMipmapLevel;
  38952. const compilationPromises = [];
  38953. this._currentRenderContext = renderContext;
  38954. this._currentRenderObjectFunction = this.renderObject;
  38955. this._handleObjectFunction = this._createObjectPipeline;
  38956. this._compilationPromises = compilationPromises;
  38957. nodeFrame.renderId ++;
  38958. //
  38959. nodeFrame.update();
  38960. //
  38961. renderContext.depth = this.depth;
  38962. renderContext.stencil = this.stencil;
  38963. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38964. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  38965. //
  38966. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38967. //
  38968. const renderList = this._renderLists.get( scene, camera );
  38969. renderList.begin();
  38970. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  38971. // include lights from target scene
  38972. if ( targetScene !== scene ) {
  38973. targetScene.traverseVisible( function ( object ) {
  38974. if ( object.isLight && object.layers.test( camera.layers ) ) {
  38975. renderList.pushLight( object );
  38976. }
  38977. } );
  38978. }
  38979. renderList.finish();
  38980. //
  38981. if ( renderTarget !== null ) {
  38982. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38983. const renderTargetData = this._textures.get( renderTarget );
  38984. renderContext.textures = renderTargetData.textures;
  38985. renderContext.depthTexture = renderTargetData.depthTexture;
  38986. } else {
  38987. renderContext.textures = null;
  38988. renderContext.depthTexture = null;
  38989. }
  38990. //
  38991. this._background.update( sceneRef, renderList, renderContext );
  38992. // process render lists
  38993. const opaqueObjects = renderList.opaque;
  38994. const transparentObjects = renderList.transparent;
  38995. const transparentDoublePassObjects = renderList.transparentDoublePass;
  38996. const lightsNode = renderList.lightsNode;
  38997. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38998. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  38999. // restore render tree
  39000. nodeFrame.renderId = previousRenderId;
  39001. this._currentRenderContext = previousRenderContext;
  39002. this._currentRenderObjectFunction = previousRenderObjectFunction;
  39003. this._compilationPromises = previousCompilationPromises;
  39004. this._handleObjectFunction = this._renderObjectDirect;
  39005. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  39006. await Promise.all( compilationPromises );
  39007. }
  39008. /**
  39009. * Renders the scene in an async fashion.
  39010. *
  39011. * @async
  39012. * @param {Object3D} scene - The scene or 3D object to render.
  39013. * @param {Camera} camera - The camera.
  39014. * @return {Promise} A Promise that resolves when the render has been finished.
  39015. */
  39016. async renderAsync( scene, camera ) {
  39017. if ( this._initialized === false ) await this.init();
  39018. this._renderScene( scene, camera );
  39019. }
  39020. /**
  39021. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  39022. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  39023. *
  39024. * @async
  39025. * @return {Promise} A Promise that resolves when synchronization has been finished.
  39026. */
  39027. async waitForGPU() {
  39028. await this.backend.waitForGPU();
  39029. }
  39030. /**
  39031. * Enables or disables high precision for model-view and normal-view matrices.
  39032. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  39033. *
  39034. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  39035. *
  39036. * @param {boolean} value - Whether to enable or disable high precision.
  39037. * @type {boolean}
  39038. */
  39039. set highPrecision( value ) {
  39040. if ( value === true ) {
  39041. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  39042. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  39043. } else if ( this.highPrecision ) {
  39044. this.overrideNodes.modelViewMatrix = null;
  39045. this.overrideNodes.modelNormalViewMatrix = null;
  39046. }
  39047. }
  39048. /**
  39049. * Returns whether high precision is enabled or not.
  39050. *
  39051. * @return {boolean} Whether high precision is enabled or not.
  39052. * @type {boolean}
  39053. */
  39054. get highPrecision() {
  39055. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  39056. }
  39057. /**
  39058. * Sets the given MRT configuration.
  39059. *
  39060. * @param {MRTNode} mrt - The MRT node to set.
  39061. * @return {Renderer} A reference to this renderer.
  39062. */
  39063. setMRT( mrt ) {
  39064. this._mrt = mrt;
  39065. return this;
  39066. }
  39067. /**
  39068. * Returns the MRT configuration.
  39069. *
  39070. * @return {MRTNode} The MRT configuration.
  39071. */
  39072. getMRT() {
  39073. return this._mrt;
  39074. }
  39075. /**
  39076. * Returns the color buffer type.
  39077. *
  39078. * @return {number} The color buffer type.
  39079. */
  39080. getColorBufferType() {
  39081. return this._colorBufferType;
  39082. }
  39083. /**
  39084. * Default implementation of the device lost callback.
  39085. *
  39086. * @private
  39087. * @param {Object} info - Information about the context lost.
  39088. */
  39089. _onDeviceLost( info ) {
  39090. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  39091. if ( info.reason ) {
  39092. errorMessage += `\nReason: ${info.reason}`;
  39093. }
  39094. console.error( errorMessage );
  39095. this._isDeviceLost = true;
  39096. }
  39097. /**
  39098. * Renders the given render bundle.
  39099. *
  39100. * @private
  39101. * @param {Object} bundle - Render bundle data.
  39102. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  39103. * @param {LightsNode} lightsNode - The lights node.
  39104. */
  39105. _renderBundle( bundle, sceneRef, lightsNode ) {
  39106. const { bundleGroup, camera, renderList } = bundle;
  39107. const renderContext = this._currentRenderContext;
  39108. //
  39109. const renderBundle = this._bundles.get( bundleGroup, camera );
  39110. const renderBundleData = this.backend.get( renderBundle );
  39111. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  39112. //
  39113. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  39114. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  39115. renderBundleData.renderContexts.add( renderContext );
  39116. if ( renderBundleNeedsUpdate ) {
  39117. this.backend.beginBundle( renderContext );
  39118. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  39119. renderBundleData.renderObjects = [];
  39120. }
  39121. this._currentRenderBundle = renderBundle;
  39122. const {
  39123. transparentDoublePass: transparentDoublePassObjects,
  39124. transparent: transparentObjects,
  39125. opaque: opaqueObjects
  39126. } = renderList;
  39127. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39128. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39129. this._currentRenderBundle = null;
  39130. //
  39131. this.backend.finishBundle( renderContext, renderBundle );
  39132. renderBundleData.version = bundleGroup.version;
  39133. } else {
  39134. const { renderObjects } = renderBundleData;
  39135. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  39136. const renderObject = renderObjects[ i ];
  39137. if ( this._nodes.needsRefresh( renderObject ) ) {
  39138. this._nodes.updateBefore( renderObject );
  39139. this._nodes.updateForRender( renderObject );
  39140. this._bindings.updateForRender( renderObject );
  39141. this._nodes.updateAfter( renderObject );
  39142. }
  39143. }
  39144. }
  39145. this.backend.addBundle( renderContext, renderBundle );
  39146. }
  39147. /**
  39148. * Renders the scene or 3D object with the given camera. This method can only be called
  39149. * if the renderer has been initialized.
  39150. *
  39151. * The target of the method is the default framebuffer (meaning the canvas)
  39152. * or alternatively a render target when specified via `setRenderTarget()`.
  39153. *
  39154. * @param {Object3D} scene - The scene or 3D object to render.
  39155. * @param {Camera} camera - The camera to render the scene with.
  39156. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  39157. * Only returned when the renderer has not been initialized.
  39158. */
  39159. render( scene, camera ) {
  39160. if ( this._initialized === false ) {
  39161. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  39162. return this.renderAsync( scene, camera );
  39163. }
  39164. this._renderScene( scene, camera );
  39165. }
  39166. /**
  39167. * Returns an internal render target which is used when computing the output tone mapping
  39168. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  39169. * pass and not inline to achieve more correct results.
  39170. *
  39171. * @private
  39172. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  39173. */
  39174. _getFrameBufferTarget() {
  39175. const { currentToneMapping, currentColorSpace } = this;
  39176. const useToneMapping = currentToneMapping !== NoToneMapping;
  39177. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  39178. if ( useToneMapping === false && useColorSpace === false ) return null;
  39179. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  39180. const { depth, stencil } = this;
  39181. let frameBufferTarget = this._frameBufferTarget;
  39182. if ( frameBufferTarget === null ) {
  39183. frameBufferTarget = new RenderTarget( width, height, {
  39184. depthBuffer: depth,
  39185. stencilBuffer: stencil,
  39186. type: this._colorBufferType,
  39187. format: RGBAFormat,
  39188. colorSpace: ColorManagement.workingColorSpace,
  39189. generateMipmaps: false,
  39190. minFilter: LinearFilter,
  39191. magFilter: LinearFilter,
  39192. samples: this.samples
  39193. } );
  39194. frameBufferTarget.isPostProcessingRenderTarget = true;
  39195. this._frameBufferTarget = frameBufferTarget;
  39196. }
  39197. const outputRenderTarget = this.getOutputRenderTarget();
  39198. frameBufferTarget.depthBuffer = depth;
  39199. frameBufferTarget.stencilBuffer = stencil;
  39200. if ( outputRenderTarget !== null ) {
  39201. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  39202. } else {
  39203. frameBufferTarget.setSize( width, height, 1 );
  39204. }
  39205. frameBufferTarget.viewport.copy( this._viewport );
  39206. frameBufferTarget.scissor.copy( this._scissor );
  39207. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  39208. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  39209. frameBufferTarget.scissorTest = this._scissorTest;
  39210. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  39211. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  39212. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  39213. return frameBufferTarget;
  39214. }
  39215. /**
  39216. * Renders the scene or 3D object with the given camera.
  39217. *
  39218. * @private
  39219. * @param {Object3D} scene - The scene or 3D object to render.
  39220. * @param {Camera} camera - The camera to render the scene with.
  39221. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  39222. * @return {RenderContext} The current render context.
  39223. */
  39224. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  39225. if ( this._isDeviceLost === true ) return;
  39226. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  39227. // preserve render tree
  39228. const nodeFrame = this._nodes.nodeFrame;
  39229. const previousRenderId = nodeFrame.renderId;
  39230. const previousRenderContext = this._currentRenderContext;
  39231. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  39232. //
  39233. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  39234. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  39235. const activeCubeFace = this._activeCubeFace;
  39236. const activeMipmapLevel = this._activeMipmapLevel;
  39237. //
  39238. let renderTarget;
  39239. if ( frameBufferTarget !== null ) {
  39240. renderTarget = frameBufferTarget;
  39241. this.setRenderTarget( renderTarget );
  39242. } else {
  39243. renderTarget = outputRenderTarget;
  39244. }
  39245. //
  39246. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  39247. this._currentRenderContext = renderContext;
  39248. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  39249. //
  39250. this.info.calls ++;
  39251. this.info.render.calls ++;
  39252. this.info.render.frameCalls ++;
  39253. nodeFrame.renderId = this.info.calls;
  39254. //
  39255. const coordinateSystem = this.coordinateSystem;
  39256. const xr = this.xr;
  39257. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  39258. camera.coordinateSystem = coordinateSystem;
  39259. camera.updateProjectionMatrix();
  39260. if ( camera.isArrayCamera ) {
  39261. for ( const subCamera of camera.cameras ) {
  39262. subCamera.coordinateSystem = coordinateSystem;
  39263. subCamera.updateProjectionMatrix();
  39264. }
  39265. }
  39266. }
  39267. //
  39268. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  39269. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  39270. if ( xr.enabled === true && xr.isPresenting === true ) {
  39271. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  39272. camera = xr.getCamera(); // use XR camera for rendering
  39273. }
  39274. //
  39275. let viewport = this._viewport;
  39276. let scissor = this._scissor;
  39277. let pixelRatio = this._pixelRatio;
  39278. if ( renderTarget !== null ) {
  39279. viewport = renderTarget.viewport;
  39280. scissor = renderTarget.scissor;
  39281. pixelRatio = 1;
  39282. }
  39283. this.getDrawingBufferSize( _drawingBufferSize );
  39284. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  39285. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  39286. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  39287. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  39288. renderContext.viewportValue.width >>= activeMipmapLevel;
  39289. renderContext.viewportValue.height >>= activeMipmapLevel;
  39290. renderContext.viewportValue.minDepth = minDepth;
  39291. renderContext.viewportValue.maxDepth = maxDepth;
  39292. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  39293. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  39294. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  39295. renderContext.scissorValue.width >>= activeMipmapLevel;
  39296. renderContext.scissorValue.height >>= activeMipmapLevel;
  39297. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  39298. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  39299. //
  39300. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  39301. //
  39302. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  39303. if ( ! camera.isArrayCamera ) {
  39304. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  39305. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  39306. }
  39307. const renderList = this._renderLists.get( scene, camera );
  39308. renderList.begin();
  39309. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  39310. renderList.finish();
  39311. if ( this.sortObjects === true ) {
  39312. renderList.sort( this._opaqueSort, this._transparentSort );
  39313. }
  39314. //
  39315. if ( renderTarget !== null ) {
  39316. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  39317. const renderTargetData = this._textures.get( renderTarget );
  39318. renderContext.textures = renderTargetData.textures;
  39319. renderContext.depthTexture = renderTargetData.depthTexture;
  39320. renderContext.width = renderTargetData.width;
  39321. renderContext.height = renderTargetData.height;
  39322. renderContext.renderTarget = renderTarget;
  39323. renderContext.depth = renderTarget.depthBuffer;
  39324. renderContext.stencil = renderTarget.stencilBuffer;
  39325. } else {
  39326. renderContext.textures = null;
  39327. renderContext.depthTexture = null;
  39328. renderContext.width = this.domElement.width;
  39329. renderContext.height = this.domElement.height;
  39330. renderContext.depth = this.depth;
  39331. renderContext.stencil = this.stencil;
  39332. }
  39333. renderContext.width >>= activeMipmapLevel;
  39334. renderContext.height >>= activeMipmapLevel;
  39335. renderContext.activeCubeFace = activeCubeFace;
  39336. renderContext.activeMipmapLevel = activeMipmapLevel;
  39337. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  39338. //
  39339. this._background.update( sceneRef, renderList, renderContext );
  39340. //
  39341. renderContext.camera = camera;
  39342. this.backend.beginRender( renderContext );
  39343. // process render lists
  39344. const {
  39345. bundles,
  39346. lightsNode,
  39347. transparentDoublePass: transparentDoublePassObjects,
  39348. transparent: transparentObjects,
  39349. opaque: opaqueObjects
  39350. } = renderList;
  39351. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  39352. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39353. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39354. // finish render pass
  39355. this.backend.finishRender( renderContext );
  39356. // restore render tree
  39357. nodeFrame.renderId = previousRenderId;
  39358. this._currentRenderContext = previousRenderContext;
  39359. this._currentRenderObjectFunction = previousRenderObjectFunction;
  39360. //
  39361. if ( frameBufferTarget !== null ) {
  39362. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  39363. this._renderOutput( renderTarget );
  39364. }
  39365. //
  39366. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  39367. //
  39368. return renderContext;
  39369. }
  39370. _setXRLayerSize( width, height ) {
  39371. this._width = width;
  39372. this._height = height;
  39373. this.setViewport( 0, 0, width, height );
  39374. }
  39375. /**
  39376. * The output pass performs tone mapping and color space conversion.
  39377. *
  39378. * @private
  39379. * @param {RenderTarget} renderTarget - The current render target.
  39380. */
  39381. _renderOutput( renderTarget ) {
  39382. const quad = this._quad;
  39383. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  39384. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  39385. quad.material.needsUpdate = true;
  39386. }
  39387. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  39388. const currentAutoClear = this.autoClear;
  39389. const currentXR = this.xr.enabled;
  39390. this.autoClear = false;
  39391. this.xr.enabled = false;
  39392. this._renderScene( quad, quad.camera, false );
  39393. this.autoClear = currentAutoClear;
  39394. this.xr.enabled = currentXR;
  39395. }
  39396. /**
  39397. * Returns the maximum available anisotropy for texture filtering.
  39398. *
  39399. * @return {number} The maximum available anisotropy.
  39400. */
  39401. getMaxAnisotropy() {
  39402. return this.backend.getMaxAnisotropy();
  39403. }
  39404. /**
  39405. * Returns the active cube face.
  39406. *
  39407. * @return {number} The active cube face.
  39408. */
  39409. getActiveCubeFace() {
  39410. return this._activeCubeFace;
  39411. }
  39412. /**
  39413. * Returns the active mipmap level.
  39414. *
  39415. * @return {number} The active mipmap level.
  39416. */
  39417. getActiveMipmapLevel() {
  39418. return this._activeMipmapLevel;
  39419. }
  39420. /**
  39421. * Applications are advised to always define the animation loop
  39422. * with this method and not manually with `requestAnimationFrame()`
  39423. * for best compatibility.
  39424. *
  39425. * @async
  39426. * @param {?Function} callback - The application's animation loop.
  39427. * @return {Promise} A Promise that resolves when the set has been executed.
  39428. */
  39429. async setAnimationLoop( callback ) {
  39430. if ( this._initialized === false ) await this.init();
  39431. this._animation.setAnimationLoop( callback );
  39432. }
  39433. /**
  39434. * Can be used to transfer buffer data from a storage buffer attribute
  39435. * from the GPU to the CPU in context of compute shaders.
  39436. *
  39437. * @async
  39438. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39439. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39440. */
  39441. async getArrayBufferAsync( attribute ) {
  39442. return await this.backend.getArrayBufferAsync( attribute );
  39443. }
  39444. /**
  39445. * Returns the rendering context.
  39446. *
  39447. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  39448. */
  39449. getContext() {
  39450. return this.backend.getContext();
  39451. }
  39452. /**
  39453. * Returns the pixel ratio.
  39454. *
  39455. * @return {number} The pixel ratio.
  39456. */
  39457. getPixelRatio() {
  39458. return this._pixelRatio;
  39459. }
  39460. /**
  39461. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39462. *
  39463. * @param {Vector2} target - The method writes the result in this target object.
  39464. * @return {Vector2} The drawing buffer size.
  39465. */
  39466. getDrawingBufferSize( target ) {
  39467. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39468. }
  39469. /**
  39470. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39471. *
  39472. * @param {Vector2} target - The method writes the result in this target object.
  39473. * @return {Vector2} The renderer's size in logical pixels.
  39474. */
  39475. getSize( target ) {
  39476. return target.set( this._width, this._height );
  39477. }
  39478. /**
  39479. * Sets the given pixel ratio and resizes the canvas if necessary.
  39480. *
  39481. * @param {number} [value=1] - The pixel ratio.
  39482. */
  39483. setPixelRatio( value = 1 ) {
  39484. if ( this._pixelRatio === value ) return;
  39485. this._pixelRatio = value;
  39486. this.setSize( this._width, this._height, false );
  39487. }
  39488. /**
  39489. * This method allows to define the drawing buffer size by specifying
  39490. * width, height and pixel ratio all at once. The size of the drawing
  39491. * buffer is computed with this formula:
  39492. * ```js
  39493. * size.x = width * pixelRatio;
  39494. * size.y = height * pixelRatio;
  39495. * ```
  39496. *
  39497. * @param {number} width - The width in logical pixels.
  39498. * @param {number} height - The height in logical pixels.
  39499. * @param {number} pixelRatio - The pixel ratio.
  39500. */
  39501. setDrawingBufferSize( width, height, pixelRatio ) {
  39502. // Renderer can't be resized while presenting in XR.
  39503. if ( this.xr && this.xr.isPresenting ) return;
  39504. this._width = width;
  39505. this._height = height;
  39506. this._pixelRatio = pixelRatio;
  39507. this.domElement.width = Math.floor( width * pixelRatio );
  39508. this.domElement.height = Math.floor( height * pixelRatio );
  39509. this.setViewport( 0, 0, width, height );
  39510. if ( this._initialized ) this.backend.updateSize();
  39511. }
  39512. /**
  39513. * Sets the size of the renderer.
  39514. *
  39515. * @param {number} width - The width in logical pixels.
  39516. * @param {number} height - The height in logical pixels.
  39517. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39518. */
  39519. setSize( width, height, updateStyle = true ) {
  39520. // Renderer can't be resized while presenting in XR.
  39521. if ( this.xr && this.xr.isPresenting ) return;
  39522. this._width = width;
  39523. this._height = height;
  39524. this.domElement.width = Math.floor( width * this._pixelRatio );
  39525. this.domElement.height = Math.floor( height * this._pixelRatio );
  39526. if ( updateStyle === true ) {
  39527. this.domElement.style.width = width + 'px';
  39528. this.domElement.style.height = height + 'px';
  39529. }
  39530. this.setViewport( 0, 0, width, height );
  39531. if ( this._initialized ) this.backend.updateSize();
  39532. }
  39533. /**
  39534. * Defines a manual sort function for the opaque render list.
  39535. * Pass `null` to use the default sort.
  39536. *
  39537. * @param {Function} method - The sort function.
  39538. */
  39539. setOpaqueSort( method ) {
  39540. this._opaqueSort = method;
  39541. }
  39542. /**
  39543. * Defines a manual sort function for the transparent render list.
  39544. * Pass `null` to use the default sort.
  39545. *
  39546. * @param {Function} method - The sort function.
  39547. */
  39548. setTransparentSort( method ) {
  39549. this._transparentSort = method;
  39550. }
  39551. /**
  39552. * Returns the scissor rectangle.
  39553. *
  39554. * @param {Vector4} target - The method writes the result in this target object.
  39555. * @return {Vector4} The scissor rectangle.
  39556. */
  39557. getScissor( target ) {
  39558. const scissor = this._scissor;
  39559. target.x = scissor.x;
  39560. target.y = scissor.y;
  39561. target.width = scissor.width;
  39562. target.height = scissor.height;
  39563. return target;
  39564. }
  39565. /**
  39566. * Defines the scissor rectangle.
  39567. *
  39568. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39569. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39570. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39571. * @param {number} width - The width of the scissor box in logical pixel unit.
  39572. * @param {number} height - The height of the scissor box in logical pixel unit.
  39573. */
  39574. setScissor( x, y, width, height ) {
  39575. const scissor = this._scissor;
  39576. if ( x.isVector4 ) {
  39577. scissor.copy( x );
  39578. } else {
  39579. scissor.set( x, y, width, height );
  39580. }
  39581. }
  39582. /**
  39583. * Returns the scissor test value.
  39584. *
  39585. * @return {boolean} Whether the scissor test should be enabled or not.
  39586. */
  39587. getScissorTest() {
  39588. return this._scissorTest;
  39589. }
  39590. /**
  39591. * Defines the scissor test.
  39592. *
  39593. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39594. */
  39595. setScissorTest( boolean ) {
  39596. this._scissorTest = boolean;
  39597. this.backend.setScissorTest( boolean );
  39598. }
  39599. /**
  39600. * Returns the viewport definition.
  39601. *
  39602. * @param {Vector4} target - The method writes the result in this target object.
  39603. * @return {Vector4} The viewport definition.
  39604. */
  39605. getViewport( target ) {
  39606. return target.copy( this._viewport );
  39607. }
  39608. /**
  39609. * Defines the viewport.
  39610. *
  39611. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39612. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39613. * @param {number} width - The width of the viewport in logical pixel unit.
  39614. * @param {number} height - The height of the viewport in logical pixel unit.
  39615. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  39616. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  39617. */
  39618. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39619. const viewport = this._viewport;
  39620. if ( x.isVector4 ) {
  39621. viewport.copy( x );
  39622. } else {
  39623. viewport.set( x, y, width, height );
  39624. }
  39625. viewport.minDepth = minDepth;
  39626. viewport.maxDepth = maxDepth;
  39627. }
  39628. /**
  39629. * Returns the clear color.
  39630. *
  39631. * @param {Color} target - The method writes the result in this target object.
  39632. * @return {Color} The clear color.
  39633. */
  39634. getClearColor( target ) {
  39635. return target.copy( this._clearColor );
  39636. }
  39637. /**
  39638. * Defines the clear color and optionally the clear alpha.
  39639. *
  39640. * @param {Color} color - The clear color.
  39641. * @param {number} [alpha=1] - The clear alpha.
  39642. */
  39643. setClearColor( color, alpha = 1 ) {
  39644. this._clearColor.set( color );
  39645. this._clearColor.a = alpha;
  39646. }
  39647. /**
  39648. * Returns the clear alpha.
  39649. *
  39650. * @return {number} The clear alpha.
  39651. */
  39652. getClearAlpha() {
  39653. return this._clearColor.a;
  39654. }
  39655. /**
  39656. * Defines the clear alpha.
  39657. *
  39658. * @param {number} alpha - The clear alpha.
  39659. */
  39660. setClearAlpha( alpha ) {
  39661. this._clearColor.a = alpha;
  39662. }
  39663. /**
  39664. * Returns the clear depth.
  39665. *
  39666. * @return {number} The clear depth.
  39667. */
  39668. getClearDepth() {
  39669. return this._clearDepth;
  39670. }
  39671. /**
  39672. * Defines the clear depth.
  39673. *
  39674. * @param {number} depth - The clear depth.
  39675. */
  39676. setClearDepth( depth ) {
  39677. this._clearDepth = depth;
  39678. }
  39679. /**
  39680. * Returns the clear stencil.
  39681. *
  39682. * @return {number} The clear stencil.
  39683. */
  39684. getClearStencil() {
  39685. return this._clearStencil;
  39686. }
  39687. /**
  39688. * Defines the clear stencil.
  39689. *
  39690. * @param {number} stencil - The clear stencil.
  39691. */
  39692. setClearStencil( stencil ) {
  39693. this._clearStencil = stencil;
  39694. }
  39695. /**
  39696. * This method performs an occlusion query for the given 3D object.
  39697. * It returns `true` if the given 3D object is fully occluded by other
  39698. * 3D objects in the scene.
  39699. *
  39700. * @param {Object3D} object - The 3D object to test.
  39701. * @return {boolean} Whether the 3D object is fully occluded or not.
  39702. */
  39703. isOccluded( object ) {
  39704. const renderContext = this._currentRenderContext;
  39705. return renderContext && this.backend.isOccluded( renderContext, object );
  39706. }
  39707. /**
  39708. * Performs a manual clear operation. This method ignores `autoClear` properties.
  39709. *
  39710. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  39711. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  39712. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  39713. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39714. * Only returned when the renderer has not been initialized.
  39715. */
  39716. clear( color = true, depth = true, stencil = true ) {
  39717. if ( this._initialized === false ) {
  39718. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  39719. return this.clearAsync( color, depth, stencil );
  39720. }
  39721. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  39722. let renderContext = null;
  39723. if ( renderTarget !== null ) {
  39724. this._textures.updateRenderTarget( renderTarget );
  39725. const renderTargetData = this._textures.get( renderTarget );
  39726. renderContext = this._renderContexts.getForClear( renderTarget );
  39727. renderContext.textures = renderTargetData.textures;
  39728. renderContext.depthTexture = renderTargetData.depthTexture;
  39729. renderContext.width = renderTargetData.width;
  39730. renderContext.height = renderTargetData.height;
  39731. renderContext.renderTarget = renderTarget;
  39732. renderContext.depth = renderTarget.depthBuffer;
  39733. renderContext.stencil = renderTarget.stencilBuffer;
  39734. // #30329
  39735. renderContext.clearColorValue = this.backend.getClearColor();
  39736. renderContext.activeCubeFace = this.getActiveCubeFace();
  39737. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  39738. }
  39739. this.backend.clear( color, depth, stencil, renderContext );
  39740. if ( renderTarget !== null && this._renderTarget === null ) {
  39741. this._renderOutput( renderTarget );
  39742. }
  39743. }
  39744. /**
  39745. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  39746. *
  39747. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39748. * Only returned when the renderer has not been initialized.
  39749. */
  39750. clearColor() {
  39751. return this.clear( true, false, false );
  39752. }
  39753. /**
  39754. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  39755. *
  39756. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39757. * Only returned when the renderer has not been initialized.
  39758. */
  39759. clearDepth() {
  39760. return this.clear( false, true, false );
  39761. }
  39762. /**
  39763. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  39764. *
  39765. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39766. * Only returned when the renderer has not been initialized.
  39767. */
  39768. clearStencil() {
  39769. return this.clear( false, false, true );
  39770. }
  39771. /**
  39772. * Async version of {@link Renderer#clear}.
  39773. *
  39774. * @async
  39775. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  39776. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  39777. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  39778. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39779. */
  39780. async clearAsync( color = true, depth = true, stencil = true ) {
  39781. if ( this._initialized === false ) await this.init();
  39782. this.clear( color, depth, stencil );
  39783. }
  39784. /**
  39785. * Async version of {@link Renderer#clearColor}.
  39786. *
  39787. * @async
  39788. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39789. */
  39790. async clearColorAsync() {
  39791. this.clearAsync( true, false, false );
  39792. }
  39793. /**
  39794. * Async version of {@link Renderer#clearDepth}.
  39795. *
  39796. * @async
  39797. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39798. */
  39799. async clearDepthAsync() {
  39800. this.clearAsync( false, true, false );
  39801. }
  39802. /**
  39803. * Async version of {@link Renderer#clearStencil}.
  39804. *
  39805. * @async
  39806. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39807. */
  39808. async clearStencilAsync() {
  39809. this.clearAsync( false, false, true );
  39810. }
  39811. /**
  39812. * The current tone mapping of the renderer. When not producing screen output,
  39813. * the tone mapping is always `NoToneMapping`.
  39814. *
  39815. * @type {number}
  39816. */
  39817. get currentToneMapping() {
  39818. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  39819. }
  39820. /**
  39821. * The current color space of the renderer. When not producing screen output,
  39822. * the color space is always the working color space.
  39823. *
  39824. * @type {string}
  39825. */
  39826. get currentColorSpace() {
  39827. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  39828. }
  39829. /**
  39830. * Returns `true` if the rendering settings are set to screen output.
  39831. *
  39832. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  39833. */
  39834. get isOutputTarget() {
  39835. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  39836. }
  39837. /**
  39838. * Frees all internal resources of the renderer. Call this method if the renderer
  39839. * is no longer in use by your app.
  39840. */
  39841. dispose() {
  39842. this.info.dispose();
  39843. this.backend.dispose();
  39844. this._animation.dispose();
  39845. this._objects.dispose();
  39846. this._pipelines.dispose();
  39847. this._nodes.dispose();
  39848. this._bindings.dispose();
  39849. this._renderLists.dispose();
  39850. this._renderContexts.dispose();
  39851. this._textures.dispose();
  39852. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  39853. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  39854. if ( queryPool !== null ) queryPool.dispose();
  39855. } );
  39856. this.setRenderTarget( null );
  39857. this.setAnimationLoop( null );
  39858. }
  39859. /**
  39860. * Sets the given render target. Calling this method means the renderer does not
  39861. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  39862. * Use `null` as the first argument to reset the state.
  39863. *
  39864. * @param {?RenderTarget} renderTarget - The render target to set.
  39865. * @param {number} [activeCubeFace=0] - The active cube face.
  39866. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  39867. */
  39868. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  39869. this._renderTarget = renderTarget;
  39870. this._activeCubeFace = activeCubeFace;
  39871. this._activeMipmapLevel = activeMipmapLevel;
  39872. }
  39873. /**
  39874. * Returns the current render target.
  39875. *
  39876. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  39877. */
  39878. getRenderTarget() {
  39879. return this._renderTarget;
  39880. }
  39881. /**
  39882. * Sets the output render target for the renderer.
  39883. *
  39884. * @param {Object} renderTarget - The render target to set as the output target.
  39885. */
  39886. setOutputRenderTarget( renderTarget ) {
  39887. this._outputRenderTarget = renderTarget;
  39888. }
  39889. /**
  39890. * Returns the current output target.
  39891. *
  39892. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  39893. */
  39894. getOutputRenderTarget() {
  39895. return this._outputRenderTarget;
  39896. }
  39897. /**
  39898. * Resets the renderer to the initial state before WebXR started.
  39899. *
  39900. */
  39901. _resetXRState() {
  39902. this.backend.setXRTarget( null );
  39903. this.setOutputRenderTarget( null );
  39904. this.setRenderTarget( null );
  39905. this._frameBufferTarget.dispose();
  39906. this._frameBufferTarget = null;
  39907. }
  39908. /**
  39909. * Callback for {@link Renderer#setRenderObjectFunction}.
  39910. *
  39911. * @callback renderObjectFunction
  39912. * @param {Object3D} object - The 3D object.
  39913. * @param {Scene} scene - The scene the 3D object belongs to.
  39914. * @param {Camera} camera - The camera the object should be rendered with.
  39915. * @param {BufferGeometry} geometry - The object's geometry.
  39916. * @param {Material} material - The object's material.
  39917. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39918. * @param {LightsNode} lightsNode - The current lights node.
  39919. * @param {ClippingContext} clippingContext - The clipping context.
  39920. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39921. */
  39922. /**
  39923. * Sets the given render object function. Calling this method overwrites the default implementation
  39924. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  39925. * if you want to modify the way objects are rendered. For example you can define things like "every
  39926. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  39927. * The custom function must always call `renderObject()` in its implementation.
  39928. *
  39929. * Use `null` as the first argument to reset the state.
  39930. *
  39931. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  39932. */
  39933. setRenderObjectFunction( renderObjectFunction ) {
  39934. this._renderObjectFunction = renderObjectFunction;
  39935. }
  39936. /**
  39937. * Returns the current render object function.
  39938. *
  39939. * @return {?Function} The current render object function. Returns `null` if no function is set.
  39940. */
  39941. getRenderObjectFunction() {
  39942. return this._renderObjectFunction;
  39943. }
  39944. /**
  39945. * Execute a single or an array of compute nodes. This method can only be called
  39946. * if the renderer has been initialized.
  39947. *
  39948. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  39949. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  39950. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  39951. */
  39952. compute( computeNodes, dispatchSizeOrCount = null ) {
  39953. if ( this._isDeviceLost === true ) return;
  39954. if ( this._initialized === false ) {
  39955. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  39956. return this.computeAsync( computeNodes );
  39957. }
  39958. //
  39959. const nodeFrame = this._nodes.nodeFrame;
  39960. const previousRenderId = nodeFrame.renderId;
  39961. //
  39962. this.info.calls ++;
  39963. this.info.compute.calls ++;
  39964. this.info.compute.frameCalls ++;
  39965. nodeFrame.renderId = this.info.calls;
  39966. //
  39967. const backend = this.backend;
  39968. const pipelines = this._pipelines;
  39969. const bindings = this._bindings;
  39970. const nodes = this._nodes;
  39971. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  39972. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  39973. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  39974. }
  39975. backend.beginCompute( computeNodes );
  39976. for ( const computeNode of computeList ) {
  39977. // onInit
  39978. if ( pipelines.has( computeNode ) === false ) {
  39979. const dispose = () => {
  39980. computeNode.removeEventListener( 'dispose', dispose );
  39981. pipelines.delete( computeNode );
  39982. bindings.delete( computeNode );
  39983. nodes.delete( computeNode );
  39984. };
  39985. computeNode.addEventListener( 'dispose', dispose );
  39986. //
  39987. const onInitFn = computeNode.onInitFunction;
  39988. if ( onInitFn !== null ) {
  39989. onInitFn.call( computeNode, { renderer: this } );
  39990. }
  39991. }
  39992. nodes.updateForCompute( computeNode );
  39993. bindings.updateForCompute( computeNode );
  39994. const computeBindings = bindings.getForCompute( computeNode );
  39995. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  39996. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  39997. }
  39998. backend.finishCompute( computeNodes );
  39999. //
  40000. nodeFrame.renderId = previousRenderId;
  40001. }
  40002. /**
  40003. * Execute a single or an array of compute nodes.
  40004. *
  40005. * @async
  40006. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  40007. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  40008. * @return {Promise} A Promise that resolve when the compute has finished.
  40009. */
  40010. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  40011. if ( this._initialized === false ) await this.init();
  40012. this.compute( computeNodes, dispatchSizeOrCount );
  40013. }
  40014. /**
  40015. * Checks if the given feature is supported by the selected backend.
  40016. *
  40017. * @async
  40018. * @param {string} name - The feature's name.
  40019. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  40020. */
  40021. async hasFeatureAsync( name ) {
  40022. if ( this._initialized === false ) await this.init();
  40023. return this.backend.hasFeature( name );
  40024. }
  40025. async resolveTimestampsAsync( type = 'render' ) {
  40026. if ( this._initialized === false ) await this.init();
  40027. return this.backend.resolveTimestampsAsync( type );
  40028. }
  40029. /**
  40030. * Checks if the given feature is supported by the selected backend. If the
  40031. * renderer has not been initialized, this method always returns `false`.
  40032. *
  40033. * @param {string} name - The feature's name.
  40034. * @return {boolean} Whether the feature is supported or not.
  40035. */
  40036. hasFeature( name ) {
  40037. if ( this._initialized === false ) {
  40038. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  40039. return false;
  40040. }
  40041. return this.backend.hasFeature( name );
  40042. }
  40043. /**
  40044. * Returns `true` when the renderer has been initialized.
  40045. *
  40046. * @return {boolean} Whether the renderer has been initialized or not.
  40047. */
  40048. hasInitialized() {
  40049. return this._initialized;
  40050. }
  40051. /**
  40052. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  40053. * (which can cause noticeable lags due to decode and GPU upload overhead).
  40054. *
  40055. * @async
  40056. * @param {Texture} texture - The texture.
  40057. * @return {Promise} A Promise that resolves when the texture has been initialized.
  40058. */
  40059. async initTextureAsync( texture ) {
  40060. if ( this._initialized === false ) await this.init();
  40061. this._textures.updateTexture( texture );
  40062. }
  40063. /**
  40064. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  40065. * (which can cause noticeable lags due to decode and GPU upload overhead).
  40066. *
  40067. * This method can only be used if the renderer has been initialized.
  40068. *
  40069. * @param {Texture} texture - The texture.
  40070. */
  40071. initTexture( texture ) {
  40072. if ( this._initialized === false ) {
  40073. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  40074. }
  40075. this._textures.updateTexture( texture );
  40076. }
  40077. /**
  40078. * Copies the current bound framebuffer into the given texture.
  40079. *
  40080. * @param {FramebufferTexture} framebufferTexture - The texture.
  40081. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  40082. */
  40083. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  40084. if ( rectangle !== null ) {
  40085. if ( rectangle.isVector2 ) {
  40086. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  40087. } else if ( rectangle.isVector4 ) {
  40088. rectangle = _vector4.copy( rectangle ).floor();
  40089. } else {
  40090. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  40091. return;
  40092. }
  40093. } else {
  40094. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  40095. }
  40096. //
  40097. let renderContext = this._currentRenderContext;
  40098. let renderTarget;
  40099. if ( renderContext !== null ) {
  40100. renderTarget = renderContext.renderTarget;
  40101. } else {
  40102. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40103. if ( renderTarget !== null ) {
  40104. this._textures.updateRenderTarget( renderTarget );
  40105. renderContext = this._textures.get( renderTarget );
  40106. }
  40107. }
  40108. //
  40109. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  40110. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  40111. }
  40112. /**
  40113. * Copies data of the given source texture into a destination texture.
  40114. *
  40115. * @param {Texture} srcTexture - The source texture.
  40116. * @param {Texture} dstTexture - The destination texture.
  40117. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  40118. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  40119. * @param {number} [srcLevel=0] - The source mip level to copy from.
  40120. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  40121. */
  40122. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  40123. this._textures.updateTexture( srcTexture );
  40124. this._textures.updateTexture( dstTexture );
  40125. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  40126. }
  40127. /**
  40128. * Reads pixel data from the given render target.
  40129. *
  40130. * @async
  40131. * @param {RenderTarget} renderTarget - The render target to read from.
  40132. * @param {number} x - The `x` coordinate of the copy region's origin.
  40133. * @param {number} y - The `y` coordinate of the copy region's origin.
  40134. * @param {number} width - The width of the copy region.
  40135. * @param {number} height - The height of the copy region.
  40136. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  40137. * @param {number} [faceIndex=0] - The active cube face index.
  40138. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  40139. */
  40140. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  40141. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  40142. }
  40143. /**
  40144. * Analyzes the given 3D object's hierarchy and builds render lists from the
  40145. * processed hierarchy.
  40146. *
  40147. * @param {Object3D} object - The 3D object to process (usually a scene).
  40148. * @param {Camera} camera - The camera the object is rendered with.
  40149. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  40150. * @param {RenderList} renderList - The current render list.
  40151. * @param {ClippingContext} clippingContext - The current clipping context.
  40152. */
  40153. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  40154. if ( object.visible === false ) return;
  40155. const visible = object.layers.test( camera.layers );
  40156. if ( visible ) {
  40157. if ( object.isGroup ) {
  40158. groupOrder = object.renderOrder;
  40159. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  40160. } else if ( object.isLOD ) {
  40161. if ( object.autoUpdate === true ) object.update( camera );
  40162. } else if ( object.isLight ) {
  40163. renderList.pushLight( object );
  40164. } else if ( object.isSprite ) {
  40165. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40166. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  40167. if ( this.sortObjects === true ) {
  40168. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  40169. }
  40170. const { geometry, material } = object;
  40171. if ( material.visible ) {
  40172. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  40173. }
  40174. }
  40175. } else if ( object.isLineLoop ) {
  40176. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  40177. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  40178. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40179. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  40180. const { geometry, material } = object;
  40181. if ( this.sortObjects === true ) {
  40182. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  40183. _vector4
  40184. .copy( geometry.boundingSphere.center )
  40185. .applyMatrix4( object.matrixWorld )
  40186. .applyMatrix4( _projScreenMatrix );
  40187. }
  40188. if ( Array.isArray( material ) ) {
  40189. const groups = geometry.groups;
  40190. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  40191. const group = groups[ i ];
  40192. const groupMaterial = material[ group.materialIndex ];
  40193. if ( groupMaterial && groupMaterial.visible ) {
  40194. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  40195. }
  40196. }
  40197. } else if ( material.visible ) {
  40198. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  40199. }
  40200. }
  40201. }
  40202. }
  40203. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  40204. const baseRenderList = renderList;
  40205. // replace render list
  40206. renderList = this._renderLists.get( object, camera );
  40207. renderList.begin();
  40208. baseRenderList.pushBundle( {
  40209. bundleGroup: object,
  40210. camera,
  40211. renderList,
  40212. } );
  40213. renderList.finish();
  40214. }
  40215. const children = object.children;
  40216. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40217. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  40218. }
  40219. }
  40220. /**
  40221. * Renders the given render bundles.
  40222. *
  40223. * @private
  40224. * @param {Array<Object>} bundles - Array with render bundle data.
  40225. * @param {Scene} sceneRef - The scene the render bundles belong to.
  40226. * @param {LightsNode} lightsNode - The current lights node.
  40227. */
  40228. _renderBundles( bundles, sceneRef, lightsNode ) {
  40229. for ( const bundle of bundles ) {
  40230. this._renderBundle( bundle, sceneRef, lightsNode );
  40231. }
  40232. }
  40233. /**
  40234. * Renders the transparent objects from the given render lists.
  40235. *
  40236. * @private
  40237. * @param {Array<Object>} renderList - The transparent render list.
  40238. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  40239. * @param {Camera} camera - The camera the render list should be rendered with.
  40240. * @param {Scene} scene - The scene the render list belongs to.
  40241. * @param {LightsNode} lightsNode - The current lights node.
  40242. */
  40243. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  40244. if ( doublePassList.length > 0 ) {
  40245. // render back side
  40246. for ( const { material } of doublePassList ) {
  40247. material.side = BackSide;
  40248. }
  40249. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  40250. // render front side
  40251. for ( const { material } of doublePassList ) {
  40252. material.side = FrontSide;
  40253. }
  40254. this._renderObjects( renderList, camera, scene, lightsNode );
  40255. // restore
  40256. for ( const { material } of doublePassList ) {
  40257. material.side = DoubleSide;
  40258. }
  40259. } else {
  40260. this._renderObjects( renderList, camera, scene, lightsNode );
  40261. }
  40262. }
  40263. /**
  40264. * Renders the objects from the given render list.
  40265. *
  40266. * @private
  40267. * @param {Array<Object>} renderList - The render list.
  40268. * @param {Camera} camera - The camera the render list should be rendered with.
  40269. * @param {Scene} scene - The scene the render list belongs to.
  40270. * @param {LightsNode} lightsNode - The current lights node.
  40271. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40272. */
  40273. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  40274. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  40275. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  40276. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  40277. }
  40278. }
  40279. /**
  40280. * This method represents the default render object function that manages the render lifecycle
  40281. * of the object.
  40282. *
  40283. * @param {Object3D} object - The 3D object.
  40284. * @param {Scene} scene - The scene the 3D object belongs to.
  40285. * @param {Camera} camera - The camera the object should be rendered with.
  40286. * @param {BufferGeometry} geometry - The object's geometry.
  40287. * @param {Material} material - The object's material.
  40288. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40289. * @param {LightsNode} lightsNode - The current lights node.
  40290. * @param {?ClippingContext} clippingContext - The clipping context.
  40291. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40292. */
  40293. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  40294. let overridePositionNode;
  40295. let overrideColorNode;
  40296. let overrideDepthNode;
  40297. //
  40298. object.onBeforeRender( this, scene, camera, geometry, material, group );
  40299. //
  40300. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  40301. const overrideMaterial = scene.overrideMaterial;
  40302. if ( material.positionNode && material.positionNode.isNode ) {
  40303. overridePositionNode = overrideMaterial.positionNode;
  40304. overrideMaterial.positionNode = material.positionNode;
  40305. }
  40306. overrideMaterial.alphaTest = material.alphaTest;
  40307. overrideMaterial.alphaMap = material.alphaMap;
  40308. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  40309. if ( overrideMaterial.isShadowPassMaterial ) {
  40310. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  40311. if ( material.depthNode && material.depthNode.isNode ) {
  40312. overrideDepthNode = overrideMaterial.depthNode;
  40313. overrideMaterial.depthNode = material.depthNode;
  40314. }
  40315. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  40316. overrideColorNode = overrideMaterial.colorNode;
  40317. overrideMaterial.colorNode = material.castShadowNode;
  40318. }
  40319. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  40320. overridePositionNode = overrideMaterial.positionNode;
  40321. overrideMaterial.positionNode = material.castShadowPositionNode;
  40322. }
  40323. }
  40324. material = overrideMaterial;
  40325. }
  40326. //
  40327. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  40328. material.side = BackSide;
  40329. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  40330. material.side = FrontSide;
  40331. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  40332. material.side = DoubleSide;
  40333. } else {
  40334. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  40335. }
  40336. //
  40337. if ( overridePositionNode !== undefined ) {
  40338. scene.overrideMaterial.positionNode = overridePositionNode;
  40339. }
  40340. if ( overrideDepthNode !== undefined ) {
  40341. scene.overrideMaterial.depthNode = overrideDepthNode;
  40342. }
  40343. if ( overrideColorNode !== undefined ) {
  40344. scene.overrideMaterial.colorNode = overrideColorNode;
  40345. }
  40346. //
  40347. object.onAfterRender( this, scene, camera, geometry, material, group );
  40348. }
  40349. /**
  40350. * This method represents the default `_handleObjectFunction` implementation which creates
  40351. * a render object from the given data and performs the draw command with the selected backend.
  40352. *
  40353. * @private
  40354. * @param {Object3D} object - The 3D object.
  40355. * @param {Material} material - The object's material.
  40356. * @param {Scene} scene - The scene the 3D object belongs to.
  40357. * @param {Camera} camera - The camera the object should be rendered with.
  40358. * @param {LightsNode} lightsNode - The current lights node.
  40359. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40360. * @param {ClippingContext} clippingContext - The clipping context.
  40361. * @param {string} [passId] - An optional ID for identifying the pass.
  40362. */
  40363. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  40364. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  40365. renderObject.drawRange = object.geometry.drawRange;
  40366. renderObject.group = group;
  40367. //
  40368. const needsRefresh = this._nodes.needsRefresh( renderObject );
  40369. if ( needsRefresh ) {
  40370. this._nodes.updateBefore( renderObject );
  40371. this._geometries.updateForRender( renderObject );
  40372. this._nodes.updateForRender( renderObject );
  40373. this._bindings.updateForRender( renderObject );
  40374. }
  40375. this._pipelines.updateForRender( renderObject );
  40376. //
  40377. if ( this._currentRenderBundle !== null ) {
  40378. const renderBundleData = this.backend.get( this._currentRenderBundle );
  40379. renderBundleData.renderObjects.push( renderObject );
  40380. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  40381. }
  40382. this.backend.draw( renderObject, this.info );
  40383. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  40384. }
  40385. /**
  40386. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  40387. * Used in `compileAsync()`.
  40388. *
  40389. * @private
  40390. * @param {Object3D} object - The 3D object.
  40391. * @param {Material} material - The object's material.
  40392. * @param {Scene} scene - The scene the 3D object belongs to.
  40393. * @param {Camera} camera - The camera the object should be rendered with.
  40394. * @param {LightsNode} lightsNode - The current lights node.
  40395. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40396. * @param {ClippingContext} clippingContext - The clipping context.
  40397. * @param {string} [passId] - An optional ID for identifying the pass.
  40398. */
  40399. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  40400. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  40401. renderObject.drawRange = object.geometry.drawRange;
  40402. renderObject.group = group;
  40403. //
  40404. this._nodes.updateBefore( renderObject );
  40405. this._geometries.updateForRender( renderObject );
  40406. this._nodes.updateForRender( renderObject );
  40407. this._bindings.updateForRender( renderObject );
  40408. this._pipelines.getForRender( renderObject, this._compilationPromises );
  40409. this._nodes.updateAfter( renderObject );
  40410. }
  40411. /**
  40412. * Alias for `compileAsync()`.
  40413. *
  40414. * @method
  40415. * @param {Object3D} scene - The scene or 3D object to precompile.
  40416. * @param {Camera} camera - The camera that is used to render the scene.
  40417. * @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.
  40418. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  40419. */
  40420. get compile() {
  40421. return this.compileAsync;
  40422. }
  40423. }
  40424. /**
  40425. * A binding represents the connection between a resource (like a texture, sampler
  40426. * or uniform buffer) and the resource definition in a shader stage.
  40427. *
  40428. * This module is an abstract base class for all concrete bindings types.
  40429. *
  40430. * @abstract
  40431. * @private
  40432. */
  40433. class Binding {
  40434. /**
  40435. * Constructs a new binding.
  40436. *
  40437. * @param {string} [name=''] - The binding's name.
  40438. */
  40439. constructor( name = '' ) {
  40440. /**
  40441. * The binding's name.
  40442. *
  40443. * @type {string}
  40444. */
  40445. this.name = name;
  40446. /**
  40447. * A bitmask that defines in what shader stages the
  40448. * binding's resource is accessible.
  40449. *
  40450. * @type {number}
  40451. */
  40452. this.visibility = 0;
  40453. }
  40454. /**
  40455. * Makes sure binding's resource is visible for the given shader stage.
  40456. *
  40457. * @param {number} visibility - The shader stage.
  40458. */
  40459. setVisibility( visibility ) {
  40460. this.visibility |= visibility;
  40461. }
  40462. /**
  40463. * Clones the binding.
  40464. *
  40465. * @return {Binding} The cloned binding.
  40466. */
  40467. clone() {
  40468. return Object.assign( new this.constructor(), this );
  40469. }
  40470. }
  40471. /**
  40472. * This function is usually called with the length in bytes of an array buffer.
  40473. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  40474. *
  40475. * @function
  40476. * @param {number} floatLength - The buffer length.
  40477. * @return {number} The padded length.
  40478. */
  40479. function getFloatLength( floatLength ) {
  40480. // ensure chunk size alignment (STD140 layout)
  40481. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  40482. }
  40483. /**
  40484. * Represents a buffer binding type.
  40485. *
  40486. * @private
  40487. * @abstract
  40488. * @augments Binding
  40489. */
  40490. class Buffer extends Binding {
  40491. /**
  40492. * Constructs a new buffer.
  40493. *
  40494. * @param {string} name - The buffer's name.
  40495. * @param {TypedArray} [buffer=null] - The buffer.
  40496. */
  40497. constructor( name, buffer = null ) {
  40498. super( name );
  40499. /**
  40500. * This flag can be used for type testing.
  40501. *
  40502. * @type {boolean}
  40503. * @readonly
  40504. * @default true
  40505. */
  40506. this.isBuffer = true;
  40507. /**
  40508. * The bytes per element.
  40509. *
  40510. * @type {number}
  40511. */
  40512. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  40513. /**
  40514. * A reference to the internal buffer.
  40515. *
  40516. * @private
  40517. * @type {TypedArray}
  40518. */
  40519. this._buffer = buffer;
  40520. }
  40521. /**
  40522. * The buffer's byte length.
  40523. *
  40524. * @type {number}
  40525. * @readonly
  40526. */
  40527. get byteLength() {
  40528. return getFloatLength( this._buffer.byteLength );
  40529. }
  40530. /**
  40531. * A reference to the internal buffer.
  40532. *
  40533. * @type {Float32Array}
  40534. * @readonly
  40535. */
  40536. get buffer() {
  40537. return this._buffer;
  40538. }
  40539. /**
  40540. * Updates the binding.
  40541. *
  40542. * @return {boolean} Whether the buffer has been updated and must be
  40543. * uploaded to the GPU.
  40544. */
  40545. update() {
  40546. return true;
  40547. }
  40548. }
  40549. /**
  40550. * Represents a uniform buffer binding type.
  40551. *
  40552. * @private
  40553. * @augments Buffer
  40554. */
  40555. class UniformBuffer extends Buffer {
  40556. /**
  40557. * Constructs a new uniform buffer.
  40558. *
  40559. * @param {string} name - The buffer's name.
  40560. * @param {TypedArray} [buffer=null] - The buffer.
  40561. */
  40562. constructor( name, buffer = null ) {
  40563. super( name, buffer );
  40564. /**
  40565. * This flag can be used for type testing.
  40566. *
  40567. * @type {boolean}
  40568. * @readonly
  40569. * @default true
  40570. */
  40571. this.isUniformBuffer = true;
  40572. }
  40573. }
  40574. let _id$4 = 0;
  40575. /**
  40576. * A special form of uniform buffer binding type.
  40577. * It's buffer value is managed by a node object.
  40578. *
  40579. * @private
  40580. * @augments UniformBuffer
  40581. */
  40582. class NodeUniformBuffer extends UniformBuffer {
  40583. /**
  40584. * Constructs a new node-based uniform buffer.
  40585. *
  40586. * @param {BufferNode} nodeUniform - The uniform buffer node.
  40587. * @param {UniformGroupNode} groupNode - The uniform group node.
  40588. */
  40589. constructor( nodeUniform, groupNode ) {
  40590. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  40591. /**
  40592. * The uniform buffer node.
  40593. *
  40594. * @type {BufferNode}
  40595. */
  40596. this.nodeUniform = nodeUniform;
  40597. /**
  40598. * The uniform group node.
  40599. *
  40600. * @type {UniformGroupNode}
  40601. */
  40602. this.groupNode = groupNode;
  40603. }
  40604. /**
  40605. * The uniform buffer.
  40606. *
  40607. * @type {Float32Array}
  40608. */
  40609. get buffer() {
  40610. return this.nodeUniform.value;
  40611. }
  40612. }
  40613. /**
  40614. * This class represents a uniform buffer binding but with
  40615. * an API that allows to maintain individual uniform objects.
  40616. *
  40617. * @private
  40618. * @augments UniformBuffer
  40619. */
  40620. class UniformsGroup extends UniformBuffer {
  40621. /**
  40622. * Constructs a new uniforms group.
  40623. *
  40624. * @param {string} name - The group's name.
  40625. */
  40626. constructor( name ) {
  40627. super( name );
  40628. /**
  40629. * This flag can be used for type testing.
  40630. *
  40631. * @type {boolean}
  40632. * @readonly
  40633. * @default true
  40634. */
  40635. this.isUniformsGroup = true;
  40636. /**
  40637. * An array with the raw uniform values.
  40638. *
  40639. * @private
  40640. * @type {?Array<number>}
  40641. * @default null
  40642. */
  40643. this._values = null;
  40644. /**
  40645. * An array of uniform objects.
  40646. *
  40647. * The order of uniforms in this array must match the order of uniforms in the shader.
  40648. *
  40649. * @type {Array<Uniform>}
  40650. */
  40651. this.uniforms = [];
  40652. }
  40653. /**
  40654. * Adds a uniform to this group.
  40655. *
  40656. * @param {Uniform} uniform - The uniform to add.
  40657. * @return {UniformsGroup} A reference to this group.
  40658. */
  40659. addUniform( uniform ) {
  40660. this.uniforms.push( uniform );
  40661. return this;
  40662. }
  40663. /**
  40664. * Removes a uniform from this group.
  40665. *
  40666. * @param {Uniform} uniform - The uniform to remove.
  40667. * @return {UniformsGroup} A reference to this group.
  40668. */
  40669. removeUniform( uniform ) {
  40670. const index = this.uniforms.indexOf( uniform );
  40671. if ( index !== -1 ) {
  40672. this.uniforms.splice( index, 1 );
  40673. }
  40674. return this;
  40675. }
  40676. /**
  40677. * An array with the raw uniform values.
  40678. *
  40679. * @type {Array<number>}
  40680. */
  40681. get values() {
  40682. if ( this._values === null ) {
  40683. this._values = Array.from( this.buffer );
  40684. }
  40685. return this._values;
  40686. }
  40687. /**
  40688. * A Float32 array buffer with the uniform values.
  40689. *
  40690. * @type {Float32Array}
  40691. */
  40692. get buffer() {
  40693. let buffer = this._buffer;
  40694. if ( buffer === null ) {
  40695. const byteLength = this.byteLength;
  40696. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  40697. this._buffer = buffer;
  40698. }
  40699. return buffer;
  40700. }
  40701. /**
  40702. * The byte length of the buffer with correct buffer alignment.
  40703. *
  40704. * @type {number}
  40705. */
  40706. get byteLength() {
  40707. const bytesPerElement = this.bytesPerElement;
  40708. let offset = 0; // global buffer offset in bytes
  40709. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  40710. const uniform = this.uniforms[ i ];
  40711. const boundary = uniform.boundary;
  40712. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  40713. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  40714. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  40715. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  40716. offset += chunkPadding;
  40717. // Check for chunk overflow
  40718. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  40719. // Add padding to the end of the chunk
  40720. offset += ( GPU_CHUNK_BYTES - chunkStart );
  40721. }
  40722. uniform.offset = offset / bytesPerElement;
  40723. offset += itemSize;
  40724. }
  40725. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  40726. }
  40727. /**
  40728. * Updates this group by updating each uniform object of
  40729. * the internal uniform list. The uniform objects check if their
  40730. * values has actually changed so this method only returns
  40731. * `true` if there is a real value change.
  40732. *
  40733. * @return {boolean} Whether the uniforms have been updated and
  40734. * must be uploaded to the GPU.
  40735. */
  40736. update() {
  40737. let updated = false;
  40738. for ( const uniform of this.uniforms ) {
  40739. if ( this.updateByType( uniform ) === true ) {
  40740. updated = true;
  40741. }
  40742. }
  40743. return updated;
  40744. }
  40745. /**
  40746. * Updates a given uniform by calling an update method matching
  40747. * the uniforms type.
  40748. *
  40749. * @param {Uniform} uniform - The uniform to update.
  40750. * @return {boolean} Whether the uniform has been updated or not.
  40751. */
  40752. updateByType( uniform ) {
  40753. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  40754. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  40755. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  40756. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  40757. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  40758. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  40759. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  40760. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  40761. }
  40762. /**
  40763. * Updates a given Number uniform.
  40764. *
  40765. * @param {NumberUniform} uniform - The Number uniform.
  40766. * @return {boolean} Whether the uniform has been updated or not.
  40767. */
  40768. updateNumber( uniform ) {
  40769. let updated = false;
  40770. const a = this.values;
  40771. const v = uniform.getValue();
  40772. const offset = uniform.offset;
  40773. const type = uniform.getType();
  40774. if ( a[ offset ] !== v ) {
  40775. const b = this._getBufferForType( type );
  40776. b[ offset ] = a[ offset ] = v;
  40777. updated = true;
  40778. }
  40779. return updated;
  40780. }
  40781. /**
  40782. * Updates a given Vector2 uniform.
  40783. *
  40784. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  40785. * @return {boolean} Whether the uniform has been updated or not.
  40786. */
  40787. updateVector2( uniform ) {
  40788. let updated = false;
  40789. const a = this.values;
  40790. const v = uniform.getValue();
  40791. const offset = uniform.offset;
  40792. const type = uniform.getType();
  40793. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  40794. const b = this._getBufferForType( type );
  40795. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40796. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40797. updated = true;
  40798. }
  40799. return updated;
  40800. }
  40801. /**
  40802. * Updates a given Vector3 uniform.
  40803. *
  40804. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  40805. * @return {boolean} Whether the uniform has been updated or not.
  40806. */
  40807. updateVector3( uniform ) {
  40808. let updated = false;
  40809. const a = this.values;
  40810. const v = uniform.getValue();
  40811. const offset = uniform.offset;
  40812. const type = uniform.getType();
  40813. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  40814. const b = this._getBufferForType( type );
  40815. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40816. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40817. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  40818. updated = true;
  40819. }
  40820. return updated;
  40821. }
  40822. /**
  40823. * Updates a given Vector4 uniform.
  40824. *
  40825. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  40826. * @return {boolean} Whether the uniform has been updated or not.
  40827. */
  40828. updateVector4( uniform ) {
  40829. let updated = false;
  40830. const a = this.values;
  40831. const v = uniform.getValue();
  40832. const offset = uniform.offset;
  40833. const type = uniform.getType();
  40834. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  40835. const b = this._getBufferForType( type );
  40836. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40837. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40838. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  40839. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  40840. updated = true;
  40841. }
  40842. return updated;
  40843. }
  40844. /**
  40845. * Updates a given Color uniform.
  40846. *
  40847. * @param {ColorUniform} uniform - The Color uniform.
  40848. * @return {boolean} Whether the uniform has been updated or not.
  40849. */
  40850. updateColor( uniform ) {
  40851. let updated = false;
  40852. const a = this.values;
  40853. const c = uniform.getValue();
  40854. const offset = uniform.offset;
  40855. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  40856. const b = this.buffer;
  40857. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  40858. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  40859. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  40860. updated = true;
  40861. }
  40862. return updated;
  40863. }
  40864. /**
  40865. * Updates a given Matrix3 uniform.
  40866. *
  40867. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  40868. * @return {boolean} Whether the uniform has been updated or not.
  40869. */
  40870. updateMatrix3( uniform ) {
  40871. let updated = false;
  40872. const a = this.values;
  40873. const e = uniform.getValue().elements;
  40874. const offset = uniform.offset;
  40875. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  40876. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  40877. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  40878. const b = this.buffer;
  40879. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  40880. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  40881. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  40882. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  40883. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  40884. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  40885. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  40886. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  40887. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  40888. updated = true;
  40889. }
  40890. return updated;
  40891. }
  40892. /**
  40893. * Updates a given Matrix4 uniform.
  40894. *
  40895. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  40896. * @return {boolean} Whether the uniform has been updated or not.
  40897. */
  40898. updateMatrix4( uniform ) {
  40899. let updated = false;
  40900. const a = this.values;
  40901. const e = uniform.getValue().elements;
  40902. const offset = uniform.offset;
  40903. if ( arraysEqual( a, e, offset ) === false ) {
  40904. const b = this.buffer;
  40905. b.set( e, offset );
  40906. setArray( a, e, offset );
  40907. updated = true;
  40908. }
  40909. return updated;
  40910. }
  40911. /**
  40912. * Returns a typed array that matches the given data type.
  40913. *
  40914. * @param {string} type - The data type.
  40915. * @return {TypedArray} The typed array.
  40916. */
  40917. _getBufferForType( type ) {
  40918. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  40919. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  40920. return this.buffer;
  40921. }
  40922. }
  40923. /**
  40924. * Sets the values of the second array to the first array.
  40925. *
  40926. * @private
  40927. * @param {TypedArray} a - The first array.
  40928. * @param {TypedArray} b - The second array.
  40929. * @param {number} offset - An index offset for the first array.
  40930. */
  40931. function setArray( a, b, offset ) {
  40932. for ( let i = 0, l = b.length; i < l; i ++ ) {
  40933. a[ offset + i ] = b[ i ];
  40934. }
  40935. }
  40936. /**
  40937. * Returns `true` if the given arrays are equal.
  40938. *
  40939. * @private
  40940. * @param {TypedArray} a - The first array.
  40941. * @param {TypedArray} b - The second array.
  40942. * @param {number} offset - An index offset for the first array.
  40943. * @return {boolean} Whether the given arrays are equal or not.
  40944. */
  40945. function arraysEqual( a, b, offset ) {
  40946. for ( let i = 0, l = b.length; i < l; i ++ ) {
  40947. if ( a[ offset + i ] !== b[ i ] ) return false;
  40948. }
  40949. return true;
  40950. }
  40951. let _id$3 = 0;
  40952. /**
  40953. * A special form of uniforms group that represents
  40954. * the individual uniforms as node-based uniforms.
  40955. *
  40956. * @private
  40957. * @augments UniformsGroup
  40958. */
  40959. class NodeUniformsGroup extends UniformsGroup {
  40960. /**
  40961. * Constructs a new node-based uniforms group.
  40962. *
  40963. * @param {string} name - The group's name.
  40964. * @param {UniformGroupNode} groupNode - The uniform group node.
  40965. */
  40966. constructor( name, groupNode ) {
  40967. super( name );
  40968. /**
  40969. * The group's ID.
  40970. *
  40971. * @type {number}
  40972. */
  40973. this.id = _id$3 ++;
  40974. /**
  40975. * The uniform group node.
  40976. *
  40977. * @type {UniformGroupNode}
  40978. */
  40979. this.groupNode = groupNode;
  40980. /**
  40981. * This flag can be used for type testing.
  40982. *
  40983. * @type {boolean}
  40984. * @readonly
  40985. * @default true
  40986. */
  40987. this.isNodeUniformsGroup = true;
  40988. }
  40989. }
  40990. /**
  40991. * Represents a sampler binding type.
  40992. *
  40993. * @private
  40994. * @augments Binding
  40995. */
  40996. class Sampler extends Binding {
  40997. /**
  40998. * Constructs a new sampler.
  40999. *
  41000. * @param {string} name - The samplers's name.
  41001. * @param {?Texture} texture - The texture this binding is referring to.
  41002. */
  41003. constructor( name, texture ) {
  41004. super( name );
  41005. /**
  41006. * This function is called when the texture is disposed.
  41007. * @type {function}
  41008. * @private
  41009. */
  41010. this._onDisposeTexture = () => {
  41011. this.texture = null;
  41012. };
  41013. /**
  41014. * The texture the sampler is referring to.
  41015. *
  41016. * @type {?Texture}
  41017. */
  41018. this.texture = texture;
  41019. /**
  41020. * The binding's version.
  41021. *
  41022. * @type {number}
  41023. */
  41024. this.version = texture ? texture.version : 0;
  41025. /**
  41026. * The binding's generation which is an additional version
  41027. * qualifier.
  41028. *
  41029. * @type {?number}
  41030. * @default null
  41031. */
  41032. this.generation = null;
  41033. /**
  41034. * This flag can be used for type testing.
  41035. *
  41036. * @type {boolean}
  41037. * @readonly
  41038. * @default true
  41039. */
  41040. this.isSampler = true;
  41041. }
  41042. /**
  41043. * Sets the texture of this sampler.
  41044. * @param {?Texture} value - The texture to set.
  41045. */
  41046. set texture( value ) {
  41047. if ( this._texture === value ) return;
  41048. if ( this._texture ) {
  41049. this._texture.removeEventListener( 'dispose', this._onDisposeTexture );
  41050. }
  41051. this._texture = value;
  41052. this.generation = null;
  41053. this.version = 0;
  41054. if ( this._texture ) {
  41055. this._texture.addEventListener( 'dispose', this._onDisposeTexture );
  41056. }
  41057. }
  41058. /**
  41059. * Gets the texture of this sampler.
  41060. * @return {?Texture} The texture.
  41061. */
  41062. get texture() {
  41063. return this._texture;
  41064. }
  41065. /**
  41066. * Updates the binding.
  41067. *
  41068. * @return {boolean} Whether the texture has been updated and must be
  41069. * uploaded to the GPU.
  41070. */
  41071. update() {
  41072. const { texture, version } = this;
  41073. if ( version !== texture.version ) {
  41074. this.version = texture.version;
  41075. return true;
  41076. }
  41077. return false;
  41078. }
  41079. }
  41080. let _id$2 = 0;
  41081. /**
  41082. * Represents a sampled texture binding type.
  41083. *
  41084. * @private
  41085. * @augments Binding
  41086. */
  41087. class SampledTexture extends Sampler {
  41088. /**
  41089. * Constructs a new sampled texture.
  41090. *
  41091. * @param {string} name - The sampled texture's name.
  41092. * @param {?Texture} texture - The texture this binding is referring to.
  41093. */
  41094. constructor( name, texture ) {
  41095. super( name, texture );
  41096. /**
  41097. * This identifier.
  41098. *
  41099. * @type {number}
  41100. */
  41101. this.id = _id$2 ++;
  41102. /**
  41103. * Whether the texture is a storage texture or not.
  41104. *
  41105. * @type {boolean}
  41106. * @default false
  41107. */
  41108. this.store = false;
  41109. /**
  41110. * This flag can be used for type testing.
  41111. *
  41112. * @type {boolean}
  41113. * @readonly
  41114. * @default true
  41115. */
  41116. this.isSampledTexture = true;
  41117. }
  41118. }
  41119. /**
  41120. * A special form of sampled texture binding type.
  41121. * It's texture value is managed by a node object.
  41122. *
  41123. * @private
  41124. * @augments SampledTexture
  41125. */
  41126. class NodeSampledTexture extends SampledTexture {
  41127. /**
  41128. * Constructs a new node-based sampled texture.
  41129. *
  41130. * @param {string} name - The textures's name.
  41131. * @param {TextureNode} textureNode - The texture node.
  41132. * @param {UniformGroupNode} groupNode - The uniform group node.
  41133. * @param {?string} [access=null] - The access type.
  41134. */
  41135. constructor( name, textureNode, groupNode, access = null ) {
  41136. super( name, textureNode ? textureNode.value : null );
  41137. /**
  41138. * The texture node.
  41139. *
  41140. * @type {TextureNode}
  41141. */
  41142. this.textureNode = textureNode;
  41143. /**
  41144. * The uniform group node.
  41145. *
  41146. * @type {UniformGroupNode}
  41147. */
  41148. this.groupNode = groupNode;
  41149. /**
  41150. * The access type.
  41151. *
  41152. * @type {?string}
  41153. * @default null
  41154. */
  41155. this.access = access;
  41156. }
  41157. /**
  41158. * Updates the binding.
  41159. *
  41160. * @return {boolean} Whether the texture has been updated and must be
  41161. * uploaded to the GPU.
  41162. */
  41163. update() {
  41164. const { textureNode } = this;
  41165. if ( this.texture !== textureNode.value ) {
  41166. this.texture = textureNode.value;
  41167. return true;
  41168. }
  41169. return super.update();
  41170. }
  41171. }
  41172. /**
  41173. * A special form of sampled cube texture binding type.
  41174. * It's texture value is managed by a node object.
  41175. *
  41176. * @private
  41177. * @augments NodeSampledTexture
  41178. */
  41179. class NodeSampledCubeTexture extends NodeSampledTexture {
  41180. /**
  41181. * Constructs a new node-based sampled cube texture.
  41182. *
  41183. * @param {string} name - The textures's name.
  41184. * @param {TextureNode} textureNode - The texture node.
  41185. * @param {UniformGroupNode} groupNode - The uniform group node.
  41186. * @param {?string} [access=null] - The access type.
  41187. */
  41188. constructor( name, textureNode, groupNode, access = null ) {
  41189. super( name, textureNode, groupNode, access );
  41190. /**
  41191. * This flag can be used for type testing.
  41192. *
  41193. * @type {boolean}
  41194. * @readonly
  41195. * @default true
  41196. */
  41197. this.isSampledCubeTexture = true;
  41198. }
  41199. }
  41200. /**
  41201. * A special form of sampled 3D texture binding type.
  41202. * It's texture value is managed by a node object.
  41203. *
  41204. * @private
  41205. * @augments NodeSampledTexture
  41206. */
  41207. class NodeSampledTexture3D extends NodeSampledTexture {
  41208. /**
  41209. * Constructs a new node-based sampled 3D texture.
  41210. *
  41211. * @param {string} name - The textures's name.
  41212. * @param {TextureNode} textureNode - The texture node.
  41213. * @param {UniformGroupNode} groupNode - The uniform group node.
  41214. * @param {?string} [access=null] - The access type.
  41215. */
  41216. constructor( name, textureNode, groupNode, access = null ) {
  41217. super( name, textureNode, groupNode, access );
  41218. /**
  41219. * This flag can be used for type testing.
  41220. *
  41221. * @type {boolean}
  41222. * @readonly
  41223. * @default true
  41224. */
  41225. this.isSampledTexture3D = true;
  41226. }
  41227. }
  41228. const glslMethods = {
  41229. textureDimensions: 'textureSize',
  41230. equals: 'equal'
  41231. };
  41232. const precisionLib = {
  41233. low: 'lowp',
  41234. medium: 'mediump',
  41235. high: 'highp'
  41236. };
  41237. const supports$1 = {
  41238. swizzleAssign: true,
  41239. storageBuffer: false
  41240. };
  41241. const interpolationTypeMap = {
  41242. perspective: 'smooth',
  41243. linear: 'noperspective'
  41244. };
  41245. const interpolationModeMap = {
  41246. 'centroid': 'centroid'
  41247. };
  41248. const defaultPrecisions = `
  41249. precision highp float;
  41250. precision highp int;
  41251. precision highp sampler2D;
  41252. precision highp sampler3D;
  41253. precision highp samplerCube;
  41254. precision highp sampler2DArray;
  41255. precision highp usampler2D;
  41256. precision highp usampler3D;
  41257. precision highp usamplerCube;
  41258. precision highp usampler2DArray;
  41259. precision highp isampler2D;
  41260. precision highp isampler3D;
  41261. precision highp isamplerCube;
  41262. precision highp isampler2DArray;
  41263. precision lowp sampler2DShadow;
  41264. precision lowp sampler2DArrayShadow;
  41265. precision lowp samplerCubeShadow;
  41266. `;
  41267. /**
  41268. * A node builder targeting GLSL.
  41269. *
  41270. * This module generates GLSL shader code from node materials and also
  41271. * generates the respective bindings and vertex buffer definitions. These
  41272. * data are later used by the renderer to create render and compute pipelines
  41273. * for render objects.
  41274. *
  41275. * @augments NodeBuilder
  41276. */
  41277. class GLSLNodeBuilder extends NodeBuilder {
  41278. /**
  41279. * Constructs a new GLSL node builder renderer.
  41280. *
  41281. * @param {Object3D} object - The 3D object.
  41282. * @param {Renderer} renderer - The renderer.
  41283. */
  41284. constructor( object, renderer ) {
  41285. super( object, renderer, new GLSLNodeParser() );
  41286. /**
  41287. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  41288. * another dictionary which manages UBOs per group ('render','frame','object').
  41289. *
  41290. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  41291. */
  41292. this.uniformGroups = {};
  41293. /**
  41294. * An array that holds objects defining the varying and attribute data in
  41295. * context of Transform Feedback.
  41296. *
  41297. * @type {Array<Object<string,AttributeNode|string>>}
  41298. */
  41299. this.transforms = [];
  41300. /**
  41301. * A dictionary that holds for each shader stage a Map of used extensions.
  41302. *
  41303. * @type {Object<string,Map<string,Object>>}
  41304. */
  41305. this.extensions = {};
  41306. /**
  41307. * A dictionary that holds for each shader stage an Array of used builtins.
  41308. *
  41309. * @type {Object<string,Array<string>>}
  41310. */
  41311. this.builtins = { vertex: [], fragment: [], compute: [] };
  41312. }
  41313. /**
  41314. * Checks if the given texture requires a manual conversion to the working color space.
  41315. *
  41316. * @param {Texture} texture - The texture to check.
  41317. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  41318. */
  41319. needsToWorkingColorSpace( texture ) {
  41320. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  41321. }
  41322. /**
  41323. * Returns the native shader method name for a given generic name.
  41324. *
  41325. * @param {string} method - The method name to resolve.
  41326. * @return {string} The resolved GLSL method name.
  41327. */
  41328. getMethod( method ) {
  41329. return glslMethods[ method ] || method;
  41330. }
  41331. /**
  41332. * Returns the native snippet for a ternary operation.
  41333. *
  41334. * @param {string} condSnippet - The condition determining which expression gets resolved.
  41335. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  41336. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  41337. * @return {string} The resolved method name.
  41338. */
  41339. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  41340. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  41341. }
  41342. /**
  41343. * Returns the output struct name. Not relevant for GLSL.
  41344. *
  41345. * @return {string}
  41346. */
  41347. getOutputStructName() {
  41348. return '';
  41349. }
  41350. /**
  41351. * Builds the given shader node.
  41352. *
  41353. * @param {ShaderNodeInternal} shaderNode - The shader node.
  41354. * @return {string} The GLSL function code.
  41355. */
  41356. buildFunctionCode( shaderNode ) {
  41357. const layout = shaderNode.layout;
  41358. const flowData = this.flowShaderNode( shaderNode );
  41359. const parameters = [];
  41360. for ( const input of layout.inputs ) {
  41361. parameters.push( this.getType( input.type ) + ' ' + input.name );
  41362. }
  41363. //
  41364. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  41365. ${ flowData.vars }
  41366. ${ flowData.code }
  41367. return ${ flowData.result };
  41368. }`;
  41369. //
  41370. return code;
  41371. }
  41372. /**
  41373. * Setups the Pixel Buffer Object (PBO) for the given storage
  41374. * buffer node.
  41375. *
  41376. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  41377. */
  41378. setupPBO( storageBufferNode ) {
  41379. const attribute = storageBufferNode.value;
  41380. if ( attribute.pbo === undefined ) {
  41381. const originalArray = attribute.array;
  41382. const numElements = attribute.count * attribute.itemSize;
  41383. const { itemSize } = attribute;
  41384. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  41385. let format = isInteger ? RedIntegerFormat : RedFormat;
  41386. if ( itemSize === 2 ) {
  41387. format = isInteger ? RGIntegerFormat : RGFormat;
  41388. } else if ( itemSize === 3 ) {
  41389. format = isInteger ? RGBIntegerFormat : RGBFormat;
  41390. } else if ( itemSize === 4 ) {
  41391. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  41392. }
  41393. const typeMap = {
  41394. Float32Array: FloatType,
  41395. Uint8Array: UnsignedByteType,
  41396. Uint16Array: UnsignedShortType,
  41397. Uint32Array: UnsignedIntType,
  41398. Int8Array: ByteType,
  41399. Int16Array: ShortType,
  41400. Int32Array: IntType,
  41401. Uint8ClampedArray: UnsignedByteType,
  41402. };
  41403. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  41404. let height = Math.ceil( ( numElements / itemSize ) / width );
  41405. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  41406. const newSize = width * height * itemSize;
  41407. const newArray = new originalArray.constructor( newSize );
  41408. newArray.set( originalArray, 0 );
  41409. attribute.array = newArray;
  41410. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  41411. pboTexture.needsUpdate = true;
  41412. pboTexture.isPBOTexture = true;
  41413. const pbo = new TextureNode( pboTexture, null, null );
  41414. pbo.setPrecision( 'high' );
  41415. attribute.pboNode = pbo;
  41416. attribute.pbo = pbo.value;
  41417. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  41418. }
  41419. }
  41420. /**
  41421. * Returns a GLSL snippet that represents the property name of the given node.
  41422. *
  41423. * @param {Node} node - The node.
  41424. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  41425. * @return {string} The property name.
  41426. */
  41427. getPropertyName( node, shaderStage = this.shaderStage ) {
  41428. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  41429. return shaderStage.charAt( 0 ) + '_' + node.name;
  41430. }
  41431. return super.getPropertyName( node, shaderStage );
  41432. }
  41433. /**
  41434. * Setups the Pixel Buffer Object (PBO) for the given storage
  41435. * buffer node.
  41436. *
  41437. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  41438. * @return {string} The property name.
  41439. */
  41440. generatePBO( storageArrayElementNode ) {
  41441. const { node, indexNode } = storageArrayElementNode;
  41442. const attribute = node.value;
  41443. if ( this.renderer.backend.has( attribute ) ) {
  41444. const attributeData = this.renderer.backend.get( attribute );
  41445. attributeData.pbo = attribute.pbo;
  41446. }
  41447. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  41448. const textureName = this.getPropertyName( nodeUniform );
  41449. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  41450. const indexSnippet = indexNode.build( this, 'uint' );
  41451. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  41452. let propertyName = elementNodeData.propertyName;
  41453. if ( propertyName === undefined ) {
  41454. // property element
  41455. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  41456. propertyName = this.getPropertyName( nodeVar );
  41457. // property size
  41458. const bufferNodeData = this.getDataFromNode( node );
  41459. let propertySizeName = bufferNodeData.propertySizeName;
  41460. if ( propertySizeName === undefined ) {
  41461. propertySizeName = propertyName + 'Size';
  41462. this.getVarFromNode( node, propertySizeName, 'uint' );
  41463. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  41464. bufferNodeData.propertySizeName = propertySizeName;
  41465. }
  41466. //
  41467. const { itemSize } = attribute;
  41468. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  41469. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  41470. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  41471. //
  41472. let prefix = 'vec4';
  41473. if ( attribute.pbo.type === UnsignedIntType ) {
  41474. prefix = 'uvec4';
  41475. } else if ( attribute.pbo.type === IntType ) {
  41476. prefix = 'ivec4';
  41477. }
  41478. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  41479. elementNodeData.propertyName = propertyName;
  41480. }
  41481. return propertyName;
  41482. }
  41483. /**
  41484. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  41485. *
  41486. * @param {Texture} texture - The texture.
  41487. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41488. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41489. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  41490. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  41491. * @return {string} The GLSL snippet.
  41492. */
  41493. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  41494. if ( depthSnippet ) {
  41495. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  41496. } else {
  41497. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  41498. }
  41499. }
  41500. /**
  41501. * Generates the GLSL snippet for sampling/loading the given texture.
  41502. *
  41503. * @param {Texture} texture - The texture.
  41504. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41505. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41506. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  41507. * @return {string} The GLSL snippet.
  41508. */
  41509. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  41510. if ( texture.isDepthTexture ) {
  41511. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  41512. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  41513. } else {
  41514. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  41515. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  41516. }
  41517. }
  41518. /**
  41519. * Generates the GLSL snippet when sampling textures with explicit mip level.
  41520. *
  41521. * @param {Texture} texture - The texture.
  41522. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41523. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41524. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  41525. * @return {string} The GLSL snippet.
  41526. */
  41527. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  41528. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  41529. }
  41530. /**
  41531. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  41532. *
  41533. * @param {Texture} texture - The texture.
  41534. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41535. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41536. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  41537. * @return {string} The GLSL snippet.
  41538. */
  41539. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  41540. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  41541. }
  41542. /**
  41543. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  41544. *
  41545. * @param {Texture} texture - The texture.
  41546. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41547. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41548. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  41549. * @return {string} The GLSL snippet.
  41550. */
  41551. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  41552. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  41553. }
  41554. /**
  41555. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  41556. * against a reference value.
  41557. *
  41558. * @param {Texture} texture - The texture.
  41559. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41560. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41561. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  41562. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  41563. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  41564. * @return {string} The GLSL snippet.
  41565. */
  41566. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41567. if ( shaderStage === 'fragment' ) {
  41568. if ( depthSnippet ) {
  41569. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  41570. }
  41571. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  41572. } else {
  41573. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  41574. }
  41575. }
  41576. /**
  41577. * Returns the variables of the given shader stage as a GLSL string.
  41578. *
  41579. * @param {string} shaderStage - The shader stage.
  41580. * @return {string} The GLSL snippet that defines the variables.
  41581. */
  41582. getVars( shaderStage ) {
  41583. const snippets = [];
  41584. const vars = this.vars[ shaderStage ];
  41585. if ( vars !== undefined ) {
  41586. for ( const variable of vars ) {
  41587. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  41588. }
  41589. }
  41590. return snippets.join( '\n\t' );
  41591. }
  41592. /**
  41593. * Returns the uniforms of the given shader stage as a GLSL string.
  41594. *
  41595. * @param {string} shaderStage - The shader stage.
  41596. * @return {string} The GLSL snippet that defines the uniforms.
  41597. */
  41598. getUniforms( shaderStage ) {
  41599. const uniforms = this.uniforms[ shaderStage ];
  41600. const bindingSnippets = [];
  41601. const uniformGroups = {};
  41602. for ( const uniform of uniforms ) {
  41603. let snippet = null;
  41604. let group = false;
  41605. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  41606. const texture = uniform.node.value;
  41607. let typePrefix = '';
  41608. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  41609. if ( texture.type === UnsignedIntType ) {
  41610. typePrefix = 'u';
  41611. } else if ( texture.type === IntType ) {
  41612. typePrefix = 'i';
  41613. }
  41614. }
  41615. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  41616. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  41617. } else if ( texture.compareFunction ) {
  41618. if ( texture.isArrayTexture === true ) {
  41619. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  41620. } else {
  41621. snippet = `sampler2DShadow ${ uniform.name };`;
  41622. }
  41623. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  41624. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  41625. } else {
  41626. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  41627. }
  41628. } else if ( uniform.type === 'cubeTexture' ) {
  41629. snippet = `samplerCube ${ uniform.name };`;
  41630. } else if ( uniform.type === 'buffer' ) {
  41631. const bufferNode = uniform.node;
  41632. const bufferType = this.getType( bufferNode.bufferType );
  41633. const bufferCount = bufferNode.bufferCount;
  41634. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  41635. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  41636. } else {
  41637. const vectorType = this.getVectorType( uniform.type );
  41638. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  41639. group = true;
  41640. }
  41641. const precision = uniform.node.precision;
  41642. if ( precision !== null ) {
  41643. snippet = precisionLib[ precision ] + ' ' + snippet;
  41644. }
  41645. if ( group ) {
  41646. snippet = '\t' + snippet;
  41647. const groupName = uniform.groupNode.name;
  41648. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  41649. groupSnippets.push( snippet );
  41650. } else {
  41651. snippet = 'uniform ' + snippet;
  41652. bindingSnippets.push( snippet );
  41653. }
  41654. }
  41655. let output = '';
  41656. for ( const name in uniformGroups ) {
  41657. const groupSnippets = uniformGroups[ name ];
  41658. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  41659. }
  41660. output += bindingSnippets.join( '\n' );
  41661. return output;
  41662. }
  41663. /**
  41664. * Returns the type for a given buffer attribute.
  41665. *
  41666. * @param {BufferAttribute} attribute - The buffer attribute.
  41667. * @return {string} The type.
  41668. */
  41669. getTypeFromAttribute( attribute ) {
  41670. let nodeType = super.getTypeFromAttribute( attribute );
  41671. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  41672. let dataAttribute = attribute;
  41673. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  41674. const array = dataAttribute.array;
  41675. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  41676. nodeType = nodeType.slice( 1 );
  41677. }
  41678. }
  41679. return nodeType;
  41680. }
  41681. /**
  41682. * Returns the shader attributes of the given shader stage as a GLSL string.
  41683. *
  41684. * @param {string} shaderStage - The shader stage.
  41685. * @return {string} The GLSL snippet that defines the shader attributes.
  41686. */
  41687. getAttributes( shaderStage ) {
  41688. let snippet = '';
  41689. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41690. const attributes = this.getAttributesArray();
  41691. let location = 0;
  41692. for ( const attribute of attributes ) {
  41693. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  41694. }
  41695. }
  41696. return snippet;
  41697. }
  41698. /**
  41699. * Returns the members of the given struct type node as a GLSL string.
  41700. *
  41701. * @param {StructTypeNode} struct - The struct type node.
  41702. * @return {string} The GLSL snippet that defines the struct members.
  41703. */
  41704. getStructMembers( struct ) {
  41705. const snippets = [];
  41706. for ( const member of struct.members ) {
  41707. snippets.push( `\t${ member.type } ${ member.name };` );
  41708. }
  41709. return snippets.join( '\n' );
  41710. }
  41711. /**
  41712. * Returns the structs of the given shader stage as a GLSL string.
  41713. *
  41714. * @param {string} shaderStage - The shader stage.
  41715. * @return {string} The GLSL snippet that defines the structs.
  41716. */
  41717. getStructs( shaderStage ) {
  41718. const snippets = [];
  41719. const structs = this.structs[ shaderStage ];
  41720. const outputSnippet = [];
  41721. for ( const struct of structs ) {
  41722. if ( struct.output ) {
  41723. for ( const member of struct.members ) {
  41724. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  41725. }
  41726. } else {
  41727. let snippet = 'struct ' + struct.name + ' {\n';
  41728. snippet += this.getStructMembers( struct );
  41729. snippet += '\n};\n';
  41730. snippets.push( snippet );
  41731. }
  41732. }
  41733. if ( outputSnippet.length === 0 ) {
  41734. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  41735. }
  41736. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  41737. }
  41738. /**
  41739. * Returns the varyings of the given shader stage as a GLSL string.
  41740. *
  41741. * @param {string} shaderStage - The shader stage.
  41742. * @return {string} The GLSL snippet that defines the varyings.
  41743. */
  41744. getVaryings( shaderStage ) {
  41745. let snippet = '';
  41746. const varyings = this.varyings;
  41747. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41748. for ( const varying of varyings ) {
  41749. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  41750. const type = this.getType( varying.type );
  41751. if ( varying.needsInterpolation ) {
  41752. if ( varying.interpolationType ) {
  41753. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  41754. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  41755. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  41756. } else {
  41757. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  41758. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  41759. }
  41760. } else {
  41761. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  41762. }
  41763. }
  41764. } else if ( shaderStage === 'fragment' ) {
  41765. for ( const varying of varyings ) {
  41766. if ( varying.needsInterpolation ) {
  41767. const type = this.getType( varying.type );
  41768. if ( varying.interpolationType ) {
  41769. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  41770. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  41771. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  41772. } else {
  41773. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  41774. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  41775. }
  41776. }
  41777. }
  41778. }
  41779. for ( const builtin of this.builtins[ shaderStage ] ) {
  41780. snippet += `${builtin};\n`;
  41781. }
  41782. return snippet;
  41783. }
  41784. /**
  41785. * Returns the vertex index builtin.
  41786. *
  41787. * @return {string} The vertex index.
  41788. */
  41789. getVertexIndex() {
  41790. return 'uint( gl_VertexID )';
  41791. }
  41792. /**
  41793. * Returns the instance index builtin.
  41794. *
  41795. * @return {string} The instance index.
  41796. */
  41797. getInstanceIndex() {
  41798. return 'uint( gl_InstanceID )';
  41799. }
  41800. /**
  41801. * Returns the invocation local index builtin.
  41802. *
  41803. * @return {string} The invocation local index.
  41804. */
  41805. getInvocationLocalIndex() {
  41806. const workgroupSize = this.object.workgroupSize;
  41807. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  41808. return `uint( gl_InstanceID ) % ${size}u`;
  41809. }
  41810. /**
  41811. * Returns the draw index builtin.
  41812. *
  41813. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  41814. */
  41815. getDrawIndex() {
  41816. const extensions = this.renderer.backend.extensions;
  41817. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  41818. return 'uint( gl_DrawID )';
  41819. }
  41820. return null;
  41821. }
  41822. /**
  41823. * Returns the front facing builtin.
  41824. *
  41825. * @return {string} The front facing builtin.
  41826. */
  41827. getFrontFacing() {
  41828. return 'gl_FrontFacing';
  41829. }
  41830. /**
  41831. * Returns the frag coord builtin.
  41832. *
  41833. * @return {string} The frag coord builtin.
  41834. */
  41835. getFragCoord() {
  41836. return 'gl_FragCoord.xy';
  41837. }
  41838. /**
  41839. * Returns the frag depth builtin.
  41840. *
  41841. * @return {string} The frag depth builtin.
  41842. */
  41843. getFragDepth() {
  41844. return 'gl_FragDepth';
  41845. }
  41846. /**
  41847. * Enables the given extension.
  41848. *
  41849. * @param {string} name - The extension name.
  41850. * @param {string} behavior - The extension behavior.
  41851. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  41852. */
  41853. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  41854. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  41855. if ( map.has( name ) === false ) {
  41856. map.set( name, {
  41857. name,
  41858. behavior
  41859. } );
  41860. }
  41861. }
  41862. /**
  41863. * Returns the enabled extensions of the given shader stage as a GLSL string.
  41864. *
  41865. * @param {string} shaderStage - The shader stage.
  41866. * @return {string} The GLSL snippet that defines the enabled extensions.
  41867. */
  41868. getExtensions( shaderStage ) {
  41869. const snippets = [];
  41870. if ( shaderStage === 'vertex' ) {
  41871. const ext = this.renderer.backend.extensions;
  41872. const isBatchedMesh = this.object.isBatchedMesh;
  41873. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  41874. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  41875. }
  41876. }
  41877. const extensions = this.extensions[ shaderStage ];
  41878. if ( extensions !== undefined ) {
  41879. for ( const { name, behavior } of extensions.values() ) {
  41880. snippets.push( `#extension ${name} : ${behavior}` );
  41881. }
  41882. }
  41883. return snippets.join( '\n' );
  41884. }
  41885. /**
  41886. * Returns the clip distances builtin.
  41887. *
  41888. * @return {string} The clip distances builtin.
  41889. */
  41890. getClipDistance() {
  41891. return 'gl_ClipDistance';
  41892. }
  41893. /**
  41894. * Whether the requested feature is available or not.
  41895. *
  41896. * @param {string} name - The requested feature.
  41897. * @return {boolean} Whether the requested feature is supported or not.
  41898. */
  41899. isAvailable( name ) {
  41900. let result = supports$1[ name ];
  41901. if ( result === undefined ) {
  41902. let extensionName;
  41903. result = false;
  41904. switch ( name ) {
  41905. case 'float32Filterable':
  41906. extensionName = 'OES_texture_float_linear';
  41907. break;
  41908. case 'clipDistance':
  41909. extensionName = 'WEBGL_clip_cull_distance';
  41910. break;
  41911. }
  41912. if ( extensionName !== undefined ) {
  41913. const extensions = this.renderer.backend.extensions;
  41914. if ( extensions.has( extensionName ) ) {
  41915. extensions.get( extensionName );
  41916. result = true;
  41917. }
  41918. }
  41919. supports$1[ name ] = result;
  41920. }
  41921. return result;
  41922. }
  41923. /**
  41924. * Whether to flip texture data along its vertical axis or not.
  41925. *
  41926. * @return {boolean} Returns always `true` in context of GLSL.
  41927. */
  41928. isFlipY() {
  41929. return true;
  41930. }
  41931. /**
  41932. * Enables hardware clipping.
  41933. *
  41934. * @param {string} planeCount - The clipping plane count.
  41935. */
  41936. enableHardwareClipping( planeCount ) {
  41937. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  41938. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  41939. }
  41940. /**
  41941. * Enables multiview.
  41942. */
  41943. enableMultiview() {
  41944. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  41945. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  41946. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  41947. }
  41948. /**
  41949. * Registers a transform in context of Transform Feedback.
  41950. *
  41951. * @param {string} varyingName - The varying name.
  41952. * @param {AttributeNode} attributeNode - The attribute node.
  41953. */
  41954. registerTransform( varyingName, attributeNode ) {
  41955. this.transforms.push( { varyingName, attributeNode } );
  41956. }
  41957. /**
  41958. * Returns the transforms of the given shader stage as a GLSL string.
  41959. *
  41960. * @param {string} shaderStage - The shader stage.
  41961. * @return {string} The GLSL snippet that defines the transforms.
  41962. */
  41963. getTransforms( /* shaderStage */ ) {
  41964. const transforms = this.transforms;
  41965. let snippet = '';
  41966. for ( let i = 0; i < transforms.length; i ++ ) {
  41967. const transform = transforms[ i ];
  41968. const attributeName = this.getPropertyName( transform.attributeNode );
  41969. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  41970. }
  41971. return snippet;
  41972. }
  41973. /**
  41974. * Returns a GLSL struct based on the given name and variables.
  41975. *
  41976. * @private
  41977. * @param {string} name - The struct name.
  41978. * @param {string} vars - The struct variables.
  41979. * @return {string} The GLSL snippet representing a struct.
  41980. */
  41981. _getGLSLUniformStruct( name, vars ) {
  41982. return `
  41983. layout( std140 ) uniform ${name} {
  41984. ${vars}
  41985. };`;
  41986. }
  41987. /**
  41988. * Returns a GLSL vertex shader based on the given shader data.
  41989. *
  41990. * @private
  41991. * @param {Object} shaderData - The shader data.
  41992. * @return {string} The vertex shader.
  41993. */
  41994. _getGLSLVertexCode( shaderData ) {
  41995. return `#version 300 es
  41996. ${ this.getSignature() }
  41997. // extensions
  41998. ${shaderData.extensions}
  41999. // precision
  42000. ${ defaultPrecisions }
  42001. // uniforms
  42002. ${shaderData.uniforms}
  42003. // varyings
  42004. ${shaderData.varyings}
  42005. // attributes
  42006. ${shaderData.attributes}
  42007. // codes
  42008. ${shaderData.codes}
  42009. void main() {
  42010. // vars
  42011. ${shaderData.vars}
  42012. // transforms
  42013. ${shaderData.transforms}
  42014. // flow
  42015. ${shaderData.flow}
  42016. gl_PointSize = 1.0;
  42017. }
  42018. `;
  42019. }
  42020. /**
  42021. * Returns a GLSL fragment shader based on the given shader data.
  42022. *
  42023. * @private
  42024. * @param {Object} shaderData - The shader data.
  42025. * @return {string} The vertex shader.
  42026. */
  42027. _getGLSLFragmentCode( shaderData ) {
  42028. return `#version 300 es
  42029. ${ this.getSignature() }
  42030. // extensions
  42031. ${shaderData.extensions}
  42032. // precision
  42033. ${ defaultPrecisions }
  42034. // uniforms
  42035. ${shaderData.uniforms}
  42036. // varyings
  42037. ${shaderData.varyings}
  42038. // codes
  42039. ${shaderData.codes}
  42040. // structs
  42041. ${shaderData.structs}
  42042. void main() {
  42043. // vars
  42044. ${shaderData.vars}
  42045. // flow
  42046. ${shaderData.flow}
  42047. }
  42048. `;
  42049. }
  42050. /**
  42051. * Controls the code build of the shader stages.
  42052. */
  42053. buildCode() {
  42054. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  42055. this.sortBindingGroups();
  42056. for ( const shaderStage in shadersData ) {
  42057. let flow = '// code\n\n';
  42058. flow += this.flowCode[ shaderStage ];
  42059. const flowNodes = this.flowNodes[ shaderStage ];
  42060. const mainNode = flowNodes[ flowNodes.length - 1 ];
  42061. for ( const node of flowNodes ) {
  42062. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  42063. const slotName = node.name;
  42064. if ( slotName ) {
  42065. if ( flow.length > 0 ) flow += '\n';
  42066. flow += `\t// flow -> ${ slotName }\n\t`;
  42067. }
  42068. flow += `${ flowSlotData.code }\n\t`;
  42069. if ( node === mainNode && shaderStage !== 'compute' ) {
  42070. flow += '// result\n\t';
  42071. if ( shaderStage === 'vertex' ) {
  42072. flow += 'gl_Position = ';
  42073. flow += `${ flowSlotData.result };`;
  42074. } else if ( shaderStage === 'fragment' ) {
  42075. if ( ! node.outputNode.isOutputStructNode ) {
  42076. flow += 'fragColor = ';
  42077. flow += `${ flowSlotData.result };`;
  42078. }
  42079. }
  42080. }
  42081. }
  42082. const stageData = shadersData[ shaderStage ];
  42083. stageData.extensions = this.getExtensions( shaderStage );
  42084. stageData.uniforms = this.getUniforms( shaderStage );
  42085. stageData.attributes = this.getAttributes( shaderStage );
  42086. stageData.varyings = this.getVaryings( shaderStage );
  42087. stageData.vars = this.getVars( shaderStage );
  42088. stageData.structs = this.getStructs( shaderStage );
  42089. stageData.codes = this.getCodes( shaderStage );
  42090. stageData.transforms = this.getTransforms( shaderStage );
  42091. stageData.flow = flow;
  42092. }
  42093. if ( this.material !== null ) {
  42094. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  42095. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  42096. } else {
  42097. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  42098. }
  42099. }
  42100. /**
  42101. * This method is one of the more important ones since it's responsible
  42102. * for generating a matching binding instance for the given uniform node.
  42103. *
  42104. * These bindings are later used in the renderer to create bind groups
  42105. * and layouts.
  42106. *
  42107. * @param {UniformNode} node - The uniform node.
  42108. * @param {string} type - The node data type.
  42109. * @param {string} shaderStage - The shader stage.
  42110. * @param {?string} [name=null] - An optional uniform name.
  42111. * @return {NodeUniform} The node uniform object.
  42112. */
  42113. getUniformFromNode( node, type, shaderStage, name = null ) {
  42114. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42115. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42116. let uniformGPU = nodeData.uniformGPU;
  42117. if ( uniformGPU === undefined ) {
  42118. const group = node.groupNode;
  42119. const groupName = group.name;
  42120. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42121. if ( type === 'texture' ) {
  42122. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  42123. bindings.push( uniformGPU );
  42124. } else if ( type === 'cubeTexture' ) {
  42125. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  42126. bindings.push( uniformGPU );
  42127. } else if ( type === 'texture3D' ) {
  42128. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  42129. bindings.push( uniformGPU );
  42130. } else if ( type === 'buffer' ) {
  42131. node.name = `NodeBuffer_${ node.id }`;
  42132. uniformNode.name = `buffer${ node.id }`;
  42133. const buffer = new NodeUniformBuffer( node, group );
  42134. buffer.name = node.name;
  42135. bindings.push( buffer );
  42136. uniformGPU = buffer;
  42137. } else {
  42138. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42139. let uniformsGroup = uniformsStage[ groupName ];
  42140. if ( uniformsGroup === undefined ) {
  42141. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  42142. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42143. uniformsStage[ groupName ] = uniformsGroup;
  42144. bindings.push( uniformsGroup );
  42145. }
  42146. uniformGPU = this.getNodeUniform( uniformNode, type );
  42147. uniformsGroup.addUniform( uniformGPU );
  42148. }
  42149. nodeData.uniformGPU = uniformGPU;
  42150. }
  42151. return uniformNode;
  42152. }
  42153. }
  42154. let _vector2 = null;
  42155. let _color4 = null;
  42156. /**
  42157. * Most of the rendering related logic is implemented in the
  42158. * {@link Renderer} module and related management components.
  42159. * Sometimes it is required though to execute commands which are
  42160. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  42161. * This abstract base class defines an interface that encapsulates
  42162. * all backend-related logic. Derived classes for each backend must
  42163. * implement the interface.
  42164. *
  42165. * @abstract
  42166. * @private
  42167. */
  42168. class Backend {
  42169. /**
  42170. * Constructs a new backend.
  42171. *
  42172. * @param {Object} parameters - An object holding parameters for the backend.
  42173. */
  42174. constructor( parameters = {} ) {
  42175. /**
  42176. * The parameters of the backend.
  42177. *
  42178. * @type {Object}
  42179. */
  42180. this.parameters = Object.assign( {}, parameters );
  42181. /**
  42182. * This weak map holds backend-specific data of objects
  42183. * like textures, attributes or render targets.
  42184. *
  42185. * @type {WeakMap}
  42186. */
  42187. this.data = new WeakMap();
  42188. /**
  42189. * A reference to the renderer.
  42190. *
  42191. * @type {?Renderer}
  42192. * @default null
  42193. */
  42194. this.renderer = null;
  42195. /**
  42196. * A reference to the canvas element the renderer is drawing to.
  42197. *
  42198. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  42199. * @default null
  42200. */
  42201. this.domElement = null;
  42202. /**
  42203. * A reference to the timestamp query pool.
  42204. *
  42205. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  42206. */
  42207. this.timestampQueryPool = {
  42208. 'render': null,
  42209. 'compute': null
  42210. };
  42211. /**
  42212. * Whether to track timestamps with a Timestamp Query API or not.
  42213. *
  42214. * @type {boolean}
  42215. * @default false
  42216. */
  42217. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42218. }
  42219. /**
  42220. * Initializes the backend so it is ready for usage. Concrete backends
  42221. * are supposed to implement their rendering context creation and related
  42222. * operations in this method.
  42223. *
  42224. * @async
  42225. * @param {Renderer} renderer - The renderer.
  42226. * @return {Promise} A Promise that resolves when the backend has been initialized.
  42227. */
  42228. async init( renderer ) {
  42229. this.renderer = renderer;
  42230. }
  42231. /**
  42232. * The coordinate system of the backend.
  42233. *
  42234. * @abstract
  42235. * @type {number}
  42236. * @readonly
  42237. */
  42238. get coordinateSystem() {}
  42239. // render context
  42240. /**
  42241. * This method is executed at the beginning of a render call and
  42242. * can be used by the backend to prepare the state for upcoming
  42243. * draw calls.
  42244. *
  42245. * @abstract
  42246. * @param {RenderContext} renderContext - The render context.
  42247. */
  42248. beginRender( /*renderContext*/ ) {}
  42249. /**
  42250. * This method is executed at the end of a render call and
  42251. * can be used by the backend to finalize work after draw
  42252. * calls.
  42253. *
  42254. * @abstract
  42255. * @param {RenderContext} renderContext - The render context.
  42256. */
  42257. finishRender( /*renderContext*/ ) {}
  42258. /**
  42259. * This method is executed at the beginning of a compute call and
  42260. * can be used by the backend to prepare the state for upcoming
  42261. * compute tasks.
  42262. *
  42263. * @abstract
  42264. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42265. */
  42266. beginCompute( /*computeGroup*/ ) {}
  42267. /**
  42268. * This method is executed at the end of a compute call and
  42269. * can be used by the backend to finalize work after compute
  42270. * tasks.
  42271. *
  42272. * @abstract
  42273. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42274. */
  42275. finishCompute( /*computeGroup*/ ) {}
  42276. // render object
  42277. /**
  42278. * Executes a draw command for the given render object.
  42279. *
  42280. * @abstract
  42281. * @param {RenderObject} renderObject - The render object to draw.
  42282. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  42283. */
  42284. draw( /*renderObject, info*/ ) { }
  42285. // compute node
  42286. /**
  42287. * Executes a compute command for the given compute node.
  42288. *
  42289. * @abstract
  42290. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  42291. * @param {Node} computeNode - The compute node.
  42292. * @param {Array<BindGroup>} bindings - The bindings.
  42293. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42294. */
  42295. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  42296. // program
  42297. /**
  42298. * Creates a shader program from the given programmable stage.
  42299. *
  42300. * @abstract
  42301. * @param {ProgrammableStage} program - The programmable stage.
  42302. */
  42303. createProgram( /*program*/ ) { }
  42304. /**
  42305. * Destroys the shader program of the given programmable stage.
  42306. *
  42307. * @abstract
  42308. * @param {ProgrammableStage} program - The programmable stage.
  42309. */
  42310. destroyProgram( /*program*/ ) { }
  42311. // bindings
  42312. /**
  42313. * Creates bindings from the given bind group definition.
  42314. *
  42315. * @abstract
  42316. * @param {BindGroup} bindGroup - The bind group.
  42317. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42318. * @param {number} cacheIndex - The cache index.
  42319. * @param {number} version - The version.
  42320. */
  42321. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  42322. /**
  42323. * Updates the given bind group definition.
  42324. *
  42325. * @abstract
  42326. * @param {BindGroup} bindGroup - The bind group.
  42327. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42328. * @param {number} cacheIndex - The cache index.
  42329. * @param {number} version - The version.
  42330. */
  42331. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  42332. /**
  42333. * Updates a buffer binding.
  42334. *
  42335. * @abstract
  42336. * @param {Buffer} binding - The buffer binding to update.
  42337. */
  42338. updateBinding( /*binding*/ ) { }
  42339. // pipeline
  42340. /**
  42341. * Creates a render pipeline for the given render object.
  42342. *
  42343. * @abstract
  42344. * @param {RenderObject} renderObject - The render object.
  42345. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  42346. */
  42347. createRenderPipeline( /*renderObject, promises*/ ) { }
  42348. /**
  42349. * Creates a compute pipeline for the given compute node.
  42350. *
  42351. * @abstract
  42352. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42353. * @param {Array<BindGroup>} bindings - The bindings.
  42354. */
  42355. createComputePipeline( /*computePipeline, bindings*/ ) { }
  42356. // cache key
  42357. /**
  42358. * Returns `true` if the render pipeline requires an update.
  42359. *
  42360. * @abstract
  42361. * @param {RenderObject} renderObject - The render object.
  42362. * @return {boolean} Whether the render pipeline requires an update or not.
  42363. */
  42364. needsRenderUpdate( /*renderObject*/ ) { }
  42365. /**
  42366. * Returns a cache key that is used to identify render pipelines.
  42367. *
  42368. * @abstract
  42369. * @param {RenderObject} renderObject - The render object.
  42370. * @return {string} The cache key.
  42371. */
  42372. getRenderCacheKey( /*renderObject*/ ) { }
  42373. // node builder
  42374. /**
  42375. * Returns a node builder for the given render object.
  42376. *
  42377. * @abstract
  42378. * @param {RenderObject} renderObject - The render object.
  42379. * @param {Renderer} renderer - The renderer.
  42380. * @return {NodeBuilder} The node builder.
  42381. */
  42382. createNodeBuilder( /*renderObject, renderer*/ ) { }
  42383. // textures
  42384. /**
  42385. * Creates a GPU sampler for the given texture.
  42386. *
  42387. * @abstract
  42388. * @param {Texture} texture - The texture to create the sampler for.
  42389. */
  42390. createSampler( /*texture*/ ) { }
  42391. /**
  42392. * Destroys the GPU sampler for the given texture.
  42393. *
  42394. * @abstract
  42395. * @param {Texture} texture - The texture to destroy the sampler for.
  42396. */
  42397. destroySampler( /*texture*/ ) {}
  42398. /**
  42399. * Creates a default texture for the given texture that can be used
  42400. * as a placeholder until the actual texture is ready for usage.
  42401. *
  42402. * @abstract
  42403. * @param {Texture} texture - The texture to create a default texture for.
  42404. */
  42405. createDefaultTexture( /*texture*/ ) { }
  42406. /**
  42407. * Defines a texture on the GPU for the given texture object.
  42408. *
  42409. * @abstract
  42410. * @param {Texture} texture - The texture.
  42411. * @param {Object} [options={}] - Optional configuration parameter.
  42412. */
  42413. createTexture( /*texture, options={}*/ ) { }
  42414. /**
  42415. * Uploads the updated texture data to the GPU.
  42416. *
  42417. * @abstract
  42418. * @param {Texture} texture - The texture.
  42419. * @param {Object} [options={}] - Optional configuration parameter.
  42420. */
  42421. updateTexture( /*texture, options = {}*/ ) { }
  42422. /**
  42423. * Generates mipmaps for the given texture.
  42424. *
  42425. * @abstract
  42426. * @param {Texture} texture - The texture.
  42427. */
  42428. generateMipmaps( /*texture*/ ) { }
  42429. /**
  42430. * Destroys the GPU data for the given texture object.
  42431. *
  42432. * @abstract
  42433. * @param {Texture} texture - The texture.
  42434. */
  42435. destroyTexture( /*texture*/ ) { }
  42436. /**
  42437. * Returns texture data as a typed array.
  42438. *
  42439. * @abstract
  42440. * @async
  42441. * @param {Texture} texture - The texture to copy.
  42442. * @param {number} x - The x coordinate of the copy origin.
  42443. * @param {number} y - The y coordinate of the copy origin.
  42444. * @param {number} width - The width of the copy.
  42445. * @param {number} height - The height of the copy.
  42446. * @param {number} faceIndex - The face index.
  42447. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42448. */
  42449. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  42450. /**
  42451. * Copies data of the given source texture to the given destination texture.
  42452. *
  42453. * @abstract
  42454. * @param {Texture} srcTexture - The source texture.
  42455. * @param {Texture} dstTexture - The destination texture.
  42456. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  42457. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42458. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42459. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42460. */
  42461. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  42462. /**
  42463. * Copies the current bound framebuffer to the given texture.
  42464. *
  42465. * @abstract
  42466. * @param {Texture} texture - The destination texture.
  42467. * @param {RenderContext} renderContext - The render context.
  42468. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42469. */
  42470. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  42471. // attributes
  42472. /**
  42473. * Creates the GPU buffer of a shader attribute.
  42474. *
  42475. * @abstract
  42476. * @param {BufferAttribute} attribute - The buffer attribute.
  42477. */
  42478. createAttribute( /*attribute*/ ) { }
  42479. /**
  42480. * Creates the GPU buffer of an indexed shader attribute.
  42481. *
  42482. * @abstract
  42483. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  42484. */
  42485. createIndexAttribute( /*attribute*/ ) { }
  42486. /**
  42487. * Creates the GPU buffer of a storage attribute.
  42488. *
  42489. * @abstract
  42490. * @param {BufferAttribute} attribute - The buffer attribute.
  42491. */
  42492. createStorageAttribute( /*attribute*/ ) { }
  42493. /**
  42494. * Updates the GPU buffer of a shader attribute.
  42495. *
  42496. * @abstract
  42497. * @param {BufferAttribute} attribute - The buffer attribute to update.
  42498. */
  42499. updateAttribute( /*attribute*/ ) { }
  42500. /**
  42501. * Destroys the GPU buffer of a shader attribute.
  42502. *
  42503. * @abstract
  42504. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  42505. */
  42506. destroyAttribute( /*attribute*/ ) { }
  42507. // canvas
  42508. /**
  42509. * Returns the backend's rendering context.
  42510. *
  42511. * @abstract
  42512. * @return {Object} The rendering context.
  42513. */
  42514. getContext() { }
  42515. /**
  42516. * Backends can use this method if they have to run
  42517. * logic when the renderer gets resized.
  42518. *
  42519. * @abstract
  42520. */
  42521. updateSize() { }
  42522. /**
  42523. * Updates the viewport with the values from the given render context.
  42524. *
  42525. * @abstract
  42526. * @param {RenderContext} renderContext - The render context.
  42527. */
  42528. updateViewport( /*renderContext*/ ) {}
  42529. // utils
  42530. /**
  42531. * Returns `true` if the given 3D object is fully occluded by other
  42532. * 3D objects in the scene. Backends must implement this method by using
  42533. * a Occlusion Query API.
  42534. *
  42535. * @abstract
  42536. * @param {RenderContext} renderContext - The render context.
  42537. * @param {Object3D} object - The 3D object to test.
  42538. * @return {boolean} Whether the 3D object is fully occluded or not.
  42539. */
  42540. isOccluded( /*renderContext, object*/ ) {}
  42541. /**
  42542. * Resolves the time stamp for the given render context and type.
  42543. *
  42544. * @async
  42545. * @abstract
  42546. * @param {string} [type='render'] - The type of the time stamp.
  42547. * @return {Promise<number>} A Promise that resolves with the time stamp.
  42548. */
  42549. async resolveTimestampsAsync( type = 'render' ) {
  42550. if ( ! this.trackTimestamp ) {
  42551. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  42552. return;
  42553. }
  42554. const queryPool = this.timestampQueryPool[ type ];
  42555. if ( ! queryPool ) {
  42556. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  42557. return;
  42558. }
  42559. const duration = await queryPool.resolveQueriesAsync();
  42560. this.renderer.info[ type ].timestamp = duration;
  42561. return duration;
  42562. }
  42563. /**
  42564. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  42565. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  42566. *
  42567. * @async
  42568. * @abstract
  42569. * @return {Promise} A Promise that resolves when synchronization has been finished.
  42570. */
  42571. async waitForGPU() {}
  42572. /**
  42573. * This method performs a readback operation by moving buffer data from
  42574. * a storage buffer attribute from the GPU to the CPU.
  42575. *
  42576. * @async
  42577. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42578. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42579. */
  42580. async getArrayBufferAsync( /* attribute */ ) {}
  42581. /**
  42582. * Checks if the given feature is supported by the backend.
  42583. *
  42584. * @async
  42585. * @abstract
  42586. * @param {string} name - The feature's name.
  42587. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42588. */
  42589. async hasFeatureAsync( /*name*/ ) { }
  42590. /**
  42591. * Checks if the given feature is supported by the backend.
  42592. *
  42593. * @abstract
  42594. * @param {string} name - The feature's name.
  42595. * @return {boolean} Whether the feature is supported or not.
  42596. */
  42597. hasFeature( /*name*/ ) {}
  42598. /**
  42599. * Returns the maximum anisotropy texture filtering value.
  42600. *
  42601. * @abstract
  42602. * @return {number} The maximum anisotropy texture filtering value.
  42603. */
  42604. getMaxAnisotropy() {}
  42605. /**
  42606. * Returns the drawing buffer size.
  42607. *
  42608. * @return {Vector2} The drawing buffer size.
  42609. */
  42610. getDrawingBufferSize() {
  42611. _vector2 = _vector2 || new Vector2();
  42612. return this.renderer.getDrawingBufferSize( _vector2 );
  42613. }
  42614. /**
  42615. * Defines the scissor test.
  42616. *
  42617. * @abstract
  42618. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42619. */
  42620. setScissorTest( /*boolean*/ ) { }
  42621. /**
  42622. * Returns the clear color and alpha into a single
  42623. * color object.
  42624. *
  42625. * @return {Color4} The clear color.
  42626. */
  42627. getClearColor() {
  42628. const renderer = this.renderer;
  42629. _color4 = _color4 || new Color4();
  42630. renderer.getClearColor( _color4 );
  42631. _color4.getRGB( _color4 );
  42632. return _color4;
  42633. }
  42634. /**
  42635. * Returns the DOM element. If no DOM element exists, the backend
  42636. * creates a new one.
  42637. *
  42638. * @return {HTMLCanvasElement} The DOM element.
  42639. */
  42640. getDomElement() {
  42641. let domElement = this.domElement;
  42642. if ( domElement === null ) {
  42643. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  42644. // OffscreenCanvas does not have setAttribute, see #22811
  42645. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  42646. this.domElement = domElement;
  42647. }
  42648. return domElement;
  42649. }
  42650. /**
  42651. * Sets a dictionary for the given object into the
  42652. * internal data structure.
  42653. *
  42654. * @param {Object} object - The object.
  42655. * @param {Object} value - The dictionary to set.
  42656. */
  42657. set( object, value ) {
  42658. this.data.set( object, value );
  42659. }
  42660. /**
  42661. * Returns the dictionary for the given object.
  42662. *
  42663. * @param {Object} object - The object.
  42664. * @return {Object} The object's dictionary.
  42665. */
  42666. get( object ) {
  42667. let map = this.data.get( object );
  42668. if ( map === undefined ) {
  42669. map = {};
  42670. this.data.set( object, map );
  42671. }
  42672. return map;
  42673. }
  42674. /**
  42675. * Checks if the given object has a dictionary
  42676. * with data defined.
  42677. *
  42678. * @param {Object} object - The object.
  42679. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  42680. */
  42681. has( object ) {
  42682. return this.data.has( object );
  42683. }
  42684. /**
  42685. * Deletes an object from the internal data structure.
  42686. *
  42687. * @param {Object} object - The object to delete.
  42688. */
  42689. delete( object ) {
  42690. this.data.delete( object );
  42691. }
  42692. /**
  42693. * Frees internal resources.
  42694. *
  42695. * @abstract
  42696. */
  42697. dispose() { }
  42698. }
  42699. let _id$1 = 0;
  42700. /**
  42701. * This module is internally used in context of compute shaders.
  42702. * This type of shader is not natively supported in WebGL 2 and
  42703. * thus implemented via Transform Feedback. `DualAttributeData`
  42704. * manages the related data.
  42705. *
  42706. * @private
  42707. */
  42708. class DualAttributeData {
  42709. constructor( attributeData, dualBuffer ) {
  42710. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  42711. this.type = attributeData.type;
  42712. this.bufferType = attributeData.bufferType;
  42713. this.pbo = attributeData.pbo;
  42714. this.byteLength = attributeData.byteLength;
  42715. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  42716. this.version = attributeData.version;
  42717. this.isInteger = attributeData.isInteger;
  42718. this.activeBufferIndex = 0;
  42719. this.baseId = attributeData.id;
  42720. }
  42721. get id() {
  42722. return `${ this.baseId }|${ this.activeBufferIndex }`;
  42723. }
  42724. get bufferGPU() {
  42725. return this.buffers[ this.activeBufferIndex ];
  42726. }
  42727. get transformBuffer() {
  42728. return this.buffers[ this.activeBufferIndex ^ 1 ];
  42729. }
  42730. switchBuffers() {
  42731. this.activeBufferIndex ^= 1;
  42732. }
  42733. }
  42734. /**
  42735. * A WebGL 2 backend utility module for managing shader attributes.
  42736. *
  42737. * @private
  42738. */
  42739. class WebGLAttributeUtils {
  42740. /**
  42741. * Constructs a new utility object.
  42742. *
  42743. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42744. */
  42745. constructor( backend ) {
  42746. /**
  42747. * A reference to the WebGL 2 backend.
  42748. *
  42749. * @type {WebGLBackend}
  42750. */
  42751. this.backend = backend;
  42752. }
  42753. /**
  42754. * Creates the GPU buffer for the given buffer attribute.
  42755. *
  42756. * @param {BufferAttribute} attribute - The buffer attribute.
  42757. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  42758. */
  42759. createAttribute( attribute, bufferType ) {
  42760. const backend = this.backend;
  42761. const { gl } = backend;
  42762. const array = attribute.array;
  42763. const usage = attribute.usage || gl.STATIC_DRAW;
  42764. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42765. const bufferData = backend.get( bufferAttribute );
  42766. let bufferGPU = bufferData.bufferGPU;
  42767. if ( bufferGPU === undefined ) {
  42768. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  42769. bufferData.bufferGPU = bufferGPU;
  42770. bufferData.bufferType = bufferType;
  42771. bufferData.version = bufferAttribute.version;
  42772. }
  42773. //attribute.onUploadCallback();
  42774. let type;
  42775. if ( array instanceof Float32Array ) {
  42776. type = gl.FLOAT;
  42777. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42778. type = gl.HALF_FLOAT;
  42779. } else if ( array instanceof Uint16Array ) {
  42780. if ( attribute.isFloat16BufferAttribute ) {
  42781. type = gl.HALF_FLOAT;
  42782. } else {
  42783. type = gl.UNSIGNED_SHORT;
  42784. }
  42785. } else if ( array instanceof Int16Array ) {
  42786. type = gl.SHORT;
  42787. } else if ( array instanceof Uint32Array ) {
  42788. type = gl.UNSIGNED_INT;
  42789. } else if ( array instanceof Int32Array ) {
  42790. type = gl.INT;
  42791. } else if ( array instanceof Int8Array ) {
  42792. type = gl.BYTE;
  42793. } else if ( array instanceof Uint8Array ) {
  42794. type = gl.UNSIGNED_BYTE;
  42795. } else if ( array instanceof Uint8ClampedArray ) {
  42796. type = gl.UNSIGNED_BYTE;
  42797. } else {
  42798. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  42799. }
  42800. let attributeData = {
  42801. bufferGPU,
  42802. bufferType,
  42803. type,
  42804. byteLength: array.byteLength,
  42805. bytesPerElement: array.BYTES_PER_ELEMENT,
  42806. version: attribute.version,
  42807. pbo: attribute.pbo,
  42808. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  42809. id: _id$1 ++
  42810. };
  42811. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  42812. // create buffer for transform feedback use
  42813. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  42814. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  42815. }
  42816. backend.set( attribute, attributeData );
  42817. }
  42818. /**
  42819. * Updates the GPU buffer of the given buffer attribute.
  42820. *
  42821. * @param {BufferAttribute} attribute - The buffer attribute.
  42822. */
  42823. updateAttribute( attribute ) {
  42824. const backend = this.backend;
  42825. const { gl } = backend;
  42826. const array = attribute.array;
  42827. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42828. const bufferData = backend.get( bufferAttribute );
  42829. const bufferType = bufferData.bufferType;
  42830. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  42831. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  42832. if ( updateRanges.length === 0 ) {
  42833. // Not using update ranges
  42834. gl.bufferSubData( bufferType, 0, array );
  42835. } else {
  42836. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42837. const range = updateRanges[ i ];
  42838. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42839. array, range.start, range.count );
  42840. }
  42841. bufferAttribute.clearUpdateRanges();
  42842. }
  42843. gl.bindBuffer( bufferType, null );
  42844. bufferData.version = bufferAttribute.version;
  42845. }
  42846. /**
  42847. * Destroys the GPU buffer of the given buffer attribute.
  42848. *
  42849. * @param {BufferAttribute} attribute - The buffer attribute.
  42850. */
  42851. destroyAttribute( attribute ) {
  42852. const backend = this.backend;
  42853. const { gl } = backend;
  42854. if ( attribute.isInterleavedBufferAttribute ) {
  42855. backend.delete( attribute.data );
  42856. }
  42857. const attributeData = backend.get( attribute );
  42858. gl.deleteBuffer( attributeData.bufferGPU );
  42859. backend.delete( attribute );
  42860. }
  42861. /**
  42862. * This method performs a readback operation by moving buffer data from
  42863. * a storage buffer attribute from the GPU to the CPU.
  42864. *
  42865. * @async
  42866. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42867. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42868. */
  42869. async getArrayBufferAsync( attribute ) {
  42870. const backend = this.backend;
  42871. const { gl } = backend;
  42872. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42873. const { bufferGPU } = backend.get( bufferAttribute );
  42874. const array = attribute.array;
  42875. const byteLength = array.byteLength;
  42876. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  42877. const writeBuffer = gl.createBuffer();
  42878. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  42879. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  42880. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  42881. await backend.utils._clientWaitAsync();
  42882. const dstBuffer = new attribute.array.constructor( array.length );
  42883. // Ensure the buffer is bound before reading
  42884. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  42885. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  42886. gl.deleteBuffer( writeBuffer );
  42887. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  42888. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  42889. return dstBuffer.buffer;
  42890. }
  42891. /**
  42892. * Creates a WebGL buffer with the given data.
  42893. *
  42894. * @private
  42895. * @param {WebGL2RenderingContext} gl - The rendering context.
  42896. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  42897. * @param {TypedArray} array - The array of the buffer attribute.
  42898. * @param {GLenum} usage - The usage.
  42899. * @return {WebGLBuffer} The WebGL buffer.
  42900. */
  42901. _createBuffer( gl, bufferType, array, usage ) {
  42902. const bufferGPU = gl.createBuffer();
  42903. gl.bindBuffer( bufferType, bufferGPU );
  42904. gl.bufferData( bufferType, array, usage );
  42905. gl.bindBuffer( bufferType, null );
  42906. return bufferGPU;
  42907. }
  42908. }
  42909. let equationToGL, factorToGL;
  42910. /**
  42911. * A WebGL 2 backend utility module for managing the WebGL state.
  42912. *
  42913. * The major goal of this module is to reduce the number of state changes
  42914. * by caching the WEbGL state with a series of variables. In this way, the
  42915. * renderer only executes state change commands when necessary which
  42916. * improves the overall performance.
  42917. *
  42918. * @private
  42919. */
  42920. class WebGLState {
  42921. /**
  42922. * Constructs a new utility object.
  42923. *
  42924. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42925. */
  42926. constructor( backend ) {
  42927. /**
  42928. * A reference to the WebGL 2 backend.
  42929. *
  42930. * @type {WebGLBackend}
  42931. */
  42932. this.backend = backend;
  42933. /**
  42934. * A reference to the rendering context.
  42935. *
  42936. * @type {WebGL2RenderingContext}
  42937. */
  42938. this.gl = this.backend.gl;
  42939. // Below properties are intended to cache
  42940. // the WebGL state and are not explicitly
  42941. // documented for convenience reasons.
  42942. this.enabled = {};
  42943. this.currentFlipSided = null;
  42944. this.currentCullFace = null;
  42945. this.currentProgram = null;
  42946. this.currentBlendingEnabled = false;
  42947. this.currentBlending = null;
  42948. this.currentBlendSrc = null;
  42949. this.currentBlendDst = null;
  42950. this.currentBlendSrcAlpha = null;
  42951. this.currentBlendDstAlpha = null;
  42952. this.currentPremultipledAlpha = null;
  42953. this.currentPolygonOffsetFactor = null;
  42954. this.currentPolygonOffsetUnits = null;
  42955. this.currentColorMask = null;
  42956. this.currentDepthFunc = null;
  42957. this.currentDepthMask = null;
  42958. this.currentStencilFunc = null;
  42959. this.currentStencilRef = null;
  42960. this.currentStencilFuncMask = null;
  42961. this.currentStencilFail = null;
  42962. this.currentStencilZFail = null;
  42963. this.currentStencilZPass = null;
  42964. this.currentStencilMask = null;
  42965. this.currentLineWidth = null;
  42966. this.currentClippingPlanes = 0;
  42967. this.currentVAO = null;
  42968. this.currentIndex = null;
  42969. this.currentBoundFramebuffers = {};
  42970. this.currentDrawbuffers = new WeakMap();
  42971. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  42972. this.currentTextureSlot = null;
  42973. this.currentBoundTextures = {};
  42974. this.currentBoundBufferBases = {};
  42975. this._init();
  42976. }
  42977. /**
  42978. * Inits the state of the utility.
  42979. *
  42980. * @private
  42981. */
  42982. _init() {
  42983. const gl = this.gl;
  42984. // Store only WebGL constants here.
  42985. equationToGL = {
  42986. [ AddEquation ]: gl.FUNC_ADD,
  42987. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  42988. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  42989. };
  42990. factorToGL = {
  42991. [ ZeroFactor ]: gl.ZERO,
  42992. [ OneFactor ]: gl.ONE,
  42993. [ SrcColorFactor ]: gl.SRC_COLOR,
  42994. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  42995. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  42996. [ DstColorFactor ]: gl.DST_COLOR,
  42997. [ DstAlphaFactor ]: gl.DST_ALPHA,
  42998. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  42999. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  43000. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  43001. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  43002. };
  43003. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  43004. const viewportParam = gl.getParameter( gl.VIEWPORT );
  43005. this.currentScissor = new Vector4().fromArray( scissorParam );
  43006. this.currentViewport = new Vector4().fromArray( viewportParam );
  43007. this._tempVec4 = new Vector4();
  43008. }
  43009. /**
  43010. * Enables the given WebGL capability.
  43011. *
  43012. * This method caches the capability state so
  43013. * `gl.enable()` is only called when necessary.
  43014. *
  43015. * @param {GLenum} id - The capability to enable.
  43016. */
  43017. enable( id ) {
  43018. const { enabled } = this;
  43019. if ( enabled[ id ] !== true ) {
  43020. this.gl.enable( id );
  43021. enabled[ id ] = true;
  43022. }
  43023. }
  43024. /**
  43025. * Disables the given WebGL capability.
  43026. *
  43027. * This method caches the capability state so
  43028. * `gl.disable()` is only called when necessary.
  43029. *
  43030. * @param {GLenum} id - The capability to enable.
  43031. */
  43032. disable( id ) {
  43033. const { enabled } = this;
  43034. if ( enabled[ id ] !== false ) {
  43035. this.gl.disable( id );
  43036. enabled[ id ] = false;
  43037. }
  43038. }
  43039. /**
  43040. * Specifies whether polygons are front- or back-facing
  43041. * by setting the winding orientation.
  43042. *
  43043. * This method caches the state so `gl.frontFace()` is only
  43044. * called when necessary.
  43045. *
  43046. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  43047. */
  43048. setFlipSided( flipSided ) {
  43049. if ( this.currentFlipSided !== flipSided ) {
  43050. const { gl } = this;
  43051. if ( flipSided ) {
  43052. gl.frontFace( gl.CW );
  43053. } else {
  43054. gl.frontFace( gl.CCW );
  43055. }
  43056. this.currentFlipSided = flipSided;
  43057. }
  43058. }
  43059. /**
  43060. * Specifies whether or not front- and/or back-facing
  43061. * polygons can be culled.
  43062. *
  43063. * This method caches the state so `gl.cullFace()` is only
  43064. * called when necessary.
  43065. *
  43066. * @param {number} cullFace - Defines which polygons are candidates for culling.
  43067. */
  43068. setCullFace( cullFace ) {
  43069. const { gl } = this;
  43070. if ( cullFace !== CullFaceNone ) {
  43071. this.enable( gl.CULL_FACE );
  43072. if ( cullFace !== this.currentCullFace ) {
  43073. if ( cullFace === CullFaceBack ) {
  43074. gl.cullFace( gl.BACK );
  43075. } else if ( cullFace === CullFaceFront ) {
  43076. gl.cullFace( gl.FRONT );
  43077. } else {
  43078. gl.cullFace( gl.FRONT_AND_BACK );
  43079. }
  43080. }
  43081. } else {
  43082. this.disable( gl.CULL_FACE );
  43083. }
  43084. this.currentCullFace = cullFace;
  43085. }
  43086. /**
  43087. * Specifies the width of line primitives.
  43088. *
  43089. * This method caches the state so `gl.lineWidth()` is only
  43090. * called when necessary.
  43091. *
  43092. * @param {number} width - The line width.
  43093. */
  43094. setLineWidth( width ) {
  43095. const { currentLineWidth, gl } = this;
  43096. if ( width !== currentLineWidth ) {
  43097. gl.lineWidth( width );
  43098. this.currentLineWidth = width;
  43099. }
  43100. }
  43101. /**
  43102. * Defines the blending.
  43103. *
  43104. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  43105. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  43106. *
  43107. * @param {number} blending - The blending type.
  43108. * @param {number} blendEquation - The blending equation.
  43109. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  43110. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  43111. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  43112. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  43113. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  43114. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  43115. */
  43116. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  43117. const { gl } = this;
  43118. if ( blending === NoBlending ) {
  43119. if ( this.currentBlendingEnabled === true ) {
  43120. this.disable( gl.BLEND );
  43121. this.currentBlendingEnabled = false;
  43122. }
  43123. return;
  43124. }
  43125. if ( this.currentBlendingEnabled === false ) {
  43126. this.enable( gl.BLEND );
  43127. this.currentBlendingEnabled = true;
  43128. }
  43129. if ( blending !== CustomBlending ) {
  43130. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  43131. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  43132. gl.blendEquation( gl.FUNC_ADD );
  43133. this.currentBlendEquation = AddEquation;
  43134. this.currentBlendEquationAlpha = AddEquation;
  43135. }
  43136. if ( premultipliedAlpha ) {
  43137. switch ( blending ) {
  43138. case NormalBlending:
  43139. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  43140. break;
  43141. case AdditiveBlending:
  43142. gl.blendFunc( gl.ONE, gl.ONE );
  43143. break;
  43144. case SubtractiveBlending:
  43145. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  43146. break;
  43147. case MultiplyBlending:
  43148. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  43149. break;
  43150. default:
  43151. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  43152. break;
  43153. }
  43154. } else {
  43155. switch ( blending ) {
  43156. case NormalBlending:
  43157. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  43158. break;
  43159. case AdditiveBlending:
  43160. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  43161. break;
  43162. case SubtractiveBlending:
  43163. console.error( 'THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  43164. break;
  43165. case MultiplyBlending:
  43166. console.error( 'THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  43167. break;
  43168. default:
  43169. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  43170. break;
  43171. }
  43172. }
  43173. this.currentBlendSrc = null;
  43174. this.currentBlendDst = null;
  43175. this.currentBlendSrcAlpha = null;
  43176. this.currentBlendDstAlpha = null;
  43177. this.currentBlending = blending;
  43178. this.currentPremultipledAlpha = premultipliedAlpha;
  43179. }
  43180. return;
  43181. }
  43182. // custom blending
  43183. blendEquationAlpha = blendEquationAlpha || blendEquation;
  43184. blendSrcAlpha = blendSrcAlpha || blendSrc;
  43185. blendDstAlpha = blendDstAlpha || blendDst;
  43186. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  43187. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  43188. this.currentBlendEquation = blendEquation;
  43189. this.currentBlendEquationAlpha = blendEquationAlpha;
  43190. }
  43191. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  43192. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  43193. this.currentBlendSrc = blendSrc;
  43194. this.currentBlendDst = blendDst;
  43195. this.currentBlendSrcAlpha = blendSrcAlpha;
  43196. this.currentBlendDstAlpha = blendDstAlpha;
  43197. }
  43198. this.currentBlending = blending;
  43199. this.currentPremultipledAlpha = false;
  43200. }
  43201. /**
  43202. * Specifies whether colors can be written when rendering
  43203. * into a framebuffer or not.
  43204. *
  43205. * This method caches the state so `gl.colorMask()` is only
  43206. * called when necessary.
  43207. *
  43208. * @param {boolean} colorMask - The color mask.
  43209. */
  43210. setColorMask( colorMask ) {
  43211. if ( this.currentColorMask !== colorMask ) {
  43212. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  43213. this.currentColorMask = colorMask;
  43214. }
  43215. }
  43216. /**
  43217. * Specifies whether the depth test is enabled or not.
  43218. *
  43219. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  43220. */
  43221. setDepthTest( depthTest ) {
  43222. const { gl } = this;
  43223. if ( depthTest ) {
  43224. this.enable( gl.DEPTH_TEST );
  43225. } else {
  43226. this.disable( gl.DEPTH_TEST );
  43227. }
  43228. }
  43229. /**
  43230. * Specifies whether depth values can be written when rendering
  43231. * into a framebuffer or not.
  43232. *
  43233. * This method caches the state so `gl.depthMask()` is only
  43234. * called when necessary.
  43235. *
  43236. * @param {boolean} depthMask - The depth mask.
  43237. */
  43238. setDepthMask( depthMask ) {
  43239. if ( this.currentDepthMask !== depthMask ) {
  43240. this.gl.depthMask( depthMask );
  43241. this.currentDepthMask = depthMask;
  43242. }
  43243. }
  43244. /**
  43245. * Specifies the depth compare function.
  43246. *
  43247. * This method caches the state so `gl.depthFunc()` is only
  43248. * called when necessary.
  43249. *
  43250. * @param {number} depthFunc - The depth compare function.
  43251. */
  43252. setDepthFunc( depthFunc ) {
  43253. if ( this.currentDepthFunc !== depthFunc ) {
  43254. const { gl } = this;
  43255. switch ( depthFunc ) {
  43256. case NeverDepth:
  43257. gl.depthFunc( gl.NEVER );
  43258. break;
  43259. case AlwaysDepth:
  43260. gl.depthFunc( gl.ALWAYS );
  43261. break;
  43262. case LessDepth:
  43263. gl.depthFunc( gl.LESS );
  43264. break;
  43265. case LessEqualDepth:
  43266. gl.depthFunc( gl.LEQUAL );
  43267. break;
  43268. case EqualDepth:
  43269. gl.depthFunc( gl.EQUAL );
  43270. break;
  43271. case GreaterEqualDepth:
  43272. gl.depthFunc( gl.GEQUAL );
  43273. break;
  43274. case GreaterDepth:
  43275. gl.depthFunc( gl.GREATER );
  43276. break;
  43277. case NotEqualDepth:
  43278. gl.depthFunc( gl.NOTEQUAL );
  43279. break;
  43280. default:
  43281. gl.depthFunc( gl.LEQUAL );
  43282. }
  43283. this.currentDepthFunc = depthFunc;
  43284. }
  43285. }
  43286. /**
  43287. * Specifies the scissor box.
  43288. *
  43289. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  43290. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  43291. * @param {number} width - The width of the viewport.
  43292. * @param {number} height - The height of the viewport.
  43293. *
  43294. */
  43295. scissor( x, y, width, height ) {
  43296. const scissor = this._tempVec4.set( x, y, width, height );
  43297. if ( this.currentScissor.equals( scissor ) === false ) {
  43298. const { gl } = this;
  43299. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  43300. this.currentScissor.copy( scissor );
  43301. }
  43302. }
  43303. /**
  43304. * Specifies the viewport.
  43305. *
  43306. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  43307. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  43308. * @param {number} width - The width of the viewport.
  43309. * @param {number} height - The height of the viewport.
  43310. *
  43311. */
  43312. viewport( x, y, width, height ) {
  43313. const viewport = this._tempVec4.set( x, y, width, height );
  43314. if ( this.currentViewport.equals( viewport ) === false ) {
  43315. const { gl } = this;
  43316. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  43317. this.currentViewport.copy( viewport );
  43318. }
  43319. }
  43320. /**
  43321. * Defines the scissor test.
  43322. *
  43323. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43324. */
  43325. setScissorTest( boolean ) {
  43326. const gl = this.gl;
  43327. if ( boolean ) {
  43328. gl.enable( gl.SCISSOR_TEST );
  43329. } else {
  43330. gl.disable( gl.SCISSOR_TEST );
  43331. }
  43332. }
  43333. /**
  43334. * Specifies whether the stencil test is enabled or not.
  43335. *
  43336. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  43337. */
  43338. setStencilTest( stencilTest ) {
  43339. const { gl } = this;
  43340. if ( stencilTest ) {
  43341. this.enable( gl.STENCIL_TEST );
  43342. } else {
  43343. this.disable( gl.STENCIL_TEST );
  43344. }
  43345. }
  43346. /**
  43347. * Specifies whether stencil values can be written when rendering
  43348. * into a framebuffer or not.
  43349. *
  43350. * This method caches the state so `gl.stencilMask()` is only
  43351. * called when necessary.
  43352. *
  43353. * @param {boolean} stencilMask - The stencil mask.
  43354. */
  43355. setStencilMask( stencilMask ) {
  43356. if ( this.currentStencilMask !== stencilMask ) {
  43357. this.gl.stencilMask( stencilMask );
  43358. this.currentStencilMask = stencilMask;
  43359. }
  43360. }
  43361. /**
  43362. * Specifies whether the stencil test functions.
  43363. *
  43364. * This method caches the state so `gl.stencilFunc()` is only
  43365. * called when necessary.
  43366. *
  43367. * @param {number} stencilFunc - The stencil compare function.
  43368. * @param {number} stencilRef - The reference value for the stencil test.
  43369. * @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.
  43370. */
  43371. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  43372. if ( this.currentStencilFunc !== stencilFunc ||
  43373. this.currentStencilRef !== stencilRef ||
  43374. this.currentStencilFuncMask !== stencilMask ) {
  43375. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  43376. this.currentStencilFunc = stencilFunc;
  43377. this.currentStencilRef = stencilRef;
  43378. this.currentStencilFuncMask = stencilMask;
  43379. }
  43380. }
  43381. /**
  43382. * Specifies whether the stencil test operation.
  43383. *
  43384. * This method caches the state so `gl.stencilOp()` is only
  43385. * called when necessary.
  43386. *
  43387. * @param {number} stencilFail - The function to use when the stencil test fails.
  43388. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  43389. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  43390. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  43391. */
  43392. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  43393. if ( this.currentStencilFail !== stencilFail ||
  43394. this.currentStencilZFail !== stencilZFail ||
  43395. this.currentStencilZPass !== stencilZPass ) {
  43396. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  43397. this.currentStencilFail = stencilFail;
  43398. this.currentStencilZFail = stencilZFail;
  43399. this.currentStencilZPass = stencilZPass;
  43400. }
  43401. }
  43402. /**
  43403. * Configures the WebGL state for the given material.
  43404. *
  43405. * @param {Material} material - The material to configure the state for.
  43406. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  43407. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  43408. */
  43409. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  43410. const { gl } = this;
  43411. material.side === DoubleSide
  43412. ? this.disable( gl.CULL_FACE )
  43413. : this.enable( gl.CULL_FACE );
  43414. let flipSided = ( material.side === BackSide );
  43415. if ( frontFaceCW ) flipSided = ! flipSided;
  43416. this.setFlipSided( flipSided );
  43417. ( material.blending === NormalBlending && material.transparent === false )
  43418. ? this.setBlending( NoBlending )
  43419. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  43420. this.setDepthFunc( material.depthFunc );
  43421. this.setDepthTest( material.depthTest );
  43422. this.setDepthMask( material.depthWrite );
  43423. this.setColorMask( material.colorWrite );
  43424. const stencilWrite = material.stencilWrite;
  43425. this.setStencilTest( stencilWrite );
  43426. if ( stencilWrite ) {
  43427. this.setStencilMask( material.stencilWriteMask );
  43428. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  43429. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  43430. }
  43431. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  43432. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  43433. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  43434. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  43435. if ( hardwareClippingPlanes > 0 ) {
  43436. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  43437. const CLIP_DISTANCE0_WEBGL = 0x3000;
  43438. for ( let i = 0; i < 8; i ++ ) {
  43439. if ( i < hardwareClippingPlanes ) {
  43440. this.enable( CLIP_DISTANCE0_WEBGL + i );
  43441. } else {
  43442. this.disable( CLIP_DISTANCE0_WEBGL + i );
  43443. }
  43444. }
  43445. }
  43446. }
  43447. }
  43448. /**
  43449. * Specifies the polygon offset.
  43450. *
  43451. * This method caches the state so `gl.polygonOffset()` is only
  43452. * called when necessary.
  43453. *
  43454. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  43455. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  43456. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  43457. */
  43458. setPolygonOffset( polygonOffset, factor, units ) {
  43459. const { gl } = this;
  43460. if ( polygonOffset ) {
  43461. this.enable( gl.POLYGON_OFFSET_FILL );
  43462. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  43463. gl.polygonOffset( factor, units );
  43464. this.currentPolygonOffsetFactor = factor;
  43465. this.currentPolygonOffsetUnits = units;
  43466. }
  43467. } else {
  43468. this.disable( gl.POLYGON_OFFSET_FILL );
  43469. }
  43470. }
  43471. /**
  43472. * Defines the usage of the given WebGL program.
  43473. *
  43474. * This method caches the state so `gl.useProgram()` is only
  43475. * called when necessary.
  43476. *
  43477. * @param {WebGLProgram} program - The WebGL program to use.
  43478. * @return {boolean} Whether a program change has been executed or not.
  43479. */
  43480. useProgram( program ) {
  43481. if ( this.currentProgram !== program ) {
  43482. this.gl.useProgram( program );
  43483. this.currentProgram = program;
  43484. return true;
  43485. }
  43486. return false;
  43487. }
  43488. /**
  43489. * Sets the vertex state by binding the given VAO and element buffer.
  43490. *
  43491. * @param {WebGLVertexArrayObject} vao - The VAO.
  43492. * @param {WebGLBuffer} indexBuffer - The index buffer.
  43493. * @return {boolean} Whether a vertex state has been changed or not.
  43494. */
  43495. setVertexState( vao, indexBuffer = null ) {
  43496. const gl = this.gl;
  43497. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  43498. gl.bindVertexArray( vao );
  43499. if ( indexBuffer !== null ) {
  43500. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  43501. }
  43502. this.currentVAO = vao;
  43503. this.currentIndex = indexBuffer;
  43504. return true;
  43505. }
  43506. return false;
  43507. }
  43508. /**
  43509. * Resets the vertex array state by resetting the VAO and element buffer.
  43510. */
  43511. resetVertexState() {
  43512. const gl = this.gl;
  43513. gl.bindVertexArray( null );
  43514. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  43515. this.currentVAO = null;
  43516. this.currentIndex = null;
  43517. }
  43518. // framebuffer
  43519. /**
  43520. * Binds the given framebuffer.
  43521. *
  43522. * This method caches the state so `gl.bindFramebuffer()` is only
  43523. * called when necessary.
  43524. *
  43525. * @param {number} target - The binding point (target).
  43526. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  43527. * @return {boolean} Whether a bind has been executed or not.
  43528. */
  43529. bindFramebuffer( target, framebuffer ) {
  43530. const { gl, currentBoundFramebuffers } = this;
  43531. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  43532. gl.bindFramebuffer( target, framebuffer );
  43533. currentBoundFramebuffers[ target ] = framebuffer;
  43534. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  43535. if ( target === gl.DRAW_FRAMEBUFFER ) {
  43536. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  43537. }
  43538. if ( target === gl.FRAMEBUFFER ) {
  43539. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  43540. }
  43541. return true;
  43542. }
  43543. return false;
  43544. }
  43545. /**
  43546. * Defines draw buffers to which fragment colors are written into.
  43547. * Configures the MRT setup of custom framebuffers.
  43548. *
  43549. * This method caches the state so `gl.drawBuffers()` is only
  43550. * called when necessary.
  43551. *
  43552. * @param {RenderContext} renderContext - The render context.
  43553. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  43554. */
  43555. drawBuffers( renderContext, framebuffer ) {
  43556. const { gl } = this;
  43557. let drawBuffers = [];
  43558. let needsUpdate = false;
  43559. if ( renderContext.textures !== null ) {
  43560. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  43561. if ( drawBuffers === undefined ) {
  43562. drawBuffers = [];
  43563. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  43564. }
  43565. const textures = renderContext.textures;
  43566. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  43567. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  43568. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  43569. }
  43570. drawBuffers.length = textures.length;
  43571. needsUpdate = true;
  43572. }
  43573. } else {
  43574. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  43575. drawBuffers[ 0 ] = gl.BACK;
  43576. needsUpdate = true;
  43577. }
  43578. }
  43579. if ( needsUpdate ) {
  43580. gl.drawBuffers( drawBuffers );
  43581. }
  43582. }
  43583. // texture
  43584. /**
  43585. * Makes the given texture unit active.
  43586. *
  43587. * This method caches the state so `gl.activeTexture()` is only
  43588. * called when necessary.
  43589. *
  43590. * @param {number} webglSlot - The texture unit to make active.
  43591. */
  43592. activeTexture( webglSlot ) {
  43593. const { gl, currentTextureSlot, maxTextures } = this;
  43594. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  43595. if ( currentTextureSlot !== webglSlot ) {
  43596. gl.activeTexture( webglSlot );
  43597. this.currentTextureSlot = webglSlot;
  43598. }
  43599. }
  43600. /**
  43601. * Binds the given WebGL texture to a target.
  43602. *
  43603. * This method caches the state so `gl.bindTexture()` is only
  43604. * called when necessary.
  43605. *
  43606. * @param {number} webglType - The binding point (target).
  43607. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  43608. * @param {number} webglSlot - The texture.
  43609. */
  43610. bindTexture( webglType, webglTexture, webglSlot ) {
  43611. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  43612. if ( webglSlot === undefined ) {
  43613. if ( currentTextureSlot === null ) {
  43614. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  43615. } else {
  43616. webglSlot = currentTextureSlot;
  43617. }
  43618. }
  43619. let boundTexture = currentBoundTextures[ webglSlot ];
  43620. if ( boundTexture === undefined ) {
  43621. boundTexture = { type: undefined, texture: undefined };
  43622. currentBoundTextures[ webglSlot ] = boundTexture;
  43623. }
  43624. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  43625. if ( currentTextureSlot !== webglSlot ) {
  43626. gl.activeTexture( webglSlot );
  43627. this.currentTextureSlot = webglSlot;
  43628. }
  43629. gl.bindTexture( webglType, webglTexture );
  43630. boundTexture.type = webglType;
  43631. boundTexture.texture = webglTexture;
  43632. }
  43633. }
  43634. /**
  43635. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  43636. *
  43637. * This method caches the state so `gl.bindBufferBase()` is only
  43638. * called when necessary.
  43639. *
  43640. * @param {number} target - The target for the bind operation.
  43641. * @param {number} index - The index of the target.
  43642. * @param {WebGLBuffer} buffer - The WebGL buffer.
  43643. * @return {boolean} Whether a bind has been executed or not.
  43644. */
  43645. bindBufferBase( target, index, buffer ) {
  43646. const { gl } = this;
  43647. const key = `${target}-${index}`;
  43648. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  43649. gl.bindBufferBase( target, index, buffer );
  43650. this.currentBoundBufferBases[ key ] = buffer;
  43651. return true;
  43652. }
  43653. return false;
  43654. }
  43655. /**
  43656. * Unbinds the current bound texture.
  43657. *
  43658. * This method caches the state so `gl.bindTexture()` is only
  43659. * called when necessary.
  43660. */
  43661. unbindTexture() {
  43662. const { gl, currentTextureSlot, currentBoundTextures } = this;
  43663. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  43664. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  43665. gl.bindTexture( boundTexture.type, null );
  43666. boundTexture.type = undefined;
  43667. boundTexture.texture = undefined;
  43668. }
  43669. }
  43670. }
  43671. /**
  43672. * A WebGL 2 backend utility module with common helpers.
  43673. *
  43674. * @private
  43675. */
  43676. class WebGLUtils {
  43677. /**
  43678. * Constructs a new utility object.
  43679. *
  43680. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43681. */
  43682. constructor( backend ) {
  43683. /**
  43684. * A reference to the WebGL 2 backend.
  43685. *
  43686. * @type {WebGLBackend}
  43687. */
  43688. this.backend = backend;
  43689. /**
  43690. * A reference to the rendering context.
  43691. *
  43692. * @type {WebGL2RenderingContext}
  43693. */
  43694. this.gl = this.backend.gl;
  43695. /**
  43696. * A reference to a backend module holding extension-related
  43697. * utility functions.
  43698. *
  43699. * @type {WebGLExtensions}
  43700. */
  43701. this.extensions = backend.extensions;
  43702. }
  43703. /**
  43704. * Converts the given three.js constant into a WebGL constant.
  43705. * The method currently supports the conversion of texture formats
  43706. * and types.
  43707. *
  43708. * @param {number} p - The three.js constant.
  43709. * @param {string} [colorSpace=NoColorSpace] - The color space.
  43710. * @return {?number} The corresponding WebGL constant.
  43711. */
  43712. convert( p, colorSpace = NoColorSpace ) {
  43713. const { gl, extensions } = this;
  43714. let extension;
  43715. const transfer = ColorManagement.getTransfer( colorSpace );
  43716. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  43717. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  43718. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  43719. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  43720. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  43721. if ( p === ByteType ) return gl.BYTE;
  43722. if ( p === ShortType ) return gl.SHORT;
  43723. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  43724. if ( p === IntType ) return gl.INT;
  43725. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  43726. if ( p === FloatType ) return gl.FLOAT;
  43727. if ( p === HalfFloatType ) {
  43728. return gl.HALF_FLOAT;
  43729. }
  43730. if ( p === AlphaFormat ) return gl.ALPHA;
  43731. if ( p === RGBFormat ) return gl.RGB;
  43732. if ( p === RGBAFormat ) return gl.RGBA;
  43733. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  43734. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  43735. // WebGL2 formats.
  43736. if ( p === RedFormat ) return gl.RED;
  43737. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  43738. if ( p === RGFormat ) return gl.RG;
  43739. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  43740. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  43741. // S3TC
  43742. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  43743. if ( transfer === SRGBTransfer ) {
  43744. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  43745. if ( extension !== null ) {
  43746. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  43747. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  43748. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  43749. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  43750. } else {
  43751. return null;
  43752. }
  43753. } else {
  43754. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  43755. if ( extension !== null ) {
  43756. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  43757. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  43758. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  43759. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  43760. } else {
  43761. return null;
  43762. }
  43763. }
  43764. }
  43765. // PVRTC
  43766. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  43767. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  43768. if ( extension !== null ) {
  43769. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  43770. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  43771. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  43772. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  43773. } else {
  43774. return null;
  43775. }
  43776. }
  43777. // ETC
  43778. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  43779. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  43780. if ( extension !== null ) {
  43781. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  43782. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  43783. } else {
  43784. return null;
  43785. }
  43786. }
  43787. // ASTC
  43788. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  43789. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  43790. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  43791. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  43792. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  43793. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  43794. if ( extension !== null ) {
  43795. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  43796. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  43797. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  43798. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  43799. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  43800. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  43801. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  43802. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  43803. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  43804. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  43805. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  43806. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  43807. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  43808. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  43809. } else {
  43810. return null;
  43811. }
  43812. }
  43813. // BPTC
  43814. if ( p === RGBA_BPTC_Format ) {
  43815. extension = extensions.get( 'EXT_texture_compression_bptc' );
  43816. if ( extension !== null ) {
  43817. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  43818. } else {
  43819. return null;
  43820. }
  43821. }
  43822. // RGTC
  43823. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  43824. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  43825. if ( extension !== null ) {
  43826. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  43827. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  43828. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  43829. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  43830. } else {
  43831. return null;
  43832. }
  43833. }
  43834. //
  43835. if ( p === UnsignedInt248Type ) {
  43836. return gl.UNSIGNED_INT_24_8;
  43837. }
  43838. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  43839. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  43840. }
  43841. /**
  43842. * This method can be used to synchronize the CPU with the GPU by waiting until
  43843. * ongoing GPU commands have been completed.
  43844. *
  43845. * @private
  43846. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  43847. */
  43848. _clientWaitAsync() {
  43849. const { gl } = this;
  43850. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  43851. gl.flush();
  43852. return new Promise( ( resolve, reject ) => {
  43853. function test() {
  43854. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  43855. if ( res === gl.WAIT_FAILED ) {
  43856. gl.deleteSync( sync );
  43857. reject();
  43858. return;
  43859. }
  43860. if ( res === gl.TIMEOUT_EXPIRED ) {
  43861. requestAnimationFrame( test );
  43862. return;
  43863. }
  43864. gl.deleteSync( sync );
  43865. resolve();
  43866. }
  43867. test();
  43868. } );
  43869. }
  43870. }
  43871. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  43872. /**
  43873. * A WebGL 2 backend utility module for managing textures.
  43874. *
  43875. * @private
  43876. */
  43877. class WebGLTextureUtils {
  43878. /**
  43879. * Constructs a new utility object.
  43880. *
  43881. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43882. */
  43883. constructor( backend ) {
  43884. /**
  43885. * A reference to the WebGL 2 backend.
  43886. *
  43887. * @type {WebGLBackend}
  43888. */
  43889. this.backend = backend;
  43890. /**
  43891. * A reference to the rendering context.
  43892. *
  43893. * @type {WebGL2RenderingContext}
  43894. */
  43895. this.gl = backend.gl;
  43896. /**
  43897. * A reference to a backend module holding extension-related
  43898. * utility functions.
  43899. *
  43900. * @type {WebGLExtensions}
  43901. */
  43902. this.extensions = backend.extensions;
  43903. /**
  43904. * A dictionary for managing default textures. The key
  43905. * is the binding point (target), the value the WEbGL texture object.
  43906. *
  43907. * @type {Object<GLenum,WebGLTexture>}
  43908. */
  43909. this.defaultTextures = {};
  43910. if ( initialized === false ) {
  43911. this._init();
  43912. initialized = true;
  43913. }
  43914. }
  43915. /**
  43916. * Inits the state of the utility.
  43917. *
  43918. * @private
  43919. */
  43920. _init() {
  43921. const gl = this.gl;
  43922. // Store only WebGL constants here.
  43923. wrappingToGL = {
  43924. [ RepeatWrapping ]: gl.REPEAT,
  43925. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  43926. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  43927. };
  43928. filterToGL = {
  43929. [ NearestFilter ]: gl.NEAREST,
  43930. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  43931. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  43932. [ LinearFilter ]: gl.LINEAR,
  43933. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  43934. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  43935. };
  43936. compareToGL = {
  43937. [ NeverCompare ]: gl.NEVER,
  43938. [ AlwaysCompare ]: gl.ALWAYS,
  43939. [ LessCompare ]: gl.LESS,
  43940. [ LessEqualCompare ]: gl.LEQUAL,
  43941. [ EqualCompare ]: gl.EQUAL,
  43942. [ GreaterEqualCompare ]: gl.GEQUAL,
  43943. [ GreaterCompare ]: gl.GREATER,
  43944. [ NotEqualCompare ]: gl.NOTEQUAL
  43945. };
  43946. }
  43947. /**
  43948. * Returns the native texture type for the given texture.
  43949. *
  43950. * @param {Texture} texture - The texture.
  43951. * @return {GLenum} The native texture type.
  43952. */
  43953. getGLTextureType( texture ) {
  43954. const { gl } = this;
  43955. let glTextureType;
  43956. if ( texture.isCubeTexture === true ) {
  43957. glTextureType = gl.TEXTURE_CUBE_MAP;
  43958. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43959. glTextureType = gl.TEXTURE_2D_ARRAY;
  43960. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  43961. glTextureType = gl.TEXTURE_3D;
  43962. } else {
  43963. glTextureType = gl.TEXTURE_2D;
  43964. }
  43965. return glTextureType;
  43966. }
  43967. /**
  43968. * Returns the native texture type for the given texture.
  43969. *
  43970. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  43971. * @param {GLenum} glFormat - The WebGL format.
  43972. * @param {GLenum} glType - The WebGL type.
  43973. * @param {string} colorSpace - The texture's color space.
  43974. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  43975. * @return {GLenum} The internal format.
  43976. */
  43977. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  43978. const { gl, extensions } = this;
  43979. if ( internalFormatName !== null ) {
  43980. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  43981. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  43982. }
  43983. let internalFormat = glFormat;
  43984. if ( glFormat === gl.RED ) {
  43985. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  43986. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  43987. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  43988. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  43989. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  43990. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  43991. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  43992. if ( glType === gl.INT ) internalFormat = gl.R32I;
  43993. }
  43994. if ( glFormat === gl.RED_INTEGER ) {
  43995. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  43996. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  43997. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  43998. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  43999. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  44000. if ( glType === gl.INT ) internalFormat = gl.R32I;
  44001. }
  44002. if ( glFormat === gl.RG ) {
  44003. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  44004. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  44005. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  44006. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  44007. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  44008. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  44009. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  44010. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  44011. }
  44012. if ( glFormat === gl.RG_INTEGER ) {
  44013. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  44014. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  44015. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  44016. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  44017. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  44018. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  44019. }
  44020. if ( glFormat === gl.RGB ) {
  44021. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  44022. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  44023. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  44024. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  44025. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  44026. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  44027. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  44028. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  44029. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  44030. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  44031. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  44032. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  44033. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  44034. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  44035. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  44036. }
  44037. if ( glFormat === gl.RGB_INTEGER ) {
  44038. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  44039. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  44040. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  44041. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  44042. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  44043. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  44044. }
  44045. if ( glFormat === gl.RGBA ) {
  44046. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  44047. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  44048. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  44049. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  44050. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  44051. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  44052. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  44053. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  44054. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  44055. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  44056. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  44057. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  44058. }
  44059. if ( glFormat === gl.RGBA_INTEGER ) {
  44060. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  44061. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  44062. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  44063. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  44064. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  44065. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  44066. }
  44067. if ( glFormat === gl.DEPTH_COMPONENT ) {
  44068. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  44069. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  44070. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  44071. }
  44072. if ( glFormat === gl.DEPTH_STENCIL ) {
  44073. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  44074. }
  44075. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  44076. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  44077. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  44078. extensions.get( 'EXT_color_buffer_float' );
  44079. }
  44080. return internalFormat;
  44081. }
  44082. /**
  44083. * Sets the texture parameters for the given texture.
  44084. *
  44085. * @param {GLenum} textureType - The texture type.
  44086. * @param {Texture} texture - The texture.
  44087. */
  44088. setTextureParameters( textureType, texture ) {
  44089. const { gl, extensions, backend } = this;
  44090. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  44091. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  44092. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  44093. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  44094. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  44095. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  44096. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  44097. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  44098. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  44099. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  44100. // WebGL 2 does not support wrapping for depth 2D array textures
  44101. if ( ! texture.isArrayTexture ) {
  44102. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  44103. }
  44104. }
  44105. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  44106. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  44107. // follow WebGPU backend mapping for texture filtering
  44108. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  44109. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  44110. if ( texture.compareFunction ) {
  44111. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  44112. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  44113. }
  44114. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44115. if ( texture.magFilter === NearestFilter ) return;
  44116. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  44117. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  44118. if ( texture.anisotropy > 1 ) {
  44119. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44120. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  44121. }
  44122. }
  44123. }
  44124. /**
  44125. * Creates a default texture for the given texture that can be used
  44126. * as a placeholder until the actual texture is ready for usage.
  44127. *
  44128. * @param {Texture} texture - The texture to create a default texture for.
  44129. */
  44130. createDefaultTexture( texture ) {
  44131. const { gl, backend, defaultTextures } = this;
  44132. const glTextureType = this.getGLTextureType( texture );
  44133. let textureGPU = defaultTextures[ glTextureType ];
  44134. if ( textureGPU === undefined ) {
  44135. textureGPU = gl.createTexture();
  44136. backend.state.bindTexture( glTextureType, textureGPU );
  44137. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  44138. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  44139. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  44140. defaultTextures[ glTextureType ] = textureGPU;
  44141. }
  44142. backend.set( texture, {
  44143. textureGPU,
  44144. glTextureType,
  44145. isDefault: true
  44146. } );
  44147. }
  44148. /**
  44149. * Defines a texture on the GPU for the given texture object.
  44150. *
  44151. * @param {Texture} texture - The texture.
  44152. * @param {Object} [options={}] - Optional configuration parameter.
  44153. * @return {undefined}
  44154. */
  44155. createTexture( texture, options ) {
  44156. const { gl, backend } = this;
  44157. const { levels, width, height, depth } = options;
  44158. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  44159. const glType = backend.utils.convert( texture.type );
  44160. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  44161. const textureGPU = gl.createTexture();
  44162. const glTextureType = this.getGLTextureType( texture );
  44163. backend.state.bindTexture( glTextureType, textureGPU );
  44164. this.setTextureParameters( glTextureType, texture );
  44165. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  44166. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  44167. } else if ( texture.isData3DTexture ) {
  44168. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  44169. } else if ( ! texture.isVideoTexture ) {
  44170. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  44171. }
  44172. backend.set( texture, {
  44173. textureGPU,
  44174. glTextureType,
  44175. glFormat,
  44176. glType,
  44177. glInternalFormat
  44178. } );
  44179. }
  44180. /**
  44181. * Uploads texture buffer data to the GPU memory.
  44182. *
  44183. * @param {WebGLBuffer} buffer - The buffer data.
  44184. * @param {Texture} texture - The texture,
  44185. */
  44186. copyBufferToTexture( buffer, texture ) {
  44187. const { gl, backend } = this;
  44188. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  44189. const { width, height } = texture.source.data;
  44190. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  44191. backend.state.bindTexture( glTextureType, textureGPU );
  44192. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  44193. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  44194. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  44195. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  44196. backend.state.unbindTexture();
  44197. // debug
  44198. // const framebuffer = gl.createFramebuffer();
  44199. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  44200. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  44201. // const readout = new Float32Array( width * height * 4 );
  44202. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  44203. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  44204. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  44205. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  44206. // console.log( readout );
  44207. }
  44208. /**
  44209. * Uploads the updated texture data to the GPU.
  44210. *
  44211. * @param {Texture} texture - The texture.
  44212. * @param {Object} [options={}] - Optional configuration parameter.
  44213. */
  44214. updateTexture( texture, options ) {
  44215. const { gl } = this;
  44216. const { width, height } = options;
  44217. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  44218. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  44219. return;
  44220. this.backend.state.bindTexture( glTextureType, textureGPU );
  44221. this.setTextureParameters( glTextureType, texture );
  44222. if ( texture.isCompressedTexture ) {
  44223. const mipmaps = texture.mipmaps;
  44224. const image = options.image;
  44225. for ( let i = 0; i < mipmaps.length; i ++ ) {
  44226. const mipmap = mipmaps[ i ];
  44227. if ( texture.isCompressedArrayTexture ) {
  44228. if ( texture.format !== gl.RGBA ) {
  44229. if ( glFormat !== null ) {
  44230. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  44231. } else {
  44232. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  44233. }
  44234. } else {
  44235. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  44236. }
  44237. } else {
  44238. if ( glFormat !== null ) {
  44239. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  44240. } else {
  44241. console.warn( 'Unsupported compressed texture format' );
  44242. }
  44243. }
  44244. }
  44245. } else if ( texture.isCubeTexture ) {
  44246. const images = options.images;
  44247. const mipmaps = texture.mipmaps;
  44248. for ( let i = 0; i < 6; i ++ ) {
  44249. const image = getImage( images[ i ] );
  44250. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  44251. for ( let j = 0; j < mipmaps.length; j ++ ) {
  44252. const mipmap = mipmaps[ j ];
  44253. const image = getImage( mipmap.images[ i ] );
  44254. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  44255. }
  44256. }
  44257. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  44258. const image = options.image;
  44259. if ( texture.layerUpdates.size > 0 ) {
  44260. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  44261. for ( const layerIndex of texture.layerUpdates ) {
  44262. const layerData = image.data.subarray(
  44263. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  44264. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  44265. );
  44266. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  44267. }
  44268. texture.clearLayerUpdates();
  44269. } else {
  44270. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  44271. }
  44272. } else if ( texture.isData3DTexture ) {
  44273. const image = options.image;
  44274. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  44275. } else if ( texture.isVideoTexture ) {
  44276. texture.update();
  44277. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  44278. } else {
  44279. const mipmaps = texture.mipmaps;
  44280. if ( mipmaps.length > 0 ) {
  44281. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  44282. const mipmap = mipmaps[ i ];
  44283. const image = getImage( mipmap );
  44284. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  44285. }
  44286. } else {
  44287. const image = getImage( options.image );
  44288. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  44289. }
  44290. }
  44291. }
  44292. /**
  44293. * Generates mipmaps for the given texture.
  44294. *
  44295. * @param {Texture} texture - The texture.
  44296. */
  44297. generateMipmaps( texture ) {
  44298. const { gl, backend } = this;
  44299. const { textureGPU, glTextureType } = backend.get( texture );
  44300. backend.state.bindTexture( glTextureType, textureGPU );
  44301. gl.generateMipmap( glTextureType );
  44302. }
  44303. /**
  44304. * Deallocates the render buffers of the given render target.
  44305. *
  44306. * @param {RenderTarget} renderTarget - The render target.
  44307. */
  44308. deallocateRenderBuffers( renderTarget ) {
  44309. const { gl, backend } = this;
  44310. // remove framebuffer reference
  44311. if ( renderTarget ) {
  44312. const renderContextData = backend.get( renderTarget );
  44313. renderContextData.renderBufferStorageSetup = undefined;
  44314. if ( renderContextData.framebuffers ) {
  44315. for ( const cacheKey in renderContextData.framebuffers ) {
  44316. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  44317. }
  44318. delete renderContextData.framebuffers;
  44319. }
  44320. if ( renderContextData.depthRenderbuffer ) {
  44321. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  44322. delete renderContextData.depthRenderbuffer;
  44323. }
  44324. if ( renderContextData.stencilRenderbuffer ) {
  44325. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  44326. delete renderContextData.stencilRenderbuffer;
  44327. }
  44328. if ( renderContextData.msaaFrameBuffer ) {
  44329. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  44330. delete renderContextData.msaaFrameBuffer;
  44331. }
  44332. if ( renderContextData.msaaRenderbuffers ) {
  44333. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  44334. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  44335. }
  44336. delete renderContextData.msaaRenderbuffers;
  44337. }
  44338. }
  44339. }
  44340. /**
  44341. * Destroys the GPU data for the given texture object.
  44342. *
  44343. * @param {Texture} texture - The texture.
  44344. */
  44345. destroyTexture( texture ) {
  44346. const { gl, backend } = this;
  44347. const { textureGPU, renderTarget } = backend.get( texture );
  44348. this.deallocateRenderBuffers( renderTarget );
  44349. gl.deleteTexture( textureGPU );
  44350. backend.delete( texture );
  44351. }
  44352. /**
  44353. * Copies data of the given source texture to the given destination texture.
  44354. *
  44355. * @param {Texture} srcTexture - The source texture.
  44356. * @param {Texture} dstTexture - The destination texture.
  44357. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44358. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44359. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44360. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44361. */
  44362. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44363. const { gl, backend } = this;
  44364. const { state } = this.backend;
  44365. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  44366. state.bindTexture( glTextureType, dstTextureGPU );
  44367. // gather the necessary dimensions to copy
  44368. let width, height, depth, minX, minY, minZ;
  44369. let dstX, dstY, dstZ;
  44370. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  44371. if ( srcRegion !== null ) {
  44372. width = srcRegion.max.x - srcRegion.min.x;
  44373. height = srcRegion.max.y - srcRegion.min.y;
  44374. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  44375. minX = srcRegion.min.x;
  44376. minY = srcRegion.min.y;
  44377. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  44378. } else {
  44379. const levelScale = Math.pow( 2, - srcLevel );
  44380. width = Math.floor( image.width * levelScale );
  44381. height = Math.floor( image.height * levelScale );
  44382. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  44383. depth = image.depth;
  44384. } else if ( srcTexture.isData3DTexture ) {
  44385. depth = Math.floor( image.depth * levelScale );
  44386. } else {
  44387. depth = 1;
  44388. }
  44389. minX = 0;
  44390. minY = 0;
  44391. minZ = 0;
  44392. }
  44393. if ( dstPosition !== null ) {
  44394. dstX = dstPosition.x;
  44395. dstY = dstPosition.y;
  44396. dstZ = dstPosition.z;
  44397. } else {
  44398. dstX = 0;
  44399. dstY = 0;
  44400. dstZ = 0;
  44401. }
  44402. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  44403. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  44404. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  44405. // used for copying data from cpu
  44406. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  44407. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  44408. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  44409. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  44410. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  44411. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  44412. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  44413. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  44414. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  44415. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  44416. // set up the src texture
  44417. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  44418. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  44419. const srcTextureData = backend.get( srcTexture );
  44420. const dstTextureData = backend.get( dstTexture );
  44421. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  44422. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  44423. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  44424. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  44425. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  44426. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  44427. let mask = gl.COLOR_BUFFER_BIT;
  44428. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  44429. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  44430. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  44431. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  44432. } else {
  44433. if ( isDst3D ) {
  44434. // copy data into the 3d texture
  44435. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  44436. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  44437. } else if ( dstTexture.isCompressedArrayTexture ) {
  44438. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  44439. } else {
  44440. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  44441. }
  44442. } else {
  44443. // copy data into the 2d texture
  44444. if ( srcTexture.isDataTexture ) {
  44445. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  44446. } else if ( srcTexture.isCompressedTexture ) {
  44447. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  44448. } else {
  44449. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  44450. }
  44451. }
  44452. }
  44453. // reset values
  44454. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  44455. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  44456. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  44457. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  44458. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  44459. // Generate mipmaps only when copying level 0
  44460. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  44461. gl.generateMipmap( glTextureType );
  44462. }
  44463. state.unbindTexture();
  44464. }
  44465. /**
  44466. * Copies the current bound framebuffer to the given texture.
  44467. *
  44468. * @param {Texture} texture - The destination texture.
  44469. * @param {RenderContext} renderContext - The render context.
  44470. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44471. */
  44472. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  44473. const { gl } = this;
  44474. const { state } = this.backend;
  44475. const { textureGPU } = this.backend.get( texture );
  44476. const { x, y, z: width, w: height } = rectangle;
  44477. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  44478. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  44479. if ( requireDrawFrameBuffer ) {
  44480. const partial = ( x !== 0 || y !== 0 );
  44481. let mask;
  44482. let attachment;
  44483. if ( texture.isDepthTexture === true ) {
  44484. mask = gl.DEPTH_BUFFER_BIT;
  44485. attachment = gl.DEPTH_ATTACHMENT;
  44486. if ( renderContext.stencil ) {
  44487. mask |= gl.STENCIL_BUFFER_BIT;
  44488. }
  44489. } else {
  44490. mask = gl.COLOR_BUFFER_BIT;
  44491. attachment = gl.COLOR_ATTACHMENT0;
  44492. }
  44493. if ( partial ) {
  44494. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  44495. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  44496. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44497. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44498. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  44499. const flippedY = srcHeight - y - height;
  44500. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  44501. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  44502. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  44503. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  44504. state.unbindTexture();
  44505. } else {
  44506. const fb = gl.createFramebuffer();
  44507. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44508. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  44509. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  44510. gl.deleteFramebuffer( fb );
  44511. }
  44512. } else {
  44513. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  44514. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  44515. state.unbindTexture();
  44516. }
  44517. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  44518. this.backend._setFramebuffer( renderContext );
  44519. }
  44520. /**
  44521. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  44522. *
  44523. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  44524. * @param {RenderContext} renderContext - The render context.
  44525. * @param {number} samples - The MSAA sample count.
  44526. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  44527. */
  44528. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  44529. const { gl } = this;
  44530. const renderTarget = renderContext.renderTarget;
  44531. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  44532. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44533. if ( depthBuffer && ! stencilBuffer ) {
  44534. let glInternalFormat = gl.DEPTH_COMPONENT24;
  44535. if ( useMultisampledRTT === true ) {
  44536. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44537. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  44538. } else if ( samples > 0 ) {
  44539. if ( depthTexture && depthTexture.isDepthTexture ) {
  44540. if ( depthTexture.type === gl.FLOAT ) {
  44541. glInternalFormat = gl.DEPTH_COMPONENT32F;
  44542. }
  44543. }
  44544. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  44545. } else {
  44546. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  44547. }
  44548. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  44549. } else if ( depthBuffer && stencilBuffer ) {
  44550. if ( samples > 0 ) {
  44551. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  44552. } else {
  44553. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  44554. }
  44555. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  44556. }
  44557. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  44558. }
  44559. /**
  44560. * Returns texture data as a typed array.
  44561. *
  44562. * @async
  44563. * @param {Texture} texture - The texture to copy.
  44564. * @param {number} x - The x coordinate of the copy origin.
  44565. * @param {number} y - The y coordinate of the copy origin.
  44566. * @param {number} width - The width of the copy.
  44567. * @param {number} height - The height of the copy.
  44568. * @param {number} faceIndex - The face index.
  44569. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44570. */
  44571. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44572. const { backend, gl } = this;
  44573. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  44574. const fb = gl.createFramebuffer();
  44575. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  44576. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  44577. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  44578. const typedArrayType = this._getTypedArrayType( glType );
  44579. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  44580. const elementCount = width * height;
  44581. const byteLength = elementCount * bytesPerTexel;
  44582. const buffer = gl.createBuffer();
  44583. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  44584. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  44585. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  44586. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  44587. await backend.utils._clientWaitAsync();
  44588. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  44589. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  44590. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  44591. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  44592. gl.deleteFramebuffer( fb );
  44593. return dstBuffer;
  44594. }
  44595. /**
  44596. * Returns the corresponding typed array type for the given WebGL data type.
  44597. *
  44598. * @private
  44599. * @param {GLenum} glType - The WebGL data type.
  44600. * @return {TypedArray.constructor} The typed array type.
  44601. */
  44602. _getTypedArrayType( glType ) {
  44603. const { gl } = this;
  44604. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  44605. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  44606. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  44607. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  44608. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  44609. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  44610. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  44611. if ( glType === gl.FLOAT ) return Float32Array;
  44612. throw new Error( `Unsupported WebGL type: ${glType}` );
  44613. }
  44614. /**
  44615. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  44616. *
  44617. * @private
  44618. * @param {GLenum} glType - The WebGL data type.
  44619. * @param {GLenum} glFormat - The WebGL texture format.
  44620. * @return {number} The bytes-per-texel.
  44621. */
  44622. _getBytesPerTexel( glType, glFormat ) {
  44623. const { gl } = this;
  44624. let bytesPerComponent = 0;
  44625. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  44626. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  44627. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  44628. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  44629. glType === gl.UNSIGNED_SHORT ||
  44630. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  44631. if ( glType === gl.UNSIGNED_INT ||
  44632. glType === gl.FLOAT ) bytesPerComponent = 4;
  44633. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  44634. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  44635. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  44636. }
  44637. }
  44638. function getImage( source ) {
  44639. if ( source.isDataTexture ) {
  44640. return source.image.data;
  44641. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  44642. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  44643. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  44644. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  44645. return source;
  44646. }
  44647. return source.data;
  44648. }
  44649. /**
  44650. * A WebGL 2 backend utility module for managing extensions.
  44651. *
  44652. * @private
  44653. */
  44654. class WebGLExtensions {
  44655. /**
  44656. * Constructs a new utility object.
  44657. *
  44658. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44659. */
  44660. constructor( backend ) {
  44661. /**
  44662. * A reference to the WebGL 2 backend.
  44663. *
  44664. * @type {WebGLBackend}
  44665. */
  44666. this.backend = backend;
  44667. /**
  44668. * A reference to the rendering context.
  44669. *
  44670. * @type {WebGL2RenderingContext}
  44671. */
  44672. this.gl = this.backend.gl;
  44673. /**
  44674. * A list with all the supported WebGL extensions.
  44675. *
  44676. * @type {Array<string>}
  44677. */
  44678. this.availableExtensions = this.gl.getSupportedExtensions();
  44679. /**
  44680. * A dictionary with requested WebGL extensions.
  44681. * The key is the name of the extension, the value
  44682. * the requested extension object.
  44683. *
  44684. * @type {Object<string,Object>}
  44685. */
  44686. this.extensions = {};
  44687. }
  44688. /**
  44689. * Returns the extension object for the given extension name.
  44690. *
  44691. * @param {string} name - The extension name.
  44692. * @return {Object} The extension object.
  44693. */
  44694. get( name ) {
  44695. let extension = this.extensions[ name ];
  44696. if ( extension === undefined ) {
  44697. extension = this.gl.getExtension( name );
  44698. this.extensions[ name ] = extension;
  44699. }
  44700. return extension;
  44701. }
  44702. /**
  44703. * Returns `true` if the requested extension is available.
  44704. *
  44705. * @param {string} name - The extension name.
  44706. * @return {boolean} Whether the given extension is available or not.
  44707. */
  44708. has( name ) {
  44709. return this.availableExtensions.includes( name );
  44710. }
  44711. }
  44712. /**
  44713. * A WebGL 2 backend utility module for managing the device's capabilities.
  44714. *
  44715. * @private
  44716. */
  44717. class WebGLCapabilities {
  44718. /**
  44719. * Constructs a new utility object.
  44720. *
  44721. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44722. */
  44723. constructor( backend ) {
  44724. /**
  44725. * A reference to the WebGL 2 backend.
  44726. *
  44727. * @type {WebGLBackend}
  44728. */
  44729. this.backend = backend;
  44730. /**
  44731. * This value holds the cached max anisotropy value.
  44732. *
  44733. * @type {?number}
  44734. * @default null
  44735. */
  44736. this.maxAnisotropy = null;
  44737. }
  44738. /**
  44739. * Returns the maximum anisotropy texture filtering value. This value
  44740. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  44741. * WebGL extension.
  44742. *
  44743. * @return {number} The maximum anisotropy texture filtering value.
  44744. */
  44745. getMaxAnisotropy() {
  44746. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  44747. const gl = this.backend.gl;
  44748. const extensions = this.backend.extensions;
  44749. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44750. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44751. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44752. } else {
  44753. this.maxAnisotropy = 0;
  44754. }
  44755. return this.maxAnisotropy;
  44756. }
  44757. }
  44758. const GLFeatureName = {
  44759. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  44760. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  44761. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  44762. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  44763. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  44764. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  44765. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  44766. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  44767. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  44768. 'OVR_multiview2': 'OVR_multiview2'
  44769. };
  44770. class WebGLBufferRenderer {
  44771. constructor( backend ) {
  44772. this.gl = backend.gl;
  44773. this.extensions = backend.extensions;
  44774. this.info = backend.renderer.info;
  44775. this.mode = null;
  44776. this.index = 0;
  44777. this.type = null;
  44778. this.object = null;
  44779. }
  44780. render( start, count ) {
  44781. const { gl, mode, object, type, info, index } = this;
  44782. if ( index !== 0 ) {
  44783. gl.drawElements( mode, count, type, start );
  44784. } else {
  44785. gl.drawArrays( mode, start, count );
  44786. }
  44787. info.update( object, count, 1 );
  44788. }
  44789. renderInstances( start, count, primcount ) {
  44790. const { gl, mode, type, index, object, info } = this;
  44791. if ( primcount === 0 ) return;
  44792. if ( index !== 0 ) {
  44793. gl.drawElementsInstanced( mode, count, type, start, primcount );
  44794. } else {
  44795. gl.drawArraysInstanced( mode, start, count, primcount );
  44796. }
  44797. info.update( object, count, primcount );
  44798. }
  44799. renderMultiDraw( starts, counts, drawCount ) {
  44800. const { extensions, mode, object, info } = this;
  44801. if ( drawCount === 0 ) return;
  44802. const extension = extensions.get( 'WEBGL_multi_draw' );
  44803. if ( extension === null ) {
  44804. for ( let i = 0; i < drawCount; i ++ ) {
  44805. this.render( starts[ i ], counts[ i ] );
  44806. }
  44807. } else {
  44808. if ( this.index !== 0 ) {
  44809. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  44810. } else {
  44811. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44812. }
  44813. let elementCount = 0;
  44814. for ( let i = 0; i < drawCount; i ++ ) {
  44815. elementCount += counts[ i ];
  44816. }
  44817. info.update( object, elementCount, 1 );
  44818. }
  44819. }
  44820. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44821. const { extensions, mode, object, info } = this;
  44822. if ( drawCount === 0 ) return;
  44823. const extension = extensions.get( 'WEBGL_multi_draw' );
  44824. if ( extension === null ) {
  44825. for ( let i = 0; i < drawCount; i ++ ) {
  44826. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44827. }
  44828. } else {
  44829. if ( this.index !== 0 ) {
  44830. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  44831. } else {
  44832. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44833. }
  44834. let elementCount = 0;
  44835. for ( let i = 0; i < drawCount; i ++ ) {
  44836. elementCount += counts[ i ] * primcount[ i ];
  44837. }
  44838. info.update( object, elementCount, 1 );
  44839. }
  44840. }
  44841. //
  44842. }
  44843. /**
  44844. * Abstract base class of a timestamp query pool.
  44845. *
  44846. * @abstract
  44847. */
  44848. class TimestampQueryPool {
  44849. /**
  44850. * Creates a new timestamp query pool.
  44851. *
  44852. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  44853. */
  44854. constructor( maxQueries = 256 ) {
  44855. /**
  44856. * Whether to track timestamps or not.
  44857. *
  44858. * @type {boolean}
  44859. * @default true
  44860. */
  44861. this.trackTimestamp = true;
  44862. /**
  44863. * Maximum number of queries this pool can hold.
  44864. *
  44865. * @type {number}
  44866. * @default 256
  44867. */
  44868. this.maxQueries = maxQueries;
  44869. /**
  44870. * How many queries allocated so far.
  44871. *
  44872. * @type {number}
  44873. * @default 0
  44874. */
  44875. this.currentQueryIndex = 0;
  44876. /**
  44877. * Tracks offsets for different contexts.
  44878. *
  44879. * @type {Map<string, number>}
  44880. */
  44881. this.queryOffsets = new Map();
  44882. /**
  44883. * Whether the pool has been disposed or not.
  44884. *
  44885. * @type {boolean}
  44886. * @default false
  44887. */
  44888. this.isDisposed = false;
  44889. /**
  44890. * TODO
  44891. *
  44892. * @type {number}
  44893. * @default 0
  44894. */
  44895. this.lastValue = 0;
  44896. /**
  44897. * TODO
  44898. *
  44899. * @type {boolean}
  44900. * @default false
  44901. */
  44902. this.pendingResolve = false;
  44903. }
  44904. /**
  44905. * Allocate queries for a specific renderContext.
  44906. *
  44907. * @abstract
  44908. * @param {Object} renderContext - The render context to allocate queries for.
  44909. * @returns {?number}
  44910. */
  44911. allocateQueriesForContext( /* renderContext */ ) {}
  44912. /**
  44913. * Resolve all timestamps and return data (or process them).
  44914. *
  44915. * @abstract
  44916. * @async
  44917. * @returns {Promise<number>|number} The resolved timestamp value.
  44918. */
  44919. async resolveQueriesAsync() {}
  44920. /**
  44921. * Dispose of the query pool.
  44922. *
  44923. * @abstract
  44924. */
  44925. dispose() {}
  44926. }
  44927. /**
  44928. * Manages a pool of WebGL timestamp queries for performance measurement.
  44929. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  44930. *
  44931. * @augments TimestampQueryPool
  44932. */
  44933. class WebGLTimestampQueryPool extends TimestampQueryPool {
  44934. /**
  44935. * Creates a new WebGL timestamp query pool.
  44936. *
  44937. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  44938. * @param {string} type - The type identifier for this query pool.
  44939. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  44940. */
  44941. constructor( gl, type, maxQueries = 2048 ) {
  44942. super( maxQueries );
  44943. this.gl = gl;
  44944. this.type = type;
  44945. // Check for timer query extensions
  44946. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  44947. gl.getExtension( 'EXT_disjoint_timer_query' );
  44948. if ( ! this.ext ) {
  44949. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  44950. this.trackTimestamp = false;
  44951. return;
  44952. }
  44953. // Create query objects
  44954. this.queries = [];
  44955. for ( let i = 0; i < this.maxQueries; i ++ ) {
  44956. this.queries.push( gl.createQuery() );
  44957. }
  44958. this.activeQuery = null;
  44959. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  44960. }
  44961. /**
  44962. * Allocates a pair of queries for a given render context.
  44963. *
  44964. * @param {Object} renderContext - The render context to allocate queries for.
  44965. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  44966. */
  44967. allocateQueriesForContext( renderContext ) {
  44968. if ( ! this.trackTimestamp ) return null;
  44969. // Check if we have enough space for a new query pair
  44970. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  44971. 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() } ).` );
  44972. return null;
  44973. }
  44974. const baseOffset = this.currentQueryIndex;
  44975. this.currentQueryIndex += 2;
  44976. // Initialize query states
  44977. this.queryStates.set( baseOffset, 'inactive' );
  44978. this.queryOffsets.set( renderContext.id, baseOffset );
  44979. return baseOffset;
  44980. }
  44981. /**
  44982. * Begins a timestamp query for the specified render context.
  44983. *
  44984. * @param {Object} renderContext - The render context to begin timing for.
  44985. */
  44986. beginQuery( renderContext ) {
  44987. if ( ! this.trackTimestamp || this.isDisposed ) {
  44988. return;
  44989. }
  44990. const baseOffset = this.queryOffsets.get( renderContext.id );
  44991. if ( baseOffset == null ) {
  44992. return;
  44993. }
  44994. // Don't start a new query if there's an active one
  44995. if ( this.activeQuery !== null ) {
  44996. return;
  44997. }
  44998. const query = this.queries[ baseOffset ];
  44999. if ( ! query ) {
  45000. return;
  45001. }
  45002. try {
  45003. // Only begin if query is inactive
  45004. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  45005. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  45006. this.activeQuery = baseOffset;
  45007. this.queryStates.set( baseOffset, 'started' );
  45008. }
  45009. } catch ( error ) {
  45010. console.error( 'Error in beginQuery:', error );
  45011. this.activeQuery = null;
  45012. this.queryStates.set( baseOffset, 'inactive' );
  45013. }
  45014. }
  45015. /**
  45016. * Ends the active timestamp query for the specified render context.
  45017. *
  45018. * @param {Object} renderContext - The render context to end timing for.
  45019. * @param {string} renderContext.id - Unique identifier for the render context.
  45020. */
  45021. endQuery( renderContext ) {
  45022. if ( ! this.trackTimestamp || this.isDisposed ) {
  45023. return;
  45024. }
  45025. const baseOffset = this.queryOffsets.get( renderContext.id );
  45026. if ( baseOffset == null ) {
  45027. return;
  45028. }
  45029. // Only end if this is the active query
  45030. if ( this.activeQuery !== baseOffset ) {
  45031. return;
  45032. }
  45033. try {
  45034. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  45035. this.queryStates.set( baseOffset, 'ended' );
  45036. this.activeQuery = null;
  45037. } catch ( error ) {
  45038. console.error( 'Error in endQuery:', error );
  45039. // Reset state on error
  45040. this.queryStates.set( baseOffset, 'inactive' );
  45041. this.activeQuery = null;
  45042. }
  45043. }
  45044. /**
  45045. * Asynchronously resolves all completed queries and returns the total duration.
  45046. *
  45047. * @async
  45048. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  45049. */
  45050. async resolveQueriesAsync() {
  45051. if ( ! this.trackTimestamp || this.pendingResolve ) {
  45052. return this.lastValue;
  45053. }
  45054. this.pendingResolve = true;
  45055. try {
  45056. // Wait for all ended queries to complete
  45057. const resolvePromises = [];
  45058. for ( const [ baseOffset, state ] of this.queryStates ) {
  45059. if ( state === 'ended' ) {
  45060. const query = this.queries[ baseOffset ];
  45061. resolvePromises.push( this.resolveQuery( query ) );
  45062. }
  45063. }
  45064. if ( resolvePromises.length === 0 ) {
  45065. return this.lastValue;
  45066. }
  45067. const results = await Promise.all( resolvePromises );
  45068. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  45069. // Store the last valid result
  45070. this.lastValue = totalDuration;
  45071. // Reset states
  45072. this.currentQueryIndex = 0;
  45073. this.queryOffsets.clear();
  45074. this.queryStates.clear();
  45075. this.activeQuery = null;
  45076. return totalDuration;
  45077. } catch ( error ) {
  45078. console.error( 'Error resolving queries:', error );
  45079. return this.lastValue;
  45080. } finally {
  45081. this.pendingResolve = false;
  45082. }
  45083. }
  45084. /**
  45085. * Resolves a single query, checking for completion and disjoint operation.
  45086. *
  45087. * @async
  45088. * @param {WebGLQuery} query - The query object to resolve.
  45089. * @returns {Promise<number>} The elapsed time in milliseconds.
  45090. */
  45091. async resolveQuery( query ) {
  45092. return new Promise( ( resolve ) => {
  45093. if ( this.isDisposed ) {
  45094. resolve( this.lastValue );
  45095. return;
  45096. }
  45097. let timeoutId;
  45098. let isResolved = false;
  45099. const cleanup = () => {
  45100. if ( timeoutId ) {
  45101. clearTimeout( timeoutId );
  45102. timeoutId = null;
  45103. }
  45104. };
  45105. const finalizeResolution = ( value ) => {
  45106. if ( ! isResolved ) {
  45107. isResolved = true;
  45108. cleanup();
  45109. resolve( value );
  45110. }
  45111. };
  45112. const checkQuery = () => {
  45113. if ( this.isDisposed ) {
  45114. finalizeResolution( this.lastValue );
  45115. return;
  45116. }
  45117. try {
  45118. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  45119. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  45120. if ( disjoint ) {
  45121. finalizeResolution( this.lastValue );
  45122. return;
  45123. }
  45124. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  45125. if ( ! available ) {
  45126. timeoutId = setTimeout( checkQuery, 1 );
  45127. return;
  45128. }
  45129. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  45130. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  45131. } catch ( error ) {
  45132. console.error( 'Error checking query:', error );
  45133. resolve( this.lastValue );
  45134. }
  45135. };
  45136. checkQuery();
  45137. } );
  45138. }
  45139. /**
  45140. * Releases all resources held by this query pool.
  45141. * This includes deleting all query objects and clearing internal state.
  45142. */
  45143. dispose() {
  45144. if ( this.isDisposed ) {
  45145. return;
  45146. }
  45147. this.isDisposed = true;
  45148. if ( ! this.trackTimestamp ) return;
  45149. for ( const query of this.queries ) {
  45150. this.gl.deleteQuery( query );
  45151. }
  45152. this.queries = [];
  45153. this.queryStates.clear();
  45154. this.queryOffsets.clear();
  45155. this.lastValue = 0;
  45156. this.activeQuery = null;
  45157. }
  45158. }
  45159. /**
  45160. * A backend implementation targeting WebGL 2.
  45161. *
  45162. * @private
  45163. * @augments Backend
  45164. */
  45165. class WebGLBackend extends Backend {
  45166. /**
  45167. * WebGLBackend options.
  45168. *
  45169. * @typedef {Object} WebGLBackend~Options
  45170. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  45171. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  45172. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  45173. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  45174. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  45175. * @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.
  45176. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  45177. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  45178. */
  45179. /**
  45180. * Constructs a new WebGPU backend.
  45181. *
  45182. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  45183. */
  45184. constructor( parameters = {} ) {
  45185. super( parameters );
  45186. /**
  45187. * This flag can be used for type testing.
  45188. *
  45189. * @type {boolean}
  45190. * @readonly
  45191. * @default true
  45192. */
  45193. this.isWebGLBackend = true;
  45194. /**
  45195. * A reference to a backend module holding shader attribute-related
  45196. * utility functions.
  45197. *
  45198. * @type {?WebGLAttributeUtils}
  45199. * @default null
  45200. */
  45201. this.attributeUtils = null;
  45202. /**
  45203. * A reference to a backend module holding extension-related
  45204. * utility functions.
  45205. *
  45206. * @type {?WebGLExtensions}
  45207. * @default null
  45208. */
  45209. this.extensions = null;
  45210. /**
  45211. * A reference to a backend module holding capability-related
  45212. * utility functions.
  45213. *
  45214. * @type {?WebGLCapabilities}
  45215. * @default null
  45216. */
  45217. this.capabilities = null;
  45218. /**
  45219. * A reference to a backend module holding texture-related
  45220. * utility functions.
  45221. *
  45222. * @type {?WebGLTextureUtils}
  45223. * @default null
  45224. */
  45225. this.textureUtils = null;
  45226. /**
  45227. * A reference to a backend module holding renderer-related
  45228. * utility functions.
  45229. *
  45230. * @type {?WebGLBufferRenderer}
  45231. * @default null
  45232. */
  45233. this.bufferRenderer = null;
  45234. /**
  45235. * A reference to the rendering context.
  45236. *
  45237. * @type {?WebGL2RenderingContext}
  45238. * @default null
  45239. */
  45240. this.gl = null;
  45241. /**
  45242. * A reference to a backend module holding state-related
  45243. * utility functions.
  45244. *
  45245. * @type {?WebGLState}
  45246. * @default null
  45247. */
  45248. this.state = null;
  45249. /**
  45250. * A reference to a backend module holding common
  45251. * utility functions.
  45252. *
  45253. * @type {?WebGLUtils}
  45254. * @default null
  45255. */
  45256. this.utils = null;
  45257. /**
  45258. * Dictionary for caching VAOs.
  45259. *
  45260. * @type {Object<string,WebGLVertexArrayObject>}
  45261. */
  45262. this.vaoCache = {};
  45263. /**
  45264. * Dictionary for caching transform feedback objects.
  45265. *
  45266. * @type {Object<string,WebGLTransformFeedback>}
  45267. */
  45268. this.transformFeedbackCache = {};
  45269. /**
  45270. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  45271. * Only relevant when using compute shaders.
  45272. *
  45273. * @type {boolean}
  45274. * @default false
  45275. */
  45276. this.discard = false;
  45277. /**
  45278. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  45279. * device does not support the extension.
  45280. *
  45281. * @type {?EXTDisjointTimerQueryWebGL2}
  45282. * @default null
  45283. */
  45284. this.disjoint = null;
  45285. /**
  45286. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  45287. * device does not support the extension.
  45288. *
  45289. * @type {?KHRParallelShaderCompile}
  45290. * @default null
  45291. */
  45292. this.parallel = null;
  45293. /**
  45294. * A reference to the current render context.
  45295. *
  45296. * @private
  45297. * @type {RenderContext}
  45298. * @default null
  45299. */
  45300. this._currentContext = null;
  45301. /**
  45302. * A unique collection of bindings.
  45303. *
  45304. * @private
  45305. * @type {WeakSet<Array<BindGroup>>}
  45306. */
  45307. this._knownBindings = new WeakSet();
  45308. /**
  45309. * Whether the device supports framebuffers invalidation or not.
  45310. *
  45311. * @private
  45312. * @type {boolean}
  45313. */
  45314. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  45315. /**
  45316. * The target framebuffer when rendering with
  45317. * the WebXR device API.
  45318. *
  45319. * @private
  45320. * @type {WebGLFramebuffer}
  45321. * @default null
  45322. */
  45323. this._xrFramebuffer = null;
  45324. }
  45325. /**
  45326. * Initializes the backend so it is ready for usage.
  45327. *
  45328. * @param {Renderer} renderer - The renderer.
  45329. */
  45330. init( renderer ) {
  45331. super.init( renderer );
  45332. //
  45333. const parameters = this.parameters;
  45334. const contextAttributes = {
  45335. antialias: renderer.samples > 0,
  45336. alpha: true, // always true for performance reasons
  45337. depth: renderer.depth,
  45338. stencil: renderer.stencil
  45339. };
  45340. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  45341. function onContextLost( event ) {
  45342. event.preventDefault();
  45343. const contextLossInfo = {
  45344. api: 'WebGL',
  45345. message: event.statusMessage || 'Unknown reason',
  45346. reason: null,
  45347. originalEvent: event
  45348. };
  45349. renderer.onDeviceLost( contextLossInfo );
  45350. }
  45351. this._onContextLost = onContextLost;
  45352. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  45353. this.gl = glContext;
  45354. this.extensions = new WebGLExtensions( this );
  45355. this.capabilities = new WebGLCapabilities( this );
  45356. this.attributeUtils = new WebGLAttributeUtils( this );
  45357. this.textureUtils = new WebGLTextureUtils( this );
  45358. this.bufferRenderer = new WebGLBufferRenderer( this );
  45359. this.state = new WebGLState( this );
  45360. this.utils = new WebGLUtils( this );
  45361. this.extensions.get( 'EXT_color_buffer_float' );
  45362. this.extensions.get( 'WEBGL_clip_cull_distance' );
  45363. this.extensions.get( 'OES_texture_float_linear' );
  45364. this.extensions.get( 'EXT_color_buffer_half_float' );
  45365. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  45366. this.extensions.get( 'WEBGL_render_shared_exponent' );
  45367. this.extensions.get( 'WEBGL_multi_draw' );
  45368. this.extensions.get( 'OVR_multiview2' );
  45369. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  45370. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  45371. }
  45372. /**
  45373. * The coordinate system of the backend.
  45374. *
  45375. * @type {number}
  45376. * @readonly
  45377. */
  45378. get coordinateSystem() {
  45379. return WebGLCoordinateSystem;
  45380. }
  45381. /**
  45382. * This method performs a readback operation by moving buffer data from
  45383. * a storage buffer attribute from the GPU to the CPU.
  45384. *
  45385. * @async
  45386. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45387. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45388. */
  45389. async getArrayBufferAsync( attribute ) {
  45390. return await this.attributeUtils.getArrayBufferAsync( attribute );
  45391. }
  45392. /**
  45393. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  45394. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  45395. *
  45396. * @async
  45397. * @return {Promise} A Promise that resolves when synchronization has been finished.
  45398. */
  45399. async waitForGPU() {
  45400. await this.utils._clientWaitAsync();
  45401. }
  45402. /**
  45403. * Ensures the backend is XR compatible.
  45404. *
  45405. * @async
  45406. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  45407. */
  45408. async makeXRCompatible() {
  45409. const attributes = this.gl.getContextAttributes();
  45410. if ( attributes.xrCompatible !== true ) {
  45411. await this.gl.makeXRCompatible();
  45412. }
  45413. }
  45414. /**
  45415. * Sets the XR rendering destination.
  45416. *
  45417. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  45418. */
  45419. setXRTarget( xrFramebuffer ) {
  45420. this._xrFramebuffer = xrFramebuffer;
  45421. }
  45422. /**
  45423. * Configures the given XR render target with external textures.
  45424. *
  45425. * This method is only relevant when using the WebXR Layers API.
  45426. *
  45427. * @param {XRRenderTarget} renderTarget - The XR render target.
  45428. * @param {WebGLTexture} colorTexture - A native color texture.
  45429. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  45430. */
  45431. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  45432. const gl = this.gl;
  45433. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  45434. if ( depthTexture !== null ) {
  45435. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  45436. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  45437. // The multisample_render_to_texture extension doesn't work properly if there
  45438. // are midframe flushes and an external depth texture.
  45439. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  45440. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  45441. }
  45442. renderTarget._autoAllocateDepthBuffer = false;
  45443. }
  45444. }
  45445. /**
  45446. * Inits a time stamp query for the given render context.
  45447. *
  45448. * @param {RenderContext} renderContext - The render context.
  45449. */
  45450. initTimestampQuery( renderContext ) {
  45451. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  45452. const type = renderContext.isComputeNode ? 'compute' : 'render';
  45453. if ( ! this.timestampQueryPool[ type ] ) {
  45454. // TODO: Variable maxQueries?
  45455. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  45456. }
  45457. const timestampQueryPool = this.timestampQueryPool[ type ];
  45458. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  45459. if ( baseOffset !== null ) {
  45460. timestampQueryPool.beginQuery( renderContext );
  45461. }
  45462. }
  45463. // timestamp utils
  45464. /**
  45465. * Prepares the timestamp buffer.
  45466. *
  45467. * @param {RenderContext} renderContext - The render context.
  45468. */
  45469. prepareTimestampBuffer( renderContext ) {
  45470. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  45471. const type = renderContext.isComputeNode ? 'compute' : 'render';
  45472. const timestampQueryPool = this.timestampQueryPool[ type ];
  45473. timestampQueryPool.endQuery( renderContext );
  45474. }
  45475. /**
  45476. * Returns the backend's rendering context.
  45477. *
  45478. * @return {WebGL2RenderingContext} The rendering context.
  45479. */
  45480. getContext() {
  45481. return this.gl;
  45482. }
  45483. /**
  45484. * This method is executed at the beginning of a render call and prepares
  45485. * the WebGL state for upcoming render calls
  45486. *
  45487. * @param {RenderContext} renderContext - The render context.
  45488. */
  45489. beginRender( renderContext ) {
  45490. const { state } = this;
  45491. const renderContextData = this.get( renderContext );
  45492. //
  45493. if ( renderContext.viewport ) {
  45494. this.updateViewport( renderContext );
  45495. } else {
  45496. const { width, height } = this.getDrawingBufferSize();
  45497. state.viewport( 0, 0, width, height );
  45498. }
  45499. if ( renderContext.scissor ) {
  45500. const { x, y, width, height } = renderContext.scissorValue;
  45501. state.scissor( x, renderContext.height - height - y, width, height );
  45502. }
  45503. //
  45504. this.initTimestampQuery( renderContext );
  45505. renderContextData.previousContext = this._currentContext;
  45506. this._currentContext = renderContext;
  45507. this._setFramebuffer( renderContext );
  45508. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  45509. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45510. if ( occlusionQueryCount > 0 ) {
  45511. // Get a reference to the array of objects with queries. The renderContextData property
  45512. // can be changed by another render pass before the async reading of all previous queries complete
  45513. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  45514. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  45515. renderContextData.lastOcclusionObject = null;
  45516. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  45517. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  45518. renderContextData.occlusionQueryIndex = 0;
  45519. }
  45520. }
  45521. /**
  45522. * This method is executed at the end of a render call and finalizes work
  45523. * after draw calls.
  45524. *
  45525. * @param {RenderContext} renderContext - The render context.
  45526. */
  45527. finishRender( renderContext ) {
  45528. const { gl, state } = this;
  45529. const renderContextData = this.get( renderContext );
  45530. const previousContext = renderContextData.previousContext;
  45531. state.resetVertexState();
  45532. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45533. if ( occlusionQueryCount > 0 ) {
  45534. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  45535. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  45536. }
  45537. this.resolveOccludedAsync( renderContext );
  45538. }
  45539. const textures = renderContext.textures;
  45540. if ( textures !== null ) {
  45541. for ( let i = 0; i < textures.length; i ++ ) {
  45542. const texture = textures[ i ];
  45543. if ( texture.generateMipmaps ) {
  45544. this.generateMipmaps( texture );
  45545. }
  45546. }
  45547. }
  45548. this._currentContext = previousContext;
  45549. const renderTarget = renderContext.renderTarget;
  45550. if ( renderContext.textures !== null && renderTarget ) {
  45551. const renderTargetContextData = this.get( renderTarget );
  45552. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  45553. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  45554. let mask = gl.COLOR_BUFFER_BIT;
  45555. if ( renderTarget.resolveDepthBuffer ) {
  45556. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  45557. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  45558. }
  45559. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  45560. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  45561. const textures = renderContext.textures;
  45562. const isMRT = textures.length > 1;
  45563. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  45564. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  45565. if ( isMRT ) {
  45566. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  45567. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  45568. for ( let i = 0; i < textures.length; i ++ ) {
  45569. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  45570. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  45571. }
  45572. }
  45573. for ( let i = 0; i < textures.length; i ++ ) {
  45574. if ( isMRT ) {
  45575. // configure attachment for resolve
  45576. const { textureGPU } = this.get( textures[ i ] );
  45577. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45578. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  45579. }
  45580. if ( renderContext.scissor ) {
  45581. const { x, y, width, height } = renderContext.scissorValue;
  45582. const viewY = renderContext.height - height - y;
  45583. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  45584. } else {
  45585. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  45586. }
  45587. }
  45588. if ( isMRT ) {
  45589. // restore attachments
  45590. for ( let i = 0; i < textures.length; i ++ ) {
  45591. const { textureGPU } = this.get( textures[ i ] );
  45592. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45593. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  45594. }
  45595. }
  45596. if ( this._supportsInvalidateFramebuffer === true ) {
  45597. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  45598. }
  45599. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  45600. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  45601. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  45602. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  45603. }
  45604. }
  45605. if ( previousContext !== null ) {
  45606. this._setFramebuffer( previousContext );
  45607. if ( previousContext.viewport ) {
  45608. this.updateViewport( previousContext );
  45609. } else {
  45610. const { width, height } = this.getDrawingBufferSize();
  45611. state.viewport( 0, 0, width, height );
  45612. }
  45613. }
  45614. this.prepareTimestampBuffer( renderContext );
  45615. }
  45616. /**
  45617. * This method processes the result of occlusion queries and writes it
  45618. * into render context data.
  45619. *
  45620. * @async
  45621. * @param {RenderContext} renderContext - The render context.
  45622. */
  45623. resolveOccludedAsync( renderContext ) {
  45624. const renderContextData = this.get( renderContext );
  45625. // handle occlusion query results
  45626. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  45627. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  45628. const occluded = new WeakSet();
  45629. const { gl } = this;
  45630. renderContextData.currentOcclusionQueryObjects = null;
  45631. renderContextData.currentOcclusionQueries = null;
  45632. const check = () => {
  45633. let completed = 0;
  45634. // check all queries and requeue as appropriate
  45635. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  45636. const query = currentOcclusionQueries[ i ];
  45637. if ( query === null ) continue;
  45638. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  45639. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  45640. currentOcclusionQueries[ i ] = null;
  45641. gl.deleteQuery( query );
  45642. completed ++;
  45643. }
  45644. }
  45645. if ( completed < currentOcclusionQueries.length ) {
  45646. requestAnimationFrame( check );
  45647. } else {
  45648. renderContextData.occluded = occluded;
  45649. }
  45650. };
  45651. check();
  45652. }
  45653. }
  45654. /**
  45655. * Returns `true` if the given 3D object is fully occluded by other
  45656. * 3D objects in the scene.
  45657. *
  45658. * @param {RenderContext} renderContext - The render context.
  45659. * @param {Object3D} object - The 3D object to test.
  45660. * @return {boolean} Whether the 3D object is fully occluded or not.
  45661. */
  45662. isOccluded( renderContext, object ) {
  45663. const renderContextData = this.get( renderContext );
  45664. return renderContextData.occluded && renderContextData.occluded.has( object );
  45665. }
  45666. /**
  45667. * Updates the viewport with the values from the given render context.
  45668. *
  45669. * @param {RenderContext} renderContext - The render context.
  45670. */
  45671. updateViewport( renderContext ) {
  45672. const { state } = this;
  45673. const { x, y, width, height } = renderContext.viewportValue;
  45674. state.viewport( x, renderContext.height - height - y, width, height );
  45675. }
  45676. /**
  45677. * Defines the scissor test.
  45678. *
  45679. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45680. */
  45681. setScissorTest( boolean ) {
  45682. const state = this.state;
  45683. state.setScissorTest( boolean );
  45684. }
  45685. /**
  45686. * Returns the clear color and alpha into a single
  45687. * color object.
  45688. *
  45689. * @return {Color4} The clear color.
  45690. */
  45691. getClearColor() {
  45692. const clearColor = super.getClearColor();
  45693. // Since the canvas is always created with alpha: true,
  45694. // WebGL must always premultiply the clear color.
  45695. clearColor.r *= clearColor.a;
  45696. clearColor.g *= clearColor.a;
  45697. clearColor.b *= clearColor.a;
  45698. return clearColor;
  45699. }
  45700. /**
  45701. * Performs a clear operation.
  45702. *
  45703. * @param {boolean} color - Whether the color buffer should be cleared or not.
  45704. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  45705. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  45706. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  45707. * @param {boolean} [setFrameBuffer=true] - TODO.
  45708. */
  45709. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  45710. const { gl, renderer } = this;
  45711. if ( descriptor === null ) {
  45712. const clearColor = this.getClearColor();
  45713. descriptor = {
  45714. textures: null,
  45715. clearColorValue: clearColor
  45716. };
  45717. }
  45718. //
  45719. let clear = 0;
  45720. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  45721. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  45722. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  45723. if ( clear !== 0 ) {
  45724. let clearColor;
  45725. if ( descriptor.clearColorValue ) {
  45726. clearColor = descriptor.clearColorValue;
  45727. } else {
  45728. clearColor = this.getClearColor();
  45729. }
  45730. const clearDepth = renderer.getClearDepth();
  45731. const clearStencil = renderer.getClearStencil();
  45732. if ( depth ) this.state.setDepthMask( true );
  45733. if ( descriptor.textures === null ) {
  45734. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  45735. gl.clear( clear );
  45736. } else {
  45737. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  45738. if ( color ) {
  45739. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  45740. if ( i === 0 ) {
  45741. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  45742. } else {
  45743. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  45744. }
  45745. }
  45746. }
  45747. if ( depth && stencil ) {
  45748. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  45749. } else if ( depth ) {
  45750. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  45751. } else if ( stencil ) {
  45752. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  45753. }
  45754. }
  45755. }
  45756. }
  45757. /**
  45758. * This method is executed at the beginning of a compute call and
  45759. * prepares the state for upcoming compute tasks.
  45760. *
  45761. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45762. */
  45763. beginCompute( computeGroup ) {
  45764. const { state, gl } = this;
  45765. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  45766. this.initTimestampQuery( computeGroup );
  45767. }
  45768. /**
  45769. * Executes a compute command for the given compute node.
  45770. *
  45771. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45772. * @param {Node} computeNode - The compute node.
  45773. * @param {Array<BindGroup>} bindings - The bindings.
  45774. * @param {ComputePipeline} pipeline - The compute pipeline.
  45775. * @param {number|null} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  45776. */
  45777. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  45778. const { state, gl } = this;
  45779. if ( this.discard === false ) {
  45780. // required here to handle async behaviour of render.compute()
  45781. gl.enable( gl.RASTERIZER_DISCARD );
  45782. this.discard = true;
  45783. }
  45784. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  45785. const vaoKey = this._getVaoKey( attributes );
  45786. const vaoGPU = this.vaoCache[ vaoKey ];
  45787. if ( vaoGPU === undefined ) {
  45788. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  45789. } else {
  45790. state.setVertexState( vaoGPU );
  45791. }
  45792. state.useProgram( programGPU );
  45793. this._bindUniforms( bindings );
  45794. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  45795. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  45796. gl.beginTransformFeedback( gl.POINTS );
  45797. count = ( count !== null ) ? count : computeNode.count;
  45798. if ( Array.isArray( count ) ) {
  45799. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  45800. count = count[ 0 ];
  45801. }
  45802. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  45803. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  45804. } else {
  45805. gl.drawArrays( gl.POINTS, 0, count );
  45806. }
  45807. gl.endTransformFeedback();
  45808. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  45809. // switch active buffers
  45810. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45811. const dualAttributeData = transformBuffers[ i ];
  45812. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  45813. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  45814. }
  45815. dualAttributeData.switchBuffers();
  45816. }
  45817. }
  45818. /**
  45819. * This method is executed at the end of a compute call and
  45820. * finalizes work after compute tasks.
  45821. *
  45822. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45823. */
  45824. finishCompute( computeGroup ) {
  45825. const gl = this.gl;
  45826. this.discard = false;
  45827. gl.disable( gl.RASTERIZER_DISCARD );
  45828. this.prepareTimestampBuffer( computeGroup );
  45829. if ( this._currentContext ) {
  45830. this._setFramebuffer( this._currentContext );
  45831. }
  45832. }
  45833. /**
  45834. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  45835. *
  45836. * @param {RenderContext} renderContext - The render context.
  45837. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  45838. *
  45839. * @private
  45840. */
  45841. _isRenderCameraDepthArray( renderContext ) {
  45842. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  45843. }
  45844. /**
  45845. * Executes a draw command for the given render object.
  45846. *
  45847. * @param {RenderObject} renderObject - The render object to draw.
  45848. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45849. */
  45850. draw( renderObject/*, info*/ ) {
  45851. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  45852. const { programGPU } = this.get( pipeline );
  45853. const { gl, state } = this;
  45854. const contextData = this.get( context );
  45855. const drawParams = renderObject.getDrawParameters();
  45856. if ( drawParams === null ) return;
  45857. //
  45858. this._bindUniforms( renderObject.getBindings() );
  45859. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  45860. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  45861. state.useProgram( programGPU );
  45862. // vertex state
  45863. const attributes = renderObject.getAttributes();
  45864. const attributesData = this.get( attributes );
  45865. let vaoGPU = attributesData.vaoGPU;
  45866. if ( vaoGPU === undefined ) {
  45867. const vaoKey = this._getVaoKey( attributes );
  45868. vaoGPU = this.vaoCache[ vaoKey ];
  45869. if ( vaoGPU === undefined ) {
  45870. vaoGPU = this._createVao( attributes );
  45871. this.vaoCache[ vaoKey ] = vaoGPU;
  45872. attributesData.vaoGPU = vaoGPU;
  45873. }
  45874. }
  45875. const index = renderObject.getIndex();
  45876. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  45877. state.setVertexState( vaoGPU, indexGPU );
  45878. //
  45879. const lastObject = contextData.lastOcclusionObject;
  45880. if ( lastObject !== object && lastObject !== undefined ) {
  45881. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45882. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  45883. contextData.occlusionQueryIndex ++;
  45884. }
  45885. if ( object.occlusionTest === true ) {
  45886. const query = gl.createQuery();
  45887. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  45888. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  45889. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  45890. }
  45891. contextData.lastOcclusionObject = object;
  45892. }
  45893. //
  45894. const renderer = this.bufferRenderer;
  45895. if ( object.isPoints ) renderer.mode = gl.POINTS;
  45896. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  45897. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  45898. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  45899. else {
  45900. if ( material.wireframe === true ) {
  45901. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  45902. renderer.mode = gl.LINES;
  45903. } else {
  45904. renderer.mode = gl.TRIANGLES;
  45905. }
  45906. }
  45907. //
  45908. const { vertexCount, instanceCount } = drawParams;
  45909. let { firstVertex } = drawParams;
  45910. renderer.object = object;
  45911. if ( index !== null ) {
  45912. firstVertex *= index.array.BYTES_PER_ELEMENT;
  45913. const indexData = this.get( index );
  45914. renderer.index = index.count;
  45915. renderer.type = indexData.type;
  45916. } else {
  45917. renderer.index = 0;
  45918. }
  45919. const draw = () => {
  45920. if ( object.isBatchedMesh ) {
  45921. if ( object._multiDrawInstances !== null ) {
  45922. // @deprecated, r174
  45923. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  45924. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  45925. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  45926. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  45927. } else {
  45928. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  45929. }
  45930. } else if ( instanceCount > 1 ) {
  45931. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  45932. } else {
  45933. renderer.render( firstVertex, vertexCount );
  45934. }
  45935. };
  45936. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  45937. const cameraData = this.get( renderObject.camera );
  45938. const cameras = renderObject.camera.cameras;
  45939. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  45940. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  45941. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  45942. const indexesGPU = [];
  45943. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45944. const bufferGPU = gl.createBuffer();
  45945. data[ 0 ] = i;
  45946. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45947. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  45948. indexesGPU.push( bufferGPU );
  45949. }
  45950. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  45951. }
  45952. const cameraIndexData = this.get( cameraIndex );
  45953. const pixelRatio = this.renderer.getPixelRatio();
  45954. const renderTarget = this._currentContext.renderTarget;
  45955. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  45956. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  45957. if ( isRenderCameraDepthArray ) {
  45958. // Clear the depth texture
  45959. const textureData = this.get( renderTarget.depthTexture );
  45960. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  45961. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  45962. const { stencilBuffer } = renderTarget;
  45963. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45964. this.renderer._activeCubeFace = i;
  45965. this._currentContext.activeCubeFace = i;
  45966. this._setFramebuffer( this._currentContext );
  45967. this.clear( false, true, stencilBuffer, this._currentContext, false );
  45968. }
  45969. this.renderer._activeCubeFace = prevActiveCubeFace;
  45970. this._currentContext.activeCubeFace = prevActiveCubeFace;
  45971. }
  45972. }
  45973. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45974. const subCamera = cameras[ i ];
  45975. if ( object.layers.test( subCamera.layers ) ) {
  45976. if ( isRenderCameraDepthArray ) {
  45977. // Update the active layer
  45978. this.renderer._activeCubeFace = i;
  45979. this._currentContext.activeCubeFace = i;
  45980. this._setFramebuffer( this._currentContext );
  45981. }
  45982. const vp = subCamera.viewport;
  45983. if ( vp !== undefined ) {
  45984. const x = vp.x * pixelRatio;
  45985. const y = vp.y * pixelRatio;
  45986. const width = vp.width * pixelRatio;
  45987. const height = vp.height * pixelRatio;
  45988. state.viewport(
  45989. Math.floor( x ),
  45990. Math.floor( renderObject.context.height - height - y ),
  45991. Math.floor( width ),
  45992. Math.floor( height )
  45993. );
  45994. }
  45995. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  45996. draw();
  45997. }
  45998. this._currentContext.activeCubeFace = prevActiveCubeFace;
  45999. this.renderer._activeCubeFace = prevActiveCubeFace;
  46000. }
  46001. } else {
  46002. draw();
  46003. }
  46004. }
  46005. /**
  46006. * Explain why always null is returned.
  46007. *
  46008. * @param {RenderObject} renderObject - The render object.
  46009. * @return {boolean} Whether the render pipeline requires an update or not.
  46010. */
  46011. needsRenderUpdate( /*renderObject*/ ) {
  46012. return false;
  46013. }
  46014. /**
  46015. * Explain why no cache key is computed.
  46016. *
  46017. * @param {RenderObject} renderObject - The render object.
  46018. * @return {string} The cache key.
  46019. */
  46020. getRenderCacheKey( /*renderObject*/ ) {
  46021. return '';
  46022. }
  46023. // textures
  46024. /**
  46025. * Creates a default texture for the given texture that can be used
  46026. * as a placeholder until the actual texture is ready for usage.
  46027. *
  46028. * @param {Texture} texture - The texture to create a default texture for.
  46029. */
  46030. createDefaultTexture( texture ) {
  46031. this.textureUtils.createDefaultTexture( texture );
  46032. }
  46033. /**
  46034. * Defines a texture on the GPU for the given texture object.
  46035. *
  46036. * @param {Texture} texture - The texture.
  46037. * @param {Object} [options={}] - Optional configuration parameter.
  46038. */
  46039. createTexture( texture, options ) {
  46040. this.textureUtils.createTexture( texture, options );
  46041. }
  46042. /**
  46043. * Uploads the updated texture data to the GPU.
  46044. *
  46045. * @param {Texture} texture - The texture.
  46046. * @param {Object} [options={}] - Optional configuration parameter.
  46047. */
  46048. updateTexture( texture, options ) {
  46049. this.textureUtils.updateTexture( texture, options );
  46050. }
  46051. /**
  46052. * Generates mipmaps for the given texture.
  46053. *
  46054. * @param {Texture} texture - The texture.
  46055. */
  46056. generateMipmaps( texture ) {
  46057. this.textureUtils.generateMipmaps( texture );
  46058. }
  46059. /**
  46060. * Destroys the GPU data for the given texture object.
  46061. *
  46062. * @param {Texture} texture - The texture.
  46063. */
  46064. destroyTexture( texture ) {
  46065. this.textureUtils.destroyTexture( texture );
  46066. }
  46067. /**
  46068. * Returns texture data as a typed array.
  46069. *
  46070. * @async
  46071. * @param {Texture} texture - The texture to copy.
  46072. * @param {number} x - The x coordinate of the copy origin.
  46073. * @param {number} y - The y coordinate of the copy origin.
  46074. * @param {number} width - The width of the copy.
  46075. * @param {number} height - The height of the copy.
  46076. * @param {number} faceIndex - The face index.
  46077. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46078. */
  46079. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46080. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  46081. }
  46082. /**
  46083. * This method does nothing since WebGL 2 has no concept of samplers.
  46084. *
  46085. * @param {Texture} texture - The texture to create the sampler for.
  46086. */
  46087. createSampler( /*texture*/ ) {
  46088. //console.warn( 'Abstract class.' );
  46089. }
  46090. /**
  46091. * This method does nothing since WebGL 2 has no concept of samplers.
  46092. *
  46093. * @param {Texture} texture - The texture to destroy the sampler for.
  46094. */
  46095. destroySampler( /*texture*/ ) {}
  46096. // node builder
  46097. /**
  46098. * Returns a node builder for the given render object.
  46099. *
  46100. * @param {RenderObject} object - The render object.
  46101. * @param {Renderer} renderer - The renderer.
  46102. * @return {GLSLNodeBuilder} The node builder.
  46103. */
  46104. createNodeBuilder( object, renderer ) {
  46105. return new GLSLNodeBuilder( object, renderer );
  46106. }
  46107. // program
  46108. /**
  46109. * Creates a shader program from the given programmable stage.
  46110. *
  46111. * @param {ProgrammableStage} program - The programmable stage.
  46112. */
  46113. createProgram( program ) {
  46114. const gl = this.gl;
  46115. const { stage, code } = program;
  46116. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  46117. gl.shaderSource( shader, code );
  46118. gl.compileShader( shader );
  46119. this.set( program, {
  46120. shaderGPU: shader
  46121. } );
  46122. }
  46123. /**
  46124. * Destroys the shader program of the given programmable stage.
  46125. *
  46126. * @param {ProgrammableStage} program - The programmable stage.
  46127. */
  46128. destroyProgram( program ) {
  46129. this.delete( program );
  46130. }
  46131. /**
  46132. * Creates a render pipeline for the given render object.
  46133. *
  46134. * @param {RenderObject} renderObject - The render object.
  46135. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46136. */
  46137. createRenderPipeline( renderObject, promises ) {
  46138. const gl = this.gl;
  46139. const pipeline = renderObject.pipeline;
  46140. // Program
  46141. const { fragmentProgram, vertexProgram } = pipeline;
  46142. const programGPU = gl.createProgram();
  46143. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  46144. const vertexShader = this.get( vertexProgram ).shaderGPU;
  46145. gl.attachShader( programGPU, fragmentShader );
  46146. gl.attachShader( programGPU, vertexShader );
  46147. gl.linkProgram( programGPU );
  46148. this.set( pipeline, {
  46149. programGPU,
  46150. fragmentShader,
  46151. vertexShader
  46152. } );
  46153. if ( promises !== null && this.parallel ) {
  46154. const p = new Promise( ( resolve /*, reject*/ ) => {
  46155. const parallel = this.parallel;
  46156. const checkStatus = () => {
  46157. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  46158. this._completeCompile( renderObject, pipeline );
  46159. resolve();
  46160. } else {
  46161. requestAnimationFrame( checkStatus );
  46162. }
  46163. };
  46164. checkStatus();
  46165. } );
  46166. promises.push( p );
  46167. return;
  46168. }
  46169. this._completeCompile( renderObject, pipeline );
  46170. }
  46171. /**
  46172. * Formats the source code of error messages.
  46173. *
  46174. * @private
  46175. * @param {string} string - The code.
  46176. * @param {number} errorLine - The error line.
  46177. * @return {string} The formatted code.
  46178. */
  46179. _handleSource( string, errorLine ) {
  46180. const lines = string.split( '\n' );
  46181. const lines2 = [];
  46182. const from = Math.max( errorLine - 6, 0 );
  46183. const to = Math.min( errorLine + 6, lines.length );
  46184. for ( let i = from; i < to; i ++ ) {
  46185. const line = i + 1;
  46186. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46187. }
  46188. return lines2.join( '\n' );
  46189. }
  46190. /**
  46191. * Gets the shader compilation errors from the info log.
  46192. *
  46193. * @private
  46194. * @param {WebGL2RenderingContext} gl - The rendering context.
  46195. * @param {WebGLShader} shader - The WebGL shader object.
  46196. * @param {string} type - The shader type.
  46197. * @return {string} The shader errors.
  46198. */
  46199. _getShaderErrors( gl, shader, type ) {
  46200. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46201. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46202. const errors = shaderInfoLog.trim();
  46203. if ( status && errors === '' ) return '';
  46204. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46205. if ( errorMatches ) {
  46206. const errorLine = parseInt( errorMatches[ 1 ] );
  46207. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  46208. } else {
  46209. return errors;
  46210. }
  46211. }
  46212. /**
  46213. * Logs shader compilation errors.
  46214. *
  46215. * @private
  46216. * @param {WebGLProgram} programGPU - The WebGL program.
  46217. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  46218. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  46219. */
  46220. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  46221. if ( this.renderer.debug.checkShaderErrors ) {
  46222. const gl = this.gl;
  46223. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  46224. const programLog = programInfoLog.trim();
  46225. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46226. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  46227. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  46228. } else {
  46229. // default error reporting
  46230. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  46231. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  46232. console.error(
  46233. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46234. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  46235. 'Program Info Log: ' + programLog + '\n' +
  46236. vertexErrors + '\n' +
  46237. fragmentErrors
  46238. );
  46239. }
  46240. } else if ( programLog !== '' ) {
  46241. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  46242. }
  46243. }
  46244. }
  46245. /**
  46246. * Completes the shader program setup for the given render object.
  46247. *
  46248. * @private
  46249. * @param {RenderObject} renderObject - The render object.
  46250. * @param {RenderPipeline} pipeline - The render pipeline.
  46251. */
  46252. _completeCompile( renderObject, pipeline ) {
  46253. const { state, gl } = this;
  46254. const pipelineData = this.get( pipeline );
  46255. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  46256. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46257. this._logProgramError( programGPU, fragmentShader, vertexShader );
  46258. }
  46259. state.useProgram( programGPU );
  46260. // Bindings
  46261. const bindings = renderObject.getBindings();
  46262. this._setupBindings( bindings, programGPU );
  46263. //
  46264. this.set( pipeline, {
  46265. programGPU
  46266. } );
  46267. }
  46268. /**
  46269. * Creates a compute pipeline for the given compute node.
  46270. *
  46271. * @param {ComputePipeline} computePipeline - The compute pipeline.
  46272. * @param {Array<BindGroup>} bindings - The bindings.
  46273. */
  46274. createComputePipeline( computePipeline, bindings ) {
  46275. const { state, gl } = this;
  46276. // Program
  46277. const fragmentProgram = {
  46278. stage: 'fragment',
  46279. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  46280. };
  46281. this.createProgram( fragmentProgram );
  46282. const { computeProgram } = computePipeline;
  46283. const programGPU = gl.createProgram();
  46284. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  46285. const vertexShader = this.get( computeProgram ).shaderGPU;
  46286. const transforms = computeProgram.transforms;
  46287. const transformVaryingNames = [];
  46288. const transformAttributeNodes = [];
  46289. for ( let i = 0; i < transforms.length; i ++ ) {
  46290. const transform = transforms[ i ];
  46291. transformVaryingNames.push( transform.varyingName );
  46292. transformAttributeNodes.push( transform.attributeNode );
  46293. }
  46294. gl.attachShader( programGPU, fragmentShader );
  46295. gl.attachShader( programGPU, vertexShader );
  46296. gl.transformFeedbackVaryings(
  46297. programGPU,
  46298. transformVaryingNames,
  46299. gl.SEPARATE_ATTRIBS
  46300. );
  46301. gl.linkProgram( programGPU );
  46302. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46303. this._logProgramError( programGPU, fragmentShader, vertexShader );
  46304. }
  46305. state.useProgram( programGPU );
  46306. // Bindings
  46307. this._setupBindings( bindings, programGPU );
  46308. const attributeNodes = computeProgram.attributes;
  46309. const attributes = [];
  46310. const transformBuffers = [];
  46311. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  46312. const attribute = attributeNodes[ i ].node.attribute;
  46313. attributes.push( attribute );
  46314. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46315. }
  46316. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  46317. const attribute = transformAttributeNodes[ i ].attribute;
  46318. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46319. const attributeData = this.get( attribute );
  46320. transformBuffers.push( attributeData );
  46321. }
  46322. //
  46323. this.set( computePipeline, {
  46324. programGPU,
  46325. transformBuffers,
  46326. attributes
  46327. } );
  46328. }
  46329. /**
  46330. * Creates bindings from the given bind group definition.
  46331. *
  46332. * @param {BindGroup} bindGroup - The bind group.
  46333. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46334. * @param {number} cacheIndex - The cache index.
  46335. * @param {number} version - The version.
  46336. */
  46337. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  46338. if ( this._knownBindings.has( bindings ) === false ) {
  46339. this._knownBindings.add( bindings );
  46340. let uniformBuffers = 0;
  46341. let textures = 0;
  46342. for ( const bindGroup of bindings ) {
  46343. this.set( bindGroup, {
  46344. textures: textures,
  46345. uniformBuffers: uniformBuffers
  46346. } );
  46347. for ( const binding of bindGroup.bindings ) {
  46348. if ( binding.isUniformBuffer ) uniformBuffers ++;
  46349. if ( binding.isSampledTexture ) textures ++;
  46350. }
  46351. }
  46352. }
  46353. this.updateBindings( bindGroup, bindings );
  46354. }
  46355. /**
  46356. * Updates the given bind group definition.
  46357. *
  46358. * @param {BindGroup} bindGroup - The bind group.
  46359. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46360. * @param {number} cacheIndex - The cache index.
  46361. * @param {number} version - The version.
  46362. */
  46363. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  46364. const { gl } = this;
  46365. const bindGroupData = this.get( bindGroup );
  46366. let i = bindGroupData.uniformBuffers;
  46367. let t = bindGroupData.textures;
  46368. for ( const binding of bindGroup.bindings ) {
  46369. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46370. const data = binding.buffer;
  46371. const bufferGPU = gl.createBuffer();
  46372. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46373. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  46374. this.set( binding, {
  46375. index: i ++,
  46376. bufferGPU
  46377. } );
  46378. } else if ( binding.isSampledTexture ) {
  46379. const { textureGPU, glTextureType } = this.get( binding.texture );
  46380. this.set( binding, {
  46381. index: t ++,
  46382. textureGPU,
  46383. glTextureType
  46384. } );
  46385. }
  46386. }
  46387. }
  46388. /**
  46389. * Updates a buffer binding.
  46390. *
  46391. * @param {Buffer} binding - The buffer binding to update.
  46392. */
  46393. updateBinding( binding ) {
  46394. const gl = this.gl;
  46395. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46396. const bindingData = this.get( binding );
  46397. const bufferGPU = bindingData.bufferGPU;
  46398. const data = binding.buffer;
  46399. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46400. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  46401. }
  46402. }
  46403. // attributes
  46404. /**
  46405. * Creates the GPU buffer of an indexed shader attribute.
  46406. *
  46407. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  46408. */
  46409. createIndexAttribute( attribute ) {
  46410. const gl = this.gl;
  46411. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  46412. }
  46413. /**
  46414. * Creates the GPU buffer of a shader attribute.
  46415. *
  46416. * @param {BufferAttribute} attribute - The buffer attribute.
  46417. */
  46418. createAttribute( attribute ) {
  46419. if ( this.has( attribute ) ) return;
  46420. const gl = this.gl;
  46421. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46422. }
  46423. /**
  46424. * Creates the GPU buffer of a storage attribute.
  46425. *
  46426. * @param {BufferAttribute} attribute - The buffer attribute.
  46427. */
  46428. createStorageAttribute( attribute ) {
  46429. if ( this.has( attribute ) ) return;
  46430. const gl = this.gl;
  46431. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46432. }
  46433. /**
  46434. * Updates the GPU buffer of a shader attribute.
  46435. *
  46436. * @param {BufferAttribute} attribute - The buffer attribute to update.
  46437. */
  46438. updateAttribute( attribute ) {
  46439. this.attributeUtils.updateAttribute( attribute );
  46440. }
  46441. /**
  46442. * Destroys the GPU buffer of a shader attribute.
  46443. *
  46444. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  46445. */
  46446. destroyAttribute( attribute ) {
  46447. this.attributeUtils.destroyAttribute( attribute );
  46448. }
  46449. /**
  46450. * Checks if the given feature is supported by the backend.
  46451. *
  46452. * @param {string} name - The feature's name.
  46453. * @return {boolean} Whether the feature is supported or not.
  46454. */
  46455. hasFeature( name ) {
  46456. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  46457. const extensions = this.extensions;
  46458. for ( let i = 0; i < keysMatching.length; i ++ ) {
  46459. if ( extensions.has( keysMatching[ i ] ) ) return true;
  46460. }
  46461. return false;
  46462. }
  46463. /**
  46464. * Returns the maximum anisotropy texture filtering value.
  46465. *
  46466. * @return {number} The maximum anisotropy texture filtering value.
  46467. */
  46468. getMaxAnisotropy() {
  46469. return this.capabilities.getMaxAnisotropy();
  46470. }
  46471. /**
  46472. * Copies data of the given source texture to the given destination texture.
  46473. *
  46474. * @param {Texture} srcTexture - The source texture.
  46475. * @param {Texture} dstTexture - The destination texture.
  46476. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  46477. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  46478. * @param {number} [srcLevel=0] - The source mip level to copy from.
  46479. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  46480. */
  46481. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  46482. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  46483. }
  46484. /**
  46485. * Copies the current bound framebuffer to the given texture.
  46486. *
  46487. * @param {Texture} texture - The destination texture.
  46488. * @param {RenderContext} renderContext - The render context.
  46489. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46490. */
  46491. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46492. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  46493. }
  46494. /**
  46495. * Configures the active framebuffer from the given render context.
  46496. *
  46497. * @private
  46498. * @param {RenderContext} descriptor - The render context.
  46499. */
  46500. _setFramebuffer( descriptor ) {
  46501. const { gl, state } = this;
  46502. let currentFrameBuffer = null;
  46503. if ( descriptor.textures !== null ) {
  46504. const renderTarget = descriptor.renderTarget;
  46505. const renderTargetContextData = this.get( renderTarget );
  46506. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  46507. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  46508. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  46509. const isRenderTargetArray = renderTarget.depth > 1;
  46510. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  46511. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  46512. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  46513. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  46514. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46515. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  46516. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  46517. const cacheKey = getCacheKey( descriptor );
  46518. let fb;
  46519. if ( isCube ) {
  46520. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  46521. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  46522. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  46523. fb = this._xrFramebuffer;
  46524. } else {
  46525. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  46526. fb = renderTargetContextData.framebuffers[ cacheKey ];
  46527. }
  46528. if ( fb === undefined ) {
  46529. fb = gl.createFramebuffer();
  46530. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  46531. const textures = descriptor.textures;
  46532. const depthInvalidationArray = [];
  46533. if ( isCube ) {
  46534. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  46535. const { textureGPU } = this.get( textures[ 0 ] );
  46536. const cubeFace = this.renderer._activeCubeFace;
  46537. const mipLevel = this.renderer._activeMipmapLevel;
  46538. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  46539. } else {
  46540. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  46541. for ( let i = 0; i < textures.length; i ++ ) {
  46542. const texture = textures[ i ];
  46543. const textureData = this.get( texture );
  46544. textureData.renderTarget = descriptor.renderTarget;
  46545. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  46546. const attachment = gl.COLOR_ATTACHMENT0 + i;
  46547. if ( renderTarget.multiview ) {
  46548. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  46549. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  46550. const layer = this.renderer._activeCubeFace;
  46551. const mipLevel = this.renderer._activeMipmapLevel;
  46552. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  46553. } else {
  46554. if ( useMultisampledRTT ) {
  46555. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46556. } else {
  46557. const mipLevel = this.renderer._activeMipmapLevel;
  46558. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  46559. }
  46560. }
  46561. }
  46562. }
  46563. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46564. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  46565. const renderbuffer = gl.createRenderbuffer();
  46566. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  46567. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  46568. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  46569. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46570. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  46571. } else {
  46572. if ( descriptor.depthTexture !== null ) {
  46573. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  46574. const textureData = this.get( descriptor.depthTexture );
  46575. textureData.renderTarget = descriptor.renderTarget;
  46576. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  46577. if ( renderTarget.multiview ) {
  46578. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  46579. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  46580. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46581. } else {
  46582. if ( descriptor.depthTexture.isArrayTexture ) {
  46583. const layer = this.renderer._activeCubeFace;
  46584. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  46585. } else {
  46586. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  46587. }
  46588. }
  46589. }
  46590. }
  46591. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  46592. } else {
  46593. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  46594. if ( isRenderCameraDepthArray ) {
  46595. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  46596. const layer = this.renderer._activeCubeFace;
  46597. const depthData = this.get( descriptor.depthTexture );
  46598. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46599. gl.framebufferTextureLayer(
  46600. gl.FRAMEBUFFER,
  46601. depthStyle,
  46602. depthData.textureGPU,
  46603. 0,
  46604. layer
  46605. );
  46606. }
  46607. // rebind external XR textures
  46608. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  46609. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  46610. // rebind color
  46611. const textureData = this.get( descriptor.textures[ 0 ] );
  46612. if ( renderTarget.multiview ) {
  46613. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  46614. } else if ( useMultisampledRTT ) {
  46615. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46616. } else {
  46617. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  46618. }
  46619. // rebind depth
  46620. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46621. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  46622. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  46623. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46624. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  46625. } else {
  46626. const textureData = this.get( descriptor.depthTexture );
  46627. if ( renderTarget.multiview ) {
  46628. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  46629. } else if ( useMultisampledRTT ) {
  46630. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46631. } else {
  46632. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  46633. }
  46634. }
  46635. }
  46636. }
  46637. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  46638. if ( msaaFb === undefined ) {
  46639. const invalidationArray = [];
  46640. msaaFb = gl.createFramebuffer();
  46641. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  46642. const msaaRenderbuffers = [];
  46643. const textures = descriptor.textures;
  46644. for ( let i = 0; i < textures.length; i ++ ) {
  46645. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  46646. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  46647. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  46648. const texture = descriptor.textures[ i ];
  46649. const textureData = this.get( texture );
  46650. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  46651. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  46652. }
  46653. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  46654. renderTargetContextData.msaaFrameBuffer = msaaFb;
  46655. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  46656. if ( depthBuffer && depthRenderbuffer === undefined ) {
  46657. depthRenderbuffer = gl.createRenderbuffer();
  46658. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  46659. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  46660. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46661. invalidationArray.push( depthStyle );
  46662. }
  46663. renderTargetContextData.invalidationArray = invalidationArray;
  46664. }
  46665. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  46666. } else {
  46667. currentFrameBuffer = fb;
  46668. }
  46669. state.drawBuffers( descriptor, fb );
  46670. }
  46671. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  46672. }
  46673. /**
  46674. * Computes the VAO key for the given index and attributes.
  46675. *
  46676. * @private
  46677. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  46678. * @return {string} The VAO key.
  46679. */
  46680. _getVaoKey( attributes ) {
  46681. let key = '';
  46682. for ( let i = 0; i < attributes.length; i ++ ) {
  46683. const attributeData = this.get( attributes[ i ] );
  46684. key += ':' + attributeData.id;
  46685. }
  46686. return key;
  46687. }
  46688. /**
  46689. * Creates a VAO from the index and attributes.
  46690. *
  46691. * @private
  46692. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  46693. * @return {Object} The VAO data.
  46694. */
  46695. _createVao( attributes ) {
  46696. const { gl } = this;
  46697. const vaoGPU = gl.createVertexArray();
  46698. gl.bindVertexArray( vaoGPU );
  46699. for ( let i = 0; i < attributes.length; i ++ ) {
  46700. const attribute = attributes[ i ];
  46701. const attributeData = this.get( attribute );
  46702. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  46703. gl.enableVertexAttribArray( i );
  46704. let stride, offset;
  46705. if ( attribute.isInterleavedBufferAttribute === true ) {
  46706. stride = attribute.data.stride * attributeData.bytesPerElement;
  46707. offset = attribute.offset * attributeData.bytesPerElement;
  46708. } else {
  46709. stride = 0;
  46710. offset = 0;
  46711. }
  46712. if ( attributeData.isInteger ) {
  46713. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  46714. } else {
  46715. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  46716. }
  46717. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  46718. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  46719. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  46720. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  46721. }
  46722. }
  46723. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  46724. return vaoGPU;
  46725. }
  46726. /**
  46727. * Creates a transform feedback from the given transform buffers.
  46728. *
  46729. * @private
  46730. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  46731. * @return {WebGLTransformFeedback} The transform feedback.
  46732. */
  46733. _getTransformFeedback( transformBuffers ) {
  46734. let key = '';
  46735. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46736. key += ':' + transformBuffers[ i ].id;
  46737. }
  46738. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  46739. if ( transformFeedbackGPU !== undefined ) {
  46740. return transformFeedbackGPU;
  46741. }
  46742. const { gl } = this;
  46743. transformFeedbackGPU = gl.createTransformFeedback();
  46744. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  46745. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46746. const attributeData = transformBuffers[ i ];
  46747. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  46748. }
  46749. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  46750. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  46751. return transformFeedbackGPU;
  46752. }
  46753. /**
  46754. * Setups the given bindings.
  46755. *
  46756. * @private
  46757. * @param {Array<BindGroup>} bindings - The bindings.
  46758. * @param {WebGLProgram} programGPU - The WebGL program.
  46759. */
  46760. _setupBindings( bindings, programGPU ) {
  46761. const gl = this.gl;
  46762. for ( const bindGroup of bindings ) {
  46763. for ( const binding of bindGroup.bindings ) {
  46764. const bindingData = this.get( binding );
  46765. const index = bindingData.index;
  46766. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46767. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  46768. gl.uniformBlockBinding( programGPU, location, index );
  46769. } else if ( binding.isSampledTexture ) {
  46770. const location = gl.getUniformLocation( programGPU, binding.name );
  46771. gl.uniform1i( location, index );
  46772. }
  46773. }
  46774. }
  46775. }
  46776. /**
  46777. * Binds the given uniforms.
  46778. *
  46779. * @private
  46780. * @param {Array<BindGroup>} bindings - The bindings.
  46781. */
  46782. _bindUniforms( bindings ) {
  46783. const { gl, state } = this;
  46784. for ( const bindGroup of bindings ) {
  46785. for ( const binding of bindGroup.bindings ) {
  46786. const bindingData = this.get( binding );
  46787. const index = bindingData.index;
  46788. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46789. // TODO USE bindBufferRange to group multiple uniform buffers
  46790. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  46791. } else if ( binding.isSampledTexture ) {
  46792. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  46793. }
  46794. }
  46795. }
  46796. }
  46797. /**
  46798. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  46799. * should be used when MSAA is enabled.
  46800. *
  46801. * @private
  46802. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  46803. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  46804. */
  46805. _useMultisampledExtension( renderTarget ) {
  46806. if ( renderTarget.multiview === true ) {
  46807. return true;
  46808. }
  46809. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  46810. }
  46811. /**
  46812. * Frees internal resources.
  46813. */
  46814. dispose() {
  46815. const extension = this.extensions.get( 'WEBGL_lose_context' );
  46816. if ( extension ) extension.loseContext();
  46817. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  46818. }
  46819. }
  46820. const GPUPrimitiveTopology = {
  46821. PointList: 'point-list',
  46822. LineList: 'line-list',
  46823. LineStrip: 'line-strip',
  46824. TriangleList: 'triangle-list',
  46825. TriangleStrip: 'triangle-strip',
  46826. };
  46827. const GPUCompareFunction = {
  46828. Never: 'never',
  46829. Less: 'less',
  46830. Equal: 'equal',
  46831. LessEqual: 'less-equal',
  46832. Greater: 'greater',
  46833. NotEqual: 'not-equal',
  46834. GreaterEqual: 'greater-equal',
  46835. Always: 'always'
  46836. };
  46837. const GPUStoreOp = {
  46838. Store: 'store'};
  46839. const GPULoadOp = {
  46840. Load: 'load',
  46841. Clear: 'clear'
  46842. };
  46843. const GPUFrontFace = {
  46844. CCW: 'ccw'};
  46845. const GPUCullMode = {
  46846. None: 'none',
  46847. Front: 'front',
  46848. Back: 'back'
  46849. };
  46850. const GPUIndexFormat = {
  46851. Uint16: 'uint16',
  46852. Uint32: 'uint32'
  46853. };
  46854. const GPUTextureFormat = {
  46855. // 8-bit formats
  46856. R8Unorm: 'r8unorm',
  46857. R8Snorm: 'r8snorm',
  46858. R8Uint: 'r8uint',
  46859. R8Sint: 'r8sint',
  46860. // 16-bit formats
  46861. R16Uint: 'r16uint',
  46862. R16Sint: 'r16sint',
  46863. R16Float: 'r16float',
  46864. RG8Unorm: 'rg8unorm',
  46865. RG8Snorm: 'rg8snorm',
  46866. RG8Uint: 'rg8uint',
  46867. RG8Sint: 'rg8sint',
  46868. // 32-bit formats
  46869. R32Uint: 'r32uint',
  46870. R32Sint: 'r32sint',
  46871. R32Float: 'r32float',
  46872. RG16Uint: 'rg16uint',
  46873. RG16Sint: 'rg16sint',
  46874. RG16Float: 'rg16float',
  46875. RGBA8Unorm: 'rgba8unorm',
  46876. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  46877. RGBA8Snorm: 'rgba8snorm',
  46878. RGBA8Uint: 'rgba8uint',
  46879. RGBA8Sint: 'rgba8sint',
  46880. BGRA8Unorm: 'bgra8unorm',
  46881. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  46882. // Packed 32-bit formats
  46883. RGB9E5UFloat: 'rgb9e5ufloat',
  46884. RGB10A2Unorm: 'rgb10a2unorm',
  46885. RG11B10UFloat: 'rgb10a2unorm',
  46886. // 64-bit formats
  46887. RG32Uint: 'rg32uint',
  46888. RG32Sint: 'rg32sint',
  46889. RG32Float: 'rg32float',
  46890. RGBA16Uint: 'rgba16uint',
  46891. RGBA16Sint: 'rgba16sint',
  46892. RGBA16Float: 'rgba16float',
  46893. // 128-bit formats
  46894. RGBA32Uint: 'rgba32uint',
  46895. RGBA32Sint: 'rgba32sint',
  46896. RGBA32Float: 'rgba32float',
  46897. Depth16Unorm: 'depth16unorm',
  46898. Depth24Plus: 'depth24plus',
  46899. Depth24PlusStencil8: 'depth24plus-stencil8',
  46900. Depth32Float: 'depth32float',
  46901. // 'depth32float-stencil8' extension
  46902. Depth32FloatStencil8: 'depth32float-stencil8',
  46903. // BC compressed formats usable if 'texture-compression-bc' is both
  46904. // supported by the device/user agent and enabled in requestDevice.
  46905. BC1RGBAUnorm: 'bc1-rgba-unorm',
  46906. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  46907. BC2RGBAUnorm: 'bc2-rgba-unorm',
  46908. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  46909. BC3RGBAUnorm: 'bc3-rgba-unorm',
  46910. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  46911. BC4RUnorm: 'bc4-r-unorm',
  46912. BC4RSnorm: 'bc4-r-snorm',
  46913. BC5RGUnorm: 'bc5-rg-unorm',
  46914. BC5RGSnorm: 'bc5-rg-snorm',
  46915. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  46916. BC6HRGBFloat: 'bc6h-rgb-float',
  46917. BC7RGBAUnorm: 'bc7-rgba-unorm',
  46918. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  46919. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  46920. // supported by the device/user agent and enabled in requestDevice.
  46921. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  46922. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  46923. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  46924. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  46925. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  46926. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  46927. EACR11Unorm: 'eac-r11unorm',
  46928. EACR11Snorm: 'eac-r11snorm',
  46929. EACRG11Unorm: 'eac-rg11unorm',
  46930. EACRG11Snorm: 'eac-rg11snorm',
  46931. // ASTC compressed formats usable if 'texture-compression-astc' is both
  46932. // supported by the device/user agent and enabled in requestDevice.
  46933. ASTC4x4Unorm: 'astc-4x4-unorm',
  46934. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  46935. ASTC5x4Unorm: 'astc-5x4-unorm',
  46936. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  46937. ASTC5x5Unorm: 'astc-5x5-unorm',
  46938. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  46939. ASTC6x5Unorm: 'astc-6x5-unorm',
  46940. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  46941. ASTC6x6Unorm: 'astc-6x6-unorm',
  46942. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  46943. ASTC8x5Unorm: 'astc-8x5-unorm',
  46944. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  46945. ASTC8x6Unorm: 'astc-8x6-unorm',
  46946. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  46947. ASTC8x8Unorm: 'astc-8x8-unorm',
  46948. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  46949. ASTC10x5Unorm: 'astc-10x5-unorm',
  46950. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  46951. ASTC10x6Unorm: 'astc-10x6-unorm',
  46952. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  46953. ASTC10x8Unorm: 'astc-10x8-unorm',
  46954. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  46955. ASTC10x10Unorm: 'astc-10x10-unorm',
  46956. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  46957. ASTC12x10Unorm: 'astc-12x10-unorm',
  46958. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  46959. ASTC12x12Unorm: 'astc-12x12-unorm',
  46960. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  46961. };
  46962. const GPUAddressMode = {
  46963. ClampToEdge: 'clamp-to-edge',
  46964. Repeat: 'repeat',
  46965. MirrorRepeat: 'mirror-repeat'
  46966. };
  46967. const GPUFilterMode = {
  46968. Linear: 'linear',
  46969. Nearest: 'nearest'
  46970. };
  46971. const GPUBlendFactor = {
  46972. Zero: 'zero',
  46973. One: 'one',
  46974. Src: 'src',
  46975. OneMinusSrc: 'one-minus-src',
  46976. SrcAlpha: 'src-alpha',
  46977. OneMinusSrcAlpha: 'one-minus-src-alpha',
  46978. Dst: 'dst',
  46979. OneMinusDst: 'one-minus-dst',
  46980. DstAlpha: 'dst-alpha',
  46981. OneMinusDstAlpha: 'one-minus-dst-alpha',
  46982. SrcAlphaSaturated: 'src-alpha-saturated',
  46983. Constant: 'constant',
  46984. OneMinusConstant: 'one-minus-constant'
  46985. };
  46986. const GPUBlendOperation = {
  46987. Add: 'add',
  46988. Subtract: 'subtract',
  46989. ReverseSubtract: 'reverse-subtract',
  46990. Min: 'min',
  46991. Max: 'max'
  46992. };
  46993. const GPUColorWriteFlags = {
  46994. None: 0,
  46995. All: 0xF
  46996. };
  46997. const GPUStencilOperation = {
  46998. Keep: 'keep',
  46999. Zero: 'zero',
  47000. Replace: 'replace',
  47001. Invert: 'invert',
  47002. IncrementClamp: 'increment-clamp',
  47003. DecrementClamp: 'decrement-clamp',
  47004. IncrementWrap: 'increment-wrap',
  47005. DecrementWrap: 'decrement-wrap'
  47006. };
  47007. const GPUBufferBindingType = {
  47008. Storage: 'storage',
  47009. ReadOnlyStorage: 'read-only-storage'
  47010. };
  47011. const GPUStorageTextureAccess = {
  47012. WriteOnly: 'write-only',
  47013. ReadOnly: 'read-only',
  47014. ReadWrite: 'read-write',
  47015. };
  47016. const GPUSamplerBindingType = {
  47017. NonFiltering: 'non-filtering',
  47018. Comparison: 'comparison'
  47019. };
  47020. const GPUTextureSampleType = {
  47021. Float: 'float',
  47022. UnfilterableFloat: 'unfilterable-float',
  47023. Depth: 'depth',
  47024. SInt: 'sint',
  47025. UInt: 'uint'
  47026. };
  47027. const GPUTextureDimension = {
  47028. TwoD: '2d',
  47029. ThreeD: '3d'
  47030. };
  47031. const GPUTextureViewDimension = {
  47032. TwoD: '2d',
  47033. TwoDArray: '2d-array',
  47034. Cube: 'cube',
  47035. ThreeD: '3d'
  47036. };
  47037. const GPUTextureAspect = {
  47038. All: 'all'};
  47039. const GPUInputStepMode = {
  47040. Vertex: 'vertex',
  47041. Instance: 'instance'
  47042. };
  47043. const GPUFeatureName = {
  47044. CoreFeaturesAndLimits: 'core-features-and-limits',
  47045. DepthClipControl: 'depth-clip-control',
  47046. Depth32FloatStencil8: 'depth32float-stencil8',
  47047. TextureCompressionBC: 'texture-compression-bc',
  47048. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  47049. TextureCompressionETC2: 'texture-compression-etc2',
  47050. TextureCompressionASTC: 'texture-compression-astc',
  47051. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  47052. TimestampQuery: 'timestamp-query',
  47053. IndirectFirstInstance: 'indirect-first-instance',
  47054. ShaderF16: 'shader-f16',
  47055. RG11B10UFloat: 'rg11b10ufloat-renderable',
  47056. BGRA8UNormStorage: 'bgra8unorm-storage',
  47057. Float32Filterable: 'float32-filterable',
  47058. Float32Blendable: 'float32-blendable',
  47059. ClipDistances: 'clip-distances',
  47060. DualSourceBlending: 'dual-source-blending',
  47061. Subgroups: 'subgroups',
  47062. TextureFormatsTier1: 'texture-formats-tier1',
  47063. TextureFormatsTier2: 'texture-formats-tier2'
  47064. };
  47065. /**
  47066. * A special form of sampler binding type.
  47067. * It's texture value is managed by a node object.
  47068. *
  47069. * @private
  47070. * @augments Sampler
  47071. */
  47072. class NodeSampler extends Sampler {
  47073. /**
  47074. * Constructs a new node-based sampler.
  47075. *
  47076. * @param {string} name - The samplers's name.
  47077. * @param {TextureNode} textureNode - The texture node.
  47078. * @param {UniformGroupNode} groupNode - The uniform group node.
  47079. */
  47080. constructor( name, textureNode, groupNode ) {
  47081. super( name, textureNode ? textureNode.value : null );
  47082. /**
  47083. * The texture node.
  47084. *
  47085. * @type {TextureNode}
  47086. */
  47087. this.textureNode = textureNode;
  47088. /**
  47089. * The uniform group node.
  47090. *
  47091. * @type {UniformGroupNode}
  47092. */
  47093. this.groupNode = groupNode;
  47094. }
  47095. /**
  47096. * Updates the texture value of this sampler.
  47097. */
  47098. update() {
  47099. this.texture = this.textureNode.value;
  47100. }
  47101. }
  47102. /**
  47103. * Represents a storage buffer binding type.
  47104. *
  47105. * @private
  47106. * @augments Buffer
  47107. */
  47108. class StorageBuffer extends Buffer {
  47109. /**
  47110. * Constructs a new uniform buffer.
  47111. *
  47112. * @param {string} name - The buffer's name.
  47113. * @param {BufferAttribute} attribute - The buffer attribute.
  47114. */
  47115. constructor( name, attribute ) {
  47116. super( name, attribute ? attribute.array : null );
  47117. /**
  47118. * This flag can be used for type testing.
  47119. *
  47120. * @type {BufferAttribute}
  47121. */
  47122. this.attribute = attribute;
  47123. /**
  47124. * This flag can be used for type testing.
  47125. *
  47126. * @type {boolean}
  47127. * @readonly
  47128. * @default true
  47129. */
  47130. this.isStorageBuffer = true;
  47131. }
  47132. }
  47133. let _id = 0;
  47134. /**
  47135. * A special form of storage buffer binding type.
  47136. * It's buffer value is managed by a node object.
  47137. *
  47138. * @private
  47139. * @augments StorageBuffer
  47140. */
  47141. class NodeStorageBuffer extends StorageBuffer {
  47142. /**
  47143. * Constructs a new node-based storage buffer.
  47144. *
  47145. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  47146. * @param {UniformGroupNode} groupNode - The uniform group node.
  47147. */
  47148. constructor( nodeUniform, groupNode ) {
  47149. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  47150. /**
  47151. * The node uniform.
  47152. *
  47153. * @type {StorageBufferNode}
  47154. */
  47155. this.nodeUniform = nodeUniform;
  47156. /**
  47157. * The access type.
  47158. *
  47159. * @type {string}
  47160. */
  47161. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  47162. /**
  47163. * The uniform group node.
  47164. *
  47165. * @type {UniformGroupNode}
  47166. */
  47167. this.groupNode = groupNode;
  47168. }
  47169. /**
  47170. * The storage buffer.
  47171. *
  47172. * @type {BufferAttribute}
  47173. */
  47174. get buffer() {
  47175. return this.nodeUniform.value;
  47176. }
  47177. }
  47178. /**
  47179. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  47180. *
  47181. * @private
  47182. */
  47183. class WebGPUTexturePassUtils extends DataMap {
  47184. /**
  47185. * Constructs a new utility object.
  47186. *
  47187. * @param {GPUDevice} device - The WebGPU device.
  47188. */
  47189. constructor( device ) {
  47190. super();
  47191. /**
  47192. * The WebGPU device.
  47193. *
  47194. * @type {GPUDevice}
  47195. */
  47196. this.device = device;
  47197. const mipmapVertexSource = `
  47198. struct VarysStruct {
  47199. @builtin( position ) Position: vec4<f32>,
  47200. @location( 0 ) vTex : vec2<f32>
  47201. };
  47202. @vertex
  47203. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  47204. var Varys : VarysStruct;
  47205. var pos = array< vec2<f32>, 4 >(
  47206. vec2<f32>( -1.0, 1.0 ),
  47207. vec2<f32>( 1.0, 1.0 ),
  47208. vec2<f32>( -1.0, -1.0 ),
  47209. vec2<f32>( 1.0, -1.0 )
  47210. );
  47211. var tex = array< vec2<f32>, 4 >(
  47212. vec2<f32>( 0.0, 0.0 ),
  47213. vec2<f32>( 1.0, 0.0 ),
  47214. vec2<f32>( 0.0, 1.0 ),
  47215. vec2<f32>( 1.0, 1.0 )
  47216. );
  47217. Varys.vTex = tex[ vertexIndex ];
  47218. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  47219. return Varys;
  47220. }
  47221. `;
  47222. const mipmapFragmentSource = `
  47223. @group( 0 ) @binding( 0 )
  47224. var imgSampler : sampler;
  47225. @group( 0 ) @binding( 1 )
  47226. var img : texture_2d<f32>;
  47227. @fragment
  47228. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  47229. return textureSample( img, imgSampler, vTex );
  47230. }
  47231. `;
  47232. const flipYFragmentSource = `
  47233. @group( 0 ) @binding( 0 )
  47234. var imgSampler : sampler;
  47235. @group( 0 ) @binding( 1 )
  47236. var img : texture_2d<f32>;
  47237. @fragment
  47238. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  47239. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  47240. }
  47241. `;
  47242. /**
  47243. * The mipmap GPU sampler.
  47244. *
  47245. * @type {GPUSampler}
  47246. */
  47247. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  47248. /**
  47249. * The flipY GPU sampler.
  47250. *
  47251. * @type {GPUSampler}
  47252. */
  47253. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  47254. /**
  47255. * A cache for GPU render pipelines used for copy/transfer passes.
  47256. * Every texture format requires a unique pipeline.
  47257. *
  47258. * @type {Object<string,GPURenderPipeline>}
  47259. */
  47260. this.transferPipelines = {};
  47261. /**
  47262. * A cache for GPU render pipelines used for flipY passes.
  47263. * Every texture format requires a unique pipeline.
  47264. *
  47265. * @type {Object<string,GPURenderPipeline>}
  47266. */
  47267. this.flipYPipelines = {};
  47268. /**
  47269. * The mipmap vertex shader module.
  47270. *
  47271. * @type {GPUShaderModule}
  47272. */
  47273. this.mipmapVertexShaderModule = device.createShaderModule( {
  47274. label: 'mipmapVertex',
  47275. code: mipmapVertexSource
  47276. } );
  47277. /**
  47278. * The mipmap fragment shader module.
  47279. *
  47280. * @type {GPUShaderModule}
  47281. */
  47282. this.mipmapFragmentShaderModule = device.createShaderModule( {
  47283. label: 'mipmapFragment',
  47284. code: mipmapFragmentSource
  47285. } );
  47286. /**
  47287. * The flipY fragment shader module.
  47288. *
  47289. * @type {GPUShaderModule}
  47290. */
  47291. this.flipYFragmentShaderModule = device.createShaderModule( {
  47292. label: 'flipYFragment',
  47293. code: flipYFragmentSource
  47294. } );
  47295. }
  47296. /**
  47297. * Returns a render pipeline for the internal copy render pass. The pass
  47298. * requires a unique render pipeline for each texture format.
  47299. *
  47300. * @param {string} format - The GPU texture format
  47301. * @return {GPURenderPipeline} The GPU render pipeline.
  47302. */
  47303. getTransferPipeline( format ) {
  47304. let pipeline = this.transferPipelines[ format ];
  47305. if ( pipeline === undefined ) {
  47306. pipeline = this.device.createRenderPipeline( {
  47307. label: `mipmap-${ format }`,
  47308. vertex: {
  47309. module: this.mipmapVertexShaderModule,
  47310. entryPoint: 'main'
  47311. },
  47312. fragment: {
  47313. module: this.mipmapFragmentShaderModule,
  47314. entryPoint: 'main',
  47315. targets: [ { format } ]
  47316. },
  47317. primitive: {
  47318. topology: GPUPrimitiveTopology.TriangleStrip,
  47319. stripIndexFormat: GPUIndexFormat.Uint32
  47320. },
  47321. layout: 'auto'
  47322. } );
  47323. this.transferPipelines[ format ] = pipeline;
  47324. }
  47325. return pipeline;
  47326. }
  47327. /**
  47328. * Returns a render pipeline for the flipY render pass. The pass
  47329. * requires a unique render pipeline for each texture format.
  47330. *
  47331. * @param {string} format - The GPU texture format
  47332. * @return {GPURenderPipeline} The GPU render pipeline.
  47333. */
  47334. getFlipYPipeline( format ) {
  47335. let pipeline = this.flipYPipelines[ format ];
  47336. if ( pipeline === undefined ) {
  47337. pipeline = this.device.createRenderPipeline( {
  47338. label: `flipY-${ format }`,
  47339. vertex: {
  47340. module: this.mipmapVertexShaderModule,
  47341. entryPoint: 'main'
  47342. },
  47343. fragment: {
  47344. module: this.flipYFragmentShaderModule,
  47345. entryPoint: 'main',
  47346. targets: [ { format } ]
  47347. },
  47348. primitive: {
  47349. topology: GPUPrimitiveTopology.TriangleStrip,
  47350. stripIndexFormat: GPUIndexFormat.Uint32
  47351. },
  47352. layout: 'auto'
  47353. } );
  47354. this.flipYPipelines[ format ] = pipeline;
  47355. }
  47356. return pipeline;
  47357. }
  47358. /**
  47359. * Flip the contents of the given GPU texture along its vertical axis.
  47360. *
  47361. * @param {GPUTexture} textureGPU - The GPU texture object.
  47362. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47363. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  47364. */
  47365. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  47366. const format = textureGPUDescriptor.format;
  47367. const { width, height } = textureGPUDescriptor.size;
  47368. const transferPipeline = this.getTransferPipeline( format );
  47369. const flipYPipeline = this.getFlipYPipeline( format );
  47370. const tempTexture = this.device.createTexture( {
  47371. size: { width, height, depthOrArrayLayers: 1 },
  47372. format,
  47373. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  47374. } );
  47375. const srcView = textureGPU.createView( {
  47376. baseMipLevel: 0,
  47377. mipLevelCount: 1,
  47378. dimension: GPUTextureViewDimension.TwoD,
  47379. baseArrayLayer
  47380. } );
  47381. const dstView = tempTexture.createView( {
  47382. baseMipLevel: 0,
  47383. mipLevelCount: 1,
  47384. dimension: GPUTextureViewDimension.TwoD,
  47385. baseArrayLayer: 0
  47386. } );
  47387. const commandEncoder = this.device.createCommandEncoder( {} );
  47388. const pass = ( pipeline, sourceView, destinationView ) => {
  47389. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  47390. const bindGroup = this.device.createBindGroup( {
  47391. layout: bindGroupLayout,
  47392. entries: [ {
  47393. binding: 0,
  47394. resource: this.flipYSampler
  47395. }, {
  47396. binding: 1,
  47397. resource: sourceView
  47398. } ]
  47399. } );
  47400. const passEncoder = commandEncoder.beginRenderPass( {
  47401. colorAttachments: [ {
  47402. view: destinationView,
  47403. loadOp: GPULoadOp.Clear,
  47404. storeOp: GPUStoreOp.Store,
  47405. clearValue: [ 0, 0, 0, 0 ]
  47406. } ]
  47407. } );
  47408. passEncoder.setPipeline( pipeline );
  47409. passEncoder.setBindGroup( 0, bindGroup );
  47410. passEncoder.draw( 4, 1, 0, 0 );
  47411. passEncoder.end();
  47412. };
  47413. pass( transferPipeline, srcView, dstView );
  47414. pass( flipYPipeline, dstView, srcView );
  47415. this.device.queue.submit( [ commandEncoder.finish() ] );
  47416. tempTexture.destroy();
  47417. }
  47418. /**
  47419. * Generates mipmaps for the given GPU texture.
  47420. *
  47421. * @param {GPUTexture} textureGPU - The GPU texture object.
  47422. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47423. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  47424. */
  47425. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  47426. const textureData = this.get( textureGPU );
  47427. if ( textureData.useCount === undefined ) {
  47428. textureData.useCount = 0;
  47429. textureData.layers = [];
  47430. }
  47431. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  47432. const commandEncoder = this.device.createCommandEncoder( {} );
  47433. this._mipmapRunBundles( commandEncoder, passes );
  47434. this.device.queue.submit( [ commandEncoder.finish() ] );
  47435. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  47436. textureData.useCount ++;
  47437. }
  47438. /**
  47439. * Since multiple copy render passes are required to generate mipmaps, the passes
  47440. * are managed as render bundles to improve performance.
  47441. *
  47442. * @param {GPUTexture} textureGPU - The GPU texture object.
  47443. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47444. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  47445. * @return {Array<Object>} An array of render bundles.
  47446. */
  47447. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  47448. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  47449. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  47450. let srcView = textureGPU.createView( {
  47451. baseMipLevel: 0,
  47452. mipLevelCount: 1,
  47453. dimension: GPUTextureViewDimension.TwoD,
  47454. baseArrayLayer
  47455. } );
  47456. const passes = [];
  47457. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  47458. const bindGroup = this.device.createBindGroup( {
  47459. layout: bindGroupLayout,
  47460. entries: [ {
  47461. binding: 0,
  47462. resource: this.mipmapSampler
  47463. }, {
  47464. binding: 1,
  47465. resource: srcView
  47466. } ]
  47467. } );
  47468. const dstView = textureGPU.createView( {
  47469. baseMipLevel: i,
  47470. mipLevelCount: 1,
  47471. dimension: GPUTextureViewDimension.TwoD,
  47472. baseArrayLayer
  47473. } );
  47474. const passDescriptor = {
  47475. colorAttachments: [ {
  47476. view: dstView,
  47477. loadOp: GPULoadOp.Clear,
  47478. storeOp: GPUStoreOp.Store,
  47479. clearValue: [ 0, 0, 0, 0 ]
  47480. } ]
  47481. };
  47482. const passEncoder = this.device.createRenderBundleEncoder( {
  47483. colorFormats: [ textureGPUDescriptor.format ]
  47484. } );
  47485. passEncoder.setPipeline( pipeline );
  47486. passEncoder.setBindGroup( 0, bindGroup );
  47487. passEncoder.draw( 4, 1, 0, 0 );
  47488. passes.push( {
  47489. renderBundles: [ passEncoder.finish() ],
  47490. passDescriptor
  47491. } );
  47492. srcView = dstView;
  47493. }
  47494. return passes;
  47495. }
  47496. /**
  47497. * Executes the render bundles.
  47498. *
  47499. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  47500. * @param {Array<Object>} passes - An array of render bundles.
  47501. */
  47502. _mipmapRunBundles( commandEncoder, passes ) {
  47503. const levels = passes.length;
  47504. for ( let i = 0; i < levels; i ++ ) {
  47505. const pass = passes[ i ];
  47506. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  47507. passEncoder.executeBundles( pass.renderBundles );
  47508. passEncoder.end();
  47509. }
  47510. }
  47511. }
  47512. const _compareToWebGPU = {
  47513. [ NeverCompare ]: 'never',
  47514. [ LessCompare ]: 'less',
  47515. [ EqualCompare ]: 'equal',
  47516. [ LessEqualCompare ]: 'less-equal',
  47517. [ GreaterCompare ]: 'greater',
  47518. [ GreaterEqualCompare ]: 'greater-equal',
  47519. [ AlwaysCompare ]: 'always',
  47520. [ NotEqualCompare ]: 'not-equal'
  47521. };
  47522. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  47523. /**
  47524. * A WebGPU backend utility module for managing textures.
  47525. *
  47526. * @private
  47527. */
  47528. class WebGPUTextureUtils {
  47529. /**
  47530. * Constructs a new utility object.
  47531. *
  47532. * @param {WebGPUBackend} backend - The WebGPU backend.
  47533. */
  47534. constructor( backend ) {
  47535. /**
  47536. * A reference to the WebGPU backend.
  47537. *
  47538. * @type {WebGPUBackend}
  47539. */
  47540. this.backend = backend;
  47541. /**
  47542. * A reference to the pass utils.
  47543. *
  47544. * @type {?WebGPUTexturePassUtils}
  47545. * @default null
  47546. */
  47547. this._passUtils = null;
  47548. /**
  47549. * A dictionary for managing default textures. The key
  47550. * is the texture format, the value the texture object.
  47551. *
  47552. * @type {Object<string,Texture>}
  47553. */
  47554. this.defaultTexture = {};
  47555. /**
  47556. * A dictionary for managing default cube textures. The key
  47557. * is the texture format, the value the texture object.
  47558. *
  47559. * @type {Object<string,CubeTexture>}
  47560. */
  47561. this.defaultCubeTexture = {};
  47562. /**
  47563. * A default video frame.
  47564. *
  47565. * @type {?VideoFrame}
  47566. * @default null
  47567. */
  47568. this.defaultVideoFrame = null;
  47569. /**
  47570. * Represents the color attachment of the default framebuffer.
  47571. *
  47572. * @type {?GPUTexture}
  47573. * @default null
  47574. */
  47575. this.colorBuffer = null;
  47576. /**
  47577. * Represents the depth attachment of the default framebuffer.
  47578. *
  47579. * @type {DepthTexture}
  47580. */
  47581. this.depthTexture = new DepthTexture();
  47582. this.depthTexture.name = 'depthBuffer';
  47583. }
  47584. /**
  47585. * Creates a GPU sampler for the given texture.
  47586. *
  47587. * @param {Texture} texture - The texture to create the sampler for.
  47588. */
  47589. createSampler( texture ) {
  47590. const backend = this.backend;
  47591. const device = backend.device;
  47592. const textureGPU = backend.get( texture );
  47593. const samplerDescriptorGPU = {
  47594. addressModeU: this._convertAddressMode( texture.wrapS ),
  47595. addressModeV: this._convertAddressMode( texture.wrapT ),
  47596. addressModeW: this._convertAddressMode( texture.wrapR ),
  47597. magFilter: this._convertFilterMode( texture.magFilter ),
  47598. minFilter: this._convertFilterMode( texture.minFilter ),
  47599. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  47600. maxAnisotropy: 1
  47601. };
  47602. // anisotropy can only be used when all filter modes are set to linear.
  47603. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  47604. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  47605. }
  47606. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  47607. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  47608. }
  47609. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  47610. }
  47611. /**
  47612. * Creates a default texture for the given texture that can be used
  47613. * as a placeholder until the actual texture is ready for usage.
  47614. *
  47615. * @param {Texture} texture - The texture to create a default texture for.
  47616. */
  47617. createDefaultTexture( texture ) {
  47618. let textureGPU;
  47619. const format = getFormat( texture );
  47620. if ( texture.isCubeTexture ) {
  47621. textureGPU = this._getDefaultCubeTextureGPU( format );
  47622. } else {
  47623. textureGPU = this._getDefaultTextureGPU( format );
  47624. }
  47625. this.backend.get( texture ).texture = textureGPU;
  47626. }
  47627. /**
  47628. * Defines a texture on the GPU for the given texture object.
  47629. *
  47630. * @param {Texture} texture - The texture.
  47631. * @param {Object} [options={}] - Optional configuration parameter.
  47632. */
  47633. createTexture( texture, options = {} ) {
  47634. const backend = this.backend;
  47635. const textureData = backend.get( texture );
  47636. if ( textureData.initialized ) {
  47637. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  47638. }
  47639. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  47640. if ( options.levels === undefined ) options.levels = 1;
  47641. if ( options.depth === undefined ) options.depth = 1;
  47642. const { width, height, depth, levels } = options;
  47643. if ( texture.isFramebufferTexture ) {
  47644. if ( options.renderTarget ) {
  47645. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  47646. } else {
  47647. options.format = this.backend.utils.getPreferredCanvasFormat();
  47648. }
  47649. }
  47650. const dimension = this._getDimension( texture );
  47651. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  47652. textureData.format = format;
  47653. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  47654. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  47655. if ( texture.isStorageTexture === true ) {
  47656. usage |= GPUTextureUsage.STORAGE_BINDING;
  47657. }
  47658. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  47659. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  47660. }
  47661. const textureDescriptorGPU = {
  47662. label: texture.name,
  47663. size: {
  47664. width: width,
  47665. height: height,
  47666. depthOrArrayLayers: depth,
  47667. },
  47668. mipLevelCount: levels,
  47669. sampleCount: primarySamples,
  47670. dimension: dimension,
  47671. format: format,
  47672. usage: usage
  47673. };
  47674. // texture creation
  47675. if ( format === undefined ) {
  47676. console.warn( 'WebGPURenderer: Texture format not supported.' );
  47677. this.createDefaultTexture( texture );
  47678. return;
  47679. }
  47680. if ( texture.isCubeTexture ) {
  47681. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  47682. }
  47683. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  47684. if ( isMSAA ) {
  47685. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  47686. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  47687. msaaTextureDescriptorGPU.sampleCount = samples;
  47688. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  47689. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  47690. }
  47691. textureData.initialized = true;
  47692. textureData.textureDescriptorGPU = textureDescriptorGPU;
  47693. }
  47694. /**
  47695. * Destroys the GPU data for the given texture object.
  47696. *
  47697. * @param {Texture} texture - The texture.
  47698. */
  47699. destroyTexture( texture ) {
  47700. const backend = this.backend;
  47701. const textureData = backend.get( texture );
  47702. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  47703. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  47704. backend.delete( texture );
  47705. }
  47706. /**
  47707. * Destroys the GPU sampler for the given texture.
  47708. *
  47709. * @param {Texture} texture - The texture to destroy the sampler for.
  47710. */
  47711. destroySampler( texture ) {
  47712. const backend = this.backend;
  47713. const textureData = backend.get( texture );
  47714. delete textureData.sampler;
  47715. }
  47716. /**
  47717. * Generates mipmaps for the given texture.
  47718. *
  47719. * @param {Texture} texture - The texture.
  47720. */
  47721. generateMipmaps( texture ) {
  47722. const textureData = this.backend.get( texture );
  47723. if ( texture.isCubeTexture ) {
  47724. for ( let i = 0; i < 6; i ++ ) {
  47725. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  47726. }
  47727. } else {
  47728. const depth = texture.image.depth || 1;
  47729. for ( let i = 0; i < depth; i ++ ) {
  47730. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  47731. }
  47732. }
  47733. }
  47734. /**
  47735. * Returns the color buffer representing the color
  47736. * attachment of the default framebuffer.
  47737. *
  47738. * @return {GPUTexture} The color buffer.
  47739. */
  47740. getColorBuffer() {
  47741. if ( this.colorBuffer ) this.colorBuffer.destroy();
  47742. const backend = this.backend;
  47743. const { width, height } = backend.getDrawingBufferSize();
  47744. this.colorBuffer = backend.device.createTexture( {
  47745. label: 'colorBuffer',
  47746. size: {
  47747. width: width,
  47748. height: height,
  47749. depthOrArrayLayers: 1
  47750. },
  47751. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  47752. format: backend.utils.getPreferredCanvasFormat(),
  47753. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  47754. } );
  47755. return this.colorBuffer;
  47756. }
  47757. /**
  47758. * Returns the depth buffer representing the depth
  47759. * attachment of the default framebuffer.
  47760. *
  47761. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  47762. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  47763. * @return {GPUTexture} The depth buffer.
  47764. */
  47765. getDepthBuffer( depth = true, stencil = false ) {
  47766. const backend = this.backend;
  47767. const { width, height } = backend.getDrawingBufferSize();
  47768. const depthTexture = this.depthTexture;
  47769. const depthTextureGPU = backend.get( depthTexture ).texture;
  47770. let format, type;
  47771. if ( stencil ) {
  47772. format = DepthStencilFormat;
  47773. type = UnsignedInt248Type;
  47774. } else if ( depth ) {
  47775. format = DepthFormat;
  47776. type = UnsignedIntType;
  47777. }
  47778. if ( depthTextureGPU !== undefined ) {
  47779. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  47780. return depthTextureGPU;
  47781. }
  47782. this.destroyTexture( depthTexture );
  47783. }
  47784. depthTexture.name = 'depthBuffer';
  47785. depthTexture.format = format;
  47786. depthTexture.type = type;
  47787. depthTexture.image.width = width;
  47788. depthTexture.image.height = height;
  47789. this.createTexture( depthTexture, { width, height } );
  47790. return backend.get( depthTexture ).texture;
  47791. }
  47792. /**
  47793. * Uploads the updated texture data to the GPU.
  47794. *
  47795. * @param {Texture} texture - The texture.
  47796. * @param {Object} [options={}] - Optional configuration parameter.
  47797. */
  47798. updateTexture( texture, options ) {
  47799. const textureData = this.backend.get( texture );
  47800. const mipmaps = texture.mipmaps;
  47801. const { textureDescriptorGPU } = textureData;
  47802. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  47803. return;
  47804. // transfer texture data
  47805. if ( texture.isDataTexture ) {
  47806. if ( mipmaps.length > 0 ) {
  47807. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47808. const mipmap = mipmaps[ i ];
  47809. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  47810. }
  47811. } else {
  47812. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  47813. }
  47814. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  47815. for ( let i = 0; i < options.image.depth; i ++ ) {
  47816. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  47817. }
  47818. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  47819. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  47820. } else if ( texture.isCubeTexture ) {
  47821. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  47822. } else {
  47823. if ( mipmaps.length > 0 ) {
  47824. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47825. const mipmap = mipmaps[ i ];
  47826. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  47827. }
  47828. } else {
  47829. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  47830. }
  47831. }
  47832. //
  47833. textureData.version = texture.version;
  47834. if ( texture.onUpdate ) texture.onUpdate( texture );
  47835. }
  47836. /**
  47837. * Returns texture data as a typed array.
  47838. *
  47839. * @async
  47840. * @param {Texture} texture - The texture to copy.
  47841. * @param {number} x - The x coordinate of the copy origin.
  47842. * @param {number} y - The y coordinate of the copy origin.
  47843. * @param {number} width - The width of the copy.
  47844. * @param {number} height - The height of the copy.
  47845. * @param {number} faceIndex - The face index.
  47846. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47847. */
  47848. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47849. const device = this.backend.device;
  47850. const textureData = this.backend.get( texture );
  47851. const textureGPU = textureData.texture;
  47852. const format = textureData.textureDescriptorGPU.format;
  47853. const bytesPerTexel = this._getBytesPerTexel( format );
  47854. let bytesPerRow = width * bytesPerTexel;
  47855. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  47856. const readBuffer = device.createBuffer(
  47857. {
  47858. size: width * height * bytesPerTexel,
  47859. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47860. }
  47861. );
  47862. const encoder = device.createCommandEncoder();
  47863. encoder.copyTextureToBuffer(
  47864. {
  47865. texture: textureGPU,
  47866. origin: { x, y, z: faceIndex },
  47867. },
  47868. {
  47869. buffer: readBuffer,
  47870. bytesPerRow: bytesPerRow
  47871. },
  47872. {
  47873. width: width,
  47874. height: height
  47875. }
  47876. );
  47877. const typedArrayType = this._getTypedArrayType( format );
  47878. device.queue.submit( [ encoder.finish() ] );
  47879. await readBuffer.mapAsync( GPUMapMode.READ );
  47880. const buffer = readBuffer.getMappedRange();
  47881. return new typedArrayType( buffer );
  47882. }
  47883. /**
  47884. * Returns the default GPU texture for the given format.
  47885. *
  47886. * @private
  47887. * @param {string} format - The GPU format.
  47888. * @return {GPUTexture} The GPU texture.
  47889. */
  47890. _getDefaultTextureGPU( format ) {
  47891. let defaultTexture = this.defaultTexture[ format ];
  47892. if ( defaultTexture === undefined ) {
  47893. const texture = new Texture();
  47894. texture.minFilter = NearestFilter;
  47895. texture.magFilter = NearestFilter;
  47896. this.createTexture( texture, { width: 1, height: 1, format } );
  47897. this.defaultTexture[ format ] = defaultTexture = texture;
  47898. }
  47899. return this.backend.get( defaultTexture ).texture;
  47900. }
  47901. /**
  47902. * Returns the default GPU cube texture for the given format.
  47903. *
  47904. * @private
  47905. * @param {string} format - The GPU format.
  47906. * @return {GPUTexture} The GPU texture.
  47907. */
  47908. _getDefaultCubeTextureGPU( format ) {
  47909. let defaultCubeTexture = this.defaultTexture[ format ];
  47910. if ( defaultCubeTexture === undefined ) {
  47911. const texture = new CubeTexture();
  47912. texture.minFilter = NearestFilter;
  47913. texture.magFilter = NearestFilter;
  47914. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  47915. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  47916. }
  47917. return this.backend.get( defaultCubeTexture ).texture;
  47918. }
  47919. /**
  47920. * Uploads cube texture image data to the GPU memory.
  47921. *
  47922. * @private
  47923. * @param {CubeTexture} texture - The cube texture.
  47924. * @param {GPUTexture} textureGPU - The GPU texture.
  47925. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47926. */
  47927. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  47928. const images = texture.images;
  47929. const mipmaps = texture.mipmaps;
  47930. for ( let i = 0; i < 6; i ++ ) {
  47931. const image = images[ i ];
  47932. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  47933. if ( image.isDataTexture ) {
  47934. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  47935. } else {
  47936. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  47937. }
  47938. for ( let j = 0; j < mipmaps.length; j ++ ) {
  47939. const mipmap = mipmaps[ j ];
  47940. const image = mipmap.images[ i ];
  47941. if ( image.isDataTexture ) {
  47942. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  47943. } else {
  47944. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  47945. }
  47946. }
  47947. }
  47948. }
  47949. /**
  47950. * Uploads texture image data to the GPU memory.
  47951. *
  47952. * @private
  47953. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  47954. * @param {GPUTexture} textureGPU - The GPU texture.
  47955. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47956. * @param {number} originDepth - The origin depth.
  47957. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  47958. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  47959. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  47960. */
  47961. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  47962. const device = this.backend.device;
  47963. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  47964. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  47965. device.queue.copyExternalImageToTexture(
  47966. {
  47967. source: image,
  47968. flipY: flipY
  47969. }, {
  47970. texture: textureGPU,
  47971. mipLevel: mipLevel,
  47972. origin: { x: 0, y: 0, z: originDepth },
  47973. premultipliedAlpha: premultiplyAlpha
  47974. }, {
  47975. width: width,
  47976. height: height,
  47977. depthOrArrayLayers: 1
  47978. }
  47979. );
  47980. }
  47981. /**
  47982. * Returns the pass utils singleton.
  47983. *
  47984. * @private
  47985. * @return {WebGPUTexturePassUtils} The utils instance.
  47986. */
  47987. _getPassUtils() {
  47988. let passUtils = this._passUtils;
  47989. if ( passUtils === null ) {
  47990. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  47991. }
  47992. return passUtils;
  47993. }
  47994. /**
  47995. * Generates mipmaps for the given GPU texture.
  47996. *
  47997. * @private
  47998. * @param {GPUTexture} textureGPU - The GPU texture object.
  47999. * @param {Object} textureDescriptorGPU - The texture descriptor.
  48000. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  48001. */
  48002. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  48003. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  48004. }
  48005. /**
  48006. * Flip the contents of the given GPU texture along its vertical axis.
  48007. *
  48008. * @private
  48009. * @param {GPUTexture} textureGPU - The GPU texture object.
  48010. * @param {Object} textureDescriptorGPU - The texture descriptor.
  48011. * @param {number} [originDepth=0] - The origin depth.
  48012. */
  48013. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  48014. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  48015. }
  48016. /**
  48017. * Uploads texture buffer data to the GPU memory.
  48018. *
  48019. * @private
  48020. * @param {Object} image - An object defining the image buffer data.
  48021. * @param {GPUTexture} textureGPU - The GPU texture.
  48022. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48023. * @param {number} originDepth - The origin depth.
  48024. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  48025. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  48026. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  48027. */
  48028. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  48029. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  48030. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  48031. const device = this.backend.device;
  48032. const data = image.data;
  48033. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  48034. const bytesPerRow = image.width * bytesPerTexel;
  48035. device.queue.writeTexture(
  48036. {
  48037. texture: textureGPU,
  48038. mipLevel: mipLevel,
  48039. origin: { x: 0, y: 0, z: originDepth }
  48040. },
  48041. data,
  48042. {
  48043. offset: image.width * image.height * bytesPerTexel * depth,
  48044. bytesPerRow
  48045. },
  48046. {
  48047. width: image.width,
  48048. height: image.height,
  48049. depthOrArrayLayers: 1
  48050. } );
  48051. if ( flipY === true ) {
  48052. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  48053. }
  48054. }
  48055. /**
  48056. * Uploads compressed texture data to the GPU memory.
  48057. *
  48058. * @private
  48059. * @param {Array<Object>} mipmaps - An array with mipmap data.
  48060. * @param {GPUTexture} textureGPU - The GPU texture.
  48061. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48062. */
  48063. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  48064. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  48065. const device = this.backend.device;
  48066. const blockData = this._getBlockData( textureDescriptorGPU.format );
  48067. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  48068. for ( let i = 0; i < mipmaps.length; i ++ ) {
  48069. const mipmap = mipmaps[ i ];
  48070. const width = mipmap.width;
  48071. const height = mipmap.height;
  48072. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  48073. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  48074. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  48075. for ( let j = 0; j < depth; j ++ ) {
  48076. device.queue.writeTexture(
  48077. {
  48078. texture: textureGPU,
  48079. mipLevel: i,
  48080. origin: { x: 0, y: 0, z: j }
  48081. },
  48082. mipmap.data,
  48083. {
  48084. offset: j * bytesPerImage,
  48085. bytesPerRow,
  48086. rowsPerImage: Math.ceil( height / blockData.height )
  48087. },
  48088. {
  48089. width: Math.ceil( width / blockData.width ) * blockData.width,
  48090. height: Math.ceil( height / blockData.height ) * blockData.height,
  48091. depthOrArrayLayers: 1
  48092. }
  48093. );
  48094. }
  48095. }
  48096. }
  48097. /**
  48098. * This method is only relevant for compressed texture formats. It returns a block
  48099. * data descriptor for the given GPU compressed texture format.
  48100. *
  48101. * @private
  48102. * @param {string} format - The GPU compressed texture format.
  48103. * @return {Object} The block data descriptor.
  48104. */
  48105. _getBlockData( format ) {
  48106. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  48107. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  48108. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  48109. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  48110. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  48111. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  48112. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  48113. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  48114. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  48115. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  48116. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  48117. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  48118. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  48119. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  48120. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  48121. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  48122. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  48123. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  48124. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  48125. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  48126. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  48127. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  48128. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  48129. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  48130. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  48131. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  48132. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  48133. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  48134. }
  48135. /**
  48136. * Converts the three.js uv wrapping constants to GPU address mode constants.
  48137. *
  48138. * @private
  48139. * @param {number} value - The three.js constant defining a uv wrapping mode.
  48140. * @return {string} The GPU address mode.
  48141. */
  48142. _convertAddressMode( value ) {
  48143. let addressMode = GPUAddressMode.ClampToEdge;
  48144. if ( value === RepeatWrapping ) {
  48145. addressMode = GPUAddressMode.Repeat;
  48146. } else if ( value === MirroredRepeatWrapping ) {
  48147. addressMode = GPUAddressMode.MirrorRepeat;
  48148. }
  48149. return addressMode;
  48150. }
  48151. /**
  48152. * Converts the three.js filter constants to GPU filter constants.
  48153. *
  48154. * @private
  48155. * @param {number} value - The three.js constant defining a filter mode.
  48156. * @return {string} The GPU filter mode.
  48157. */
  48158. _convertFilterMode( value ) {
  48159. let filterMode = GPUFilterMode.Linear;
  48160. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  48161. filterMode = GPUFilterMode.Nearest;
  48162. }
  48163. return filterMode;
  48164. }
  48165. /**
  48166. * Returns the bytes-per-texel value for the given GPU texture format.
  48167. *
  48168. * @private
  48169. * @param {string} format - The GPU texture format.
  48170. * @return {number} The bytes-per-texel.
  48171. */
  48172. _getBytesPerTexel( format ) {
  48173. // 8-bit formats
  48174. if ( format === GPUTextureFormat.R8Unorm ||
  48175. format === GPUTextureFormat.R8Snorm ||
  48176. format === GPUTextureFormat.R8Uint ||
  48177. format === GPUTextureFormat.R8Sint ) return 1;
  48178. // 16-bit formats
  48179. if ( format === GPUTextureFormat.R16Uint ||
  48180. format === GPUTextureFormat.R16Sint ||
  48181. format === GPUTextureFormat.R16Float ||
  48182. format === GPUTextureFormat.RG8Unorm ||
  48183. format === GPUTextureFormat.RG8Snorm ||
  48184. format === GPUTextureFormat.RG8Uint ||
  48185. format === GPUTextureFormat.RG8Sint ) return 2;
  48186. // 32-bit formats
  48187. if ( format === GPUTextureFormat.R32Uint ||
  48188. format === GPUTextureFormat.R32Sint ||
  48189. format === GPUTextureFormat.R32Float ||
  48190. format === GPUTextureFormat.RG16Uint ||
  48191. format === GPUTextureFormat.RG16Sint ||
  48192. format === GPUTextureFormat.RG16Float ||
  48193. format === GPUTextureFormat.RGBA8Unorm ||
  48194. format === GPUTextureFormat.RGBA8UnormSRGB ||
  48195. format === GPUTextureFormat.RGBA8Snorm ||
  48196. format === GPUTextureFormat.RGBA8Uint ||
  48197. format === GPUTextureFormat.RGBA8Sint ||
  48198. format === GPUTextureFormat.BGRA8Unorm ||
  48199. format === GPUTextureFormat.BGRA8UnormSRGB ||
  48200. // Packed 32-bit formats
  48201. format === GPUTextureFormat.RGB9E5UFloat ||
  48202. format === GPUTextureFormat.RGB10A2Unorm ||
  48203. format === GPUTextureFormat.RG11B10UFloat ||
  48204. format === GPUTextureFormat.Depth32Float ||
  48205. format === GPUTextureFormat.Depth24Plus ||
  48206. format === GPUTextureFormat.Depth24PlusStencil8 ||
  48207. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  48208. // 64-bit formats
  48209. if ( format === GPUTextureFormat.RG32Uint ||
  48210. format === GPUTextureFormat.RG32Sint ||
  48211. format === GPUTextureFormat.RG32Float ||
  48212. format === GPUTextureFormat.RGBA16Uint ||
  48213. format === GPUTextureFormat.RGBA16Sint ||
  48214. format === GPUTextureFormat.RGBA16Float ) return 8;
  48215. // 128-bit formats
  48216. if ( format === GPUTextureFormat.RGBA32Uint ||
  48217. format === GPUTextureFormat.RGBA32Sint ||
  48218. format === GPUTextureFormat.RGBA32Float ) return 16;
  48219. }
  48220. /**
  48221. * Returns the corresponding typed array type for the given GPU texture format.
  48222. *
  48223. * @private
  48224. * @param {string} format - The GPU texture format.
  48225. * @return {TypedArray.constructor} The typed array type.
  48226. */
  48227. _getTypedArrayType( format ) {
  48228. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  48229. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  48230. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  48231. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  48232. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  48233. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  48234. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  48235. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  48236. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  48237. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  48238. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  48239. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  48240. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  48241. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  48242. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  48243. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  48244. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  48245. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  48246. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  48247. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  48248. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  48249. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  48250. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  48251. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  48252. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  48253. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  48254. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  48255. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  48256. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  48257. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  48258. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  48259. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  48260. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  48261. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  48262. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  48263. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  48264. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  48265. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  48266. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  48267. }
  48268. /**
  48269. * Returns the GPU dimensions for the given texture.
  48270. *
  48271. * @private
  48272. * @param {Texture} texture - The texture.
  48273. * @return {string} The GPU dimension.
  48274. */
  48275. _getDimension( texture ) {
  48276. let dimension;
  48277. if ( texture.is3DTexture || texture.isData3DTexture ) {
  48278. dimension = GPUTextureDimension.ThreeD;
  48279. } else {
  48280. dimension = GPUTextureDimension.TwoD;
  48281. }
  48282. return dimension;
  48283. }
  48284. }
  48285. /**
  48286. * Returns the GPU format for the given texture.
  48287. *
  48288. * @param {Texture} texture - The texture.
  48289. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  48290. * It is not necessary to apply the device for most formats.
  48291. * @return {string} The GPU format.
  48292. */
  48293. function getFormat( texture, device = null ) {
  48294. const format = texture.format;
  48295. const type = texture.type;
  48296. const colorSpace = texture.colorSpace;
  48297. const transfer = ColorManagement.getTransfer( colorSpace );
  48298. let formatGPU;
  48299. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  48300. switch ( format ) {
  48301. case RGBA_S3TC_DXT1_Format:
  48302. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  48303. break;
  48304. case RGBA_S3TC_DXT3_Format:
  48305. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  48306. break;
  48307. case RGBA_S3TC_DXT5_Format:
  48308. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  48309. break;
  48310. case RGB_ETC2_Format:
  48311. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  48312. break;
  48313. case RGBA_ETC2_EAC_Format:
  48314. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  48315. break;
  48316. case RGBA_ASTC_4x4_Format:
  48317. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  48318. break;
  48319. case RGBA_ASTC_5x4_Format:
  48320. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  48321. break;
  48322. case RGBA_ASTC_5x5_Format:
  48323. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  48324. break;
  48325. case RGBA_ASTC_6x5_Format:
  48326. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  48327. break;
  48328. case RGBA_ASTC_6x6_Format:
  48329. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  48330. break;
  48331. case RGBA_ASTC_8x5_Format:
  48332. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  48333. break;
  48334. case RGBA_ASTC_8x6_Format:
  48335. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  48336. break;
  48337. case RGBA_ASTC_8x8_Format:
  48338. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  48339. break;
  48340. case RGBA_ASTC_10x5_Format:
  48341. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  48342. break;
  48343. case RGBA_ASTC_10x6_Format:
  48344. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  48345. break;
  48346. case RGBA_ASTC_10x8_Format:
  48347. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  48348. break;
  48349. case RGBA_ASTC_10x10_Format:
  48350. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  48351. break;
  48352. case RGBA_ASTC_12x10_Format:
  48353. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  48354. break;
  48355. case RGBA_ASTC_12x12_Format:
  48356. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  48357. break;
  48358. case RGBAFormat:
  48359. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  48360. break;
  48361. default:
  48362. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  48363. }
  48364. } else {
  48365. switch ( format ) {
  48366. case RGBAFormat:
  48367. switch ( type ) {
  48368. case ByteType:
  48369. formatGPU = GPUTextureFormat.RGBA8Snorm;
  48370. break;
  48371. case ShortType:
  48372. formatGPU = GPUTextureFormat.RGBA16Sint;
  48373. break;
  48374. case UnsignedShortType:
  48375. formatGPU = GPUTextureFormat.RGBA16Uint;
  48376. break;
  48377. case UnsignedIntType:
  48378. formatGPU = GPUTextureFormat.RGBA32Uint;
  48379. break;
  48380. case IntType:
  48381. formatGPU = GPUTextureFormat.RGBA32Sint;
  48382. break;
  48383. case UnsignedByteType:
  48384. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  48385. break;
  48386. case HalfFloatType:
  48387. formatGPU = GPUTextureFormat.RGBA16Float;
  48388. break;
  48389. case FloatType:
  48390. formatGPU = GPUTextureFormat.RGBA32Float;
  48391. break;
  48392. default:
  48393. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  48394. }
  48395. break;
  48396. case RGBFormat:
  48397. switch ( type ) {
  48398. case UnsignedInt5999Type:
  48399. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  48400. break;
  48401. case UnsignedInt101111Type:
  48402. formatGPU = GPUTextureFormat.RG11B10UFloat;
  48403. break;
  48404. default:
  48405. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  48406. }
  48407. break;
  48408. case RedFormat:
  48409. switch ( type ) {
  48410. case ByteType:
  48411. formatGPU = GPUTextureFormat.R8Snorm;
  48412. break;
  48413. case ShortType:
  48414. formatGPU = GPUTextureFormat.R16Sint;
  48415. break;
  48416. case UnsignedShortType:
  48417. formatGPU = GPUTextureFormat.R16Uint;
  48418. break;
  48419. case UnsignedIntType:
  48420. formatGPU = GPUTextureFormat.R32Uint;
  48421. break;
  48422. case IntType:
  48423. formatGPU = GPUTextureFormat.R32Sint;
  48424. break;
  48425. case UnsignedByteType:
  48426. formatGPU = GPUTextureFormat.R8Unorm;
  48427. break;
  48428. case HalfFloatType:
  48429. formatGPU = GPUTextureFormat.R16Float;
  48430. break;
  48431. case FloatType:
  48432. formatGPU = GPUTextureFormat.R32Float;
  48433. break;
  48434. default:
  48435. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  48436. }
  48437. break;
  48438. case RGFormat:
  48439. switch ( type ) {
  48440. case ByteType:
  48441. formatGPU = GPUTextureFormat.RG8Snorm;
  48442. break;
  48443. case ShortType:
  48444. formatGPU = GPUTextureFormat.RG16Sint;
  48445. break;
  48446. case UnsignedShortType:
  48447. formatGPU = GPUTextureFormat.RG16Uint;
  48448. break;
  48449. case UnsignedIntType:
  48450. formatGPU = GPUTextureFormat.RG32Uint;
  48451. break;
  48452. case IntType:
  48453. formatGPU = GPUTextureFormat.RG32Sint;
  48454. break;
  48455. case UnsignedByteType:
  48456. formatGPU = GPUTextureFormat.RG8Unorm;
  48457. break;
  48458. case HalfFloatType:
  48459. formatGPU = GPUTextureFormat.RG16Float;
  48460. break;
  48461. case FloatType:
  48462. formatGPU = GPUTextureFormat.RG32Float;
  48463. break;
  48464. default:
  48465. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  48466. }
  48467. break;
  48468. case DepthFormat:
  48469. switch ( type ) {
  48470. case UnsignedShortType:
  48471. formatGPU = GPUTextureFormat.Depth16Unorm;
  48472. break;
  48473. case UnsignedIntType:
  48474. formatGPU = GPUTextureFormat.Depth24Plus;
  48475. break;
  48476. case FloatType:
  48477. formatGPU = GPUTextureFormat.Depth32Float;
  48478. break;
  48479. default:
  48480. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  48481. }
  48482. break;
  48483. case DepthStencilFormat:
  48484. switch ( type ) {
  48485. case UnsignedInt248Type:
  48486. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  48487. break;
  48488. case FloatType:
  48489. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  48490. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  48491. }
  48492. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  48493. break;
  48494. default:
  48495. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  48496. }
  48497. break;
  48498. case RedIntegerFormat:
  48499. switch ( type ) {
  48500. case IntType:
  48501. formatGPU = GPUTextureFormat.R32Sint;
  48502. break;
  48503. case UnsignedIntType:
  48504. formatGPU = GPUTextureFormat.R32Uint;
  48505. break;
  48506. default:
  48507. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  48508. }
  48509. break;
  48510. case RGIntegerFormat:
  48511. switch ( type ) {
  48512. case IntType:
  48513. formatGPU = GPUTextureFormat.RG32Sint;
  48514. break;
  48515. case UnsignedIntType:
  48516. formatGPU = GPUTextureFormat.RG32Uint;
  48517. break;
  48518. default:
  48519. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  48520. }
  48521. break;
  48522. case RGBAIntegerFormat:
  48523. switch ( type ) {
  48524. case IntType:
  48525. formatGPU = GPUTextureFormat.RGBA32Sint;
  48526. break;
  48527. case UnsignedIntType:
  48528. formatGPU = GPUTextureFormat.RGBA32Uint;
  48529. break;
  48530. default:
  48531. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  48532. }
  48533. break;
  48534. default:
  48535. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  48536. }
  48537. }
  48538. return formatGPU;
  48539. }
  48540. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  48541. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  48542. const wgslTypeLib$1 = {
  48543. 'f32': 'float',
  48544. 'i32': 'int',
  48545. 'u32': 'uint',
  48546. 'bool': 'bool',
  48547. 'vec2<f32>': 'vec2',
  48548. 'vec2<i32>': 'ivec2',
  48549. 'vec2<u32>': 'uvec2',
  48550. 'vec2<bool>': 'bvec2',
  48551. 'vec2f': 'vec2',
  48552. 'vec2i': 'ivec2',
  48553. 'vec2u': 'uvec2',
  48554. 'vec2b': 'bvec2',
  48555. 'vec3<f32>': 'vec3',
  48556. 'vec3<i32>': 'ivec3',
  48557. 'vec3<u32>': 'uvec3',
  48558. 'vec3<bool>': 'bvec3',
  48559. 'vec3f': 'vec3',
  48560. 'vec3i': 'ivec3',
  48561. 'vec3u': 'uvec3',
  48562. 'vec3b': 'bvec3',
  48563. 'vec4<f32>': 'vec4',
  48564. 'vec4<i32>': 'ivec4',
  48565. 'vec4<u32>': 'uvec4',
  48566. 'vec4<bool>': 'bvec4',
  48567. 'vec4f': 'vec4',
  48568. 'vec4i': 'ivec4',
  48569. 'vec4u': 'uvec4',
  48570. 'vec4b': 'bvec4',
  48571. 'mat2x2<f32>': 'mat2',
  48572. 'mat2x2f': 'mat2',
  48573. 'mat3x3<f32>': 'mat3',
  48574. 'mat3x3f': 'mat3',
  48575. 'mat4x4<f32>': 'mat4',
  48576. 'mat4x4f': 'mat4',
  48577. 'sampler': 'sampler',
  48578. 'texture_1d': 'texture',
  48579. 'texture_2d': 'texture',
  48580. 'texture_2d_array': 'texture',
  48581. 'texture_multisampled_2d': 'cubeTexture',
  48582. 'texture_depth_2d': 'depthTexture',
  48583. 'texture_depth_2d_array': 'depthTexture',
  48584. 'texture_depth_multisampled_2d': 'depthTexture',
  48585. 'texture_depth_cube': 'depthTexture',
  48586. 'texture_depth_cube_array': 'depthTexture',
  48587. 'texture_3d': 'texture3D',
  48588. 'texture_cube': 'cubeTexture',
  48589. 'texture_cube_array': 'cubeTexture',
  48590. 'texture_storage_1d': 'storageTexture',
  48591. 'texture_storage_2d': 'storageTexture',
  48592. 'texture_storage_2d_array': 'storageTexture',
  48593. 'texture_storage_3d': 'storageTexture'
  48594. };
  48595. const parse = ( source ) => {
  48596. source = source.trim();
  48597. const declaration = source.match( declarationRegexp );
  48598. if ( declaration !== null && declaration.length === 4 ) {
  48599. const inputsCode = declaration[ 2 ];
  48600. const propsMatches = [];
  48601. let match = null;
  48602. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  48603. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  48604. }
  48605. // Process matches to correctly pair names and types
  48606. const inputs = [];
  48607. for ( let i = 0; i < propsMatches.length; i ++ ) {
  48608. const { name, type } = propsMatches[ i ];
  48609. let resolvedType = type;
  48610. if ( resolvedType.startsWith( 'ptr' ) ) {
  48611. resolvedType = 'pointer';
  48612. } else {
  48613. if ( resolvedType.startsWith( 'texture' ) ) {
  48614. resolvedType = type.split( '<' )[ 0 ];
  48615. }
  48616. resolvedType = wgslTypeLib$1[ resolvedType ];
  48617. }
  48618. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  48619. }
  48620. const blockCode = source.substring( declaration[ 0 ].length );
  48621. const outputType = declaration[ 3 ] || 'void';
  48622. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  48623. const type = wgslTypeLib$1[ outputType ] || outputType;
  48624. return {
  48625. type,
  48626. inputs,
  48627. name,
  48628. inputsCode,
  48629. blockCode,
  48630. outputType
  48631. };
  48632. } else {
  48633. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  48634. }
  48635. };
  48636. /**
  48637. * This class represents a WSL node function.
  48638. *
  48639. * @augments NodeFunction
  48640. */
  48641. class WGSLNodeFunction extends NodeFunction {
  48642. /**
  48643. * Constructs a new WGSL node function.
  48644. *
  48645. * @param {string} source - The WGSL source.
  48646. */
  48647. constructor( source ) {
  48648. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  48649. super( type, inputs, name );
  48650. this.inputsCode = inputsCode;
  48651. this.blockCode = blockCode;
  48652. this.outputType = outputType;
  48653. }
  48654. /**
  48655. * This method returns the WGSL code of the node function.
  48656. *
  48657. * @param {string} [name=this.name] - The function's name.
  48658. * @return {string} The shader code.
  48659. */
  48660. getCode( name = this.name ) {
  48661. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  48662. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  48663. }
  48664. }
  48665. /**
  48666. * A WGSL node parser.
  48667. *
  48668. * @augments NodeParser
  48669. */
  48670. class WGSLNodeParser extends NodeParser {
  48671. /**
  48672. * The method parses the given WGSL code an returns a node function.
  48673. *
  48674. * @param {string} source - The WGSL code.
  48675. * @return {WGSLNodeFunction} A node function.
  48676. */
  48677. parseFunction( source ) {
  48678. return new WGSLNodeFunction( source );
  48679. }
  48680. }
  48681. // GPUShaderStage is not defined in browsers not supporting WebGPU
  48682. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  48683. const accessNames = {
  48684. [ NodeAccess.READ_ONLY ]: 'read',
  48685. [ NodeAccess.WRITE_ONLY ]: 'write',
  48686. [ NodeAccess.READ_WRITE ]: 'read_write'
  48687. };
  48688. const wrapNames = {
  48689. [ RepeatWrapping ]: 'repeat',
  48690. [ ClampToEdgeWrapping ]: 'clamp',
  48691. [ MirroredRepeatWrapping ]: 'mirror'
  48692. };
  48693. const gpuShaderStageLib = {
  48694. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  48695. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  48696. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  48697. };
  48698. const supports = {
  48699. instance: true,
  48700. swizzleAssign: false,
  48701. storageBuffer: true
  48702. };
  48703. const wgslFnOpLib = {
  48704. '^^': 'tsl_xor'
  48705. };
  48706. const wgslTypeLib = {
  48707. float: 'f32',
  48708. int: 'i32',
  48709. uint: 'u32',
  48710. bool: 'bool',
  48711. color: 'vec3<f32>',
  48712. vec2: 'vec2<f32>',
  48713. ivec2: 'vec2<i32>',
  48714. uvec2: 'vec2<u32>',
  48715. bvec2: 'vec2<bool>',
  48716. vec3: 'vec3<f32>',
  48717. ivec3: 'vec3<i32>',
  48718. uvec3: 'vec3<u32>',
  48719. bvec3: 'vec3<bool>',
  48720. vec4: 'vec4<f32>',
  48721. ivec4: 'vec4<i32>',
  48722. uvec4: 'vec4<u32>',
  48723. bvec4: 'vec4<bool>',
  48724. mat2: 'mat2x2<f32>',
  48725. mat3: 'mat3x3<f32>',
  48726. mat4: 'mat4x4<f32>'
  48727. };
  48728. const wgslCodeCache = {};
  48729. const wgslPolyfill = {
  48730. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  48731. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  48732. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  48733. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  48734. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  48735. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  48736. 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 ); }' ),
  48737. 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 ); }' ),
  48738. 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 ); }' ),
  48739. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  48740. 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 ); }' ),
  48741. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  48742. biquadraticTexture: new CodeNode( /* wgsl */`
  48743. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  48744. let res = vec2f( iRes );
  48745. let uvScaled = coord * res;
  48746. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  48747. // https://www.shadertoy.com/view/WtyXRy
  48748. let uv = uvWrapping - 0.5;
  48749. let iuv = floor( uv );
  48750. let f = fract( uv );
  48751. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  48752. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  48753. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  48754. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  48755. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  48756. }
  48757. ` )
  48758. };
  48759. const wgslMethods = {
  48760. dFdx: 'dpdx',
  48761. dFdy: '- dpdy',
  48762. mod_float: 'tsl_mod_float',
  48763. mod_vec2: 'tsl_mod_vec2',
  48764. mod_vec3: 'tsl_mod_vec3',
  48765. mod_vec4: 'tsl_mod_vec4',
  48766. equals_bool: 'tsl_equals_bool',
  48767. equals_bvec2: 'tsl_equals_bvec2',
  48768. equals_bvec3: 'tsl_equals_bvec3',
  48769. equals_bvec4: 'tsl_equals_bvec4',
  48770. inversesqrt: 'inverseSqrt',
  48771. bitcast: 'bitcast<f32>'
  48772. };
  48773. // WebGPU issue: does not support pow() with negative base on Windows
  48774. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  48775. 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 ); }' );
  48776. 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 ] );
  48777. 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 ] );
  48778. 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 ] );
  48779. wgslMethods.pow_float = 'tsl_pow_float';
  48780. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  48781. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  48782. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  48783. }
  48784. //
  48785. let diagnostics = '';
  48786. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  48787. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  48788. }
  48789. /**
  48790. * A node builder targeting WGSL.
  48791. *
  48792. * This module generates WGSL shader code from node materials and also
  48793. * generates the respective bindings and vertex buffer definitions. These
  48794. * data are later used by the renderer to create render and compute pipelines
  48795. * for render objects.
  48796. *
  48797. * @augments NodeBuilder
  48798. */
  48799. class WGSLNodeBuilder extends NodeBuilder {
  48800. /**
  48801. * Constructs a new WGSL node builder renderer.
  48802. *
  48803. * @param {Object3D} object - The 3D object.
  48804. * @param {Renderer} renderer - The renderer.
  48805. */
  48806. constructor( object, renderer ) {
  48807. super( object, renderer, new WGSLNodeParser() );
  48808. /**
  48809. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  48810. * another dictionary which manages UBOs per group ('render','frame','object').
  48811. *
  48812. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  48813. */
  48814. this.uniformGroups = {};
  48815. /**
  48816. * A dictionary that holds for each shader stage a Map of builtins.
  48817. *
  48818. * @type {Object<string,Map<string,Object>>}
  48819. */
  48820. this.builtins = {};
  48821. /**
  48822. * A dictionary that holds for each shader stage a Set of directives.
  48823. *
  48824. * @type {Object<string,Set<string>>}
  48825. */
  48826. this.directives = {};
  48827. /**
  48828. * A map for managing scope arrays. Only relevant for when using
  48829. * {@link WorkgroupInfoNode} in context of compute shaders.
  48830. *
  48831. * @type {Map<string,Object>}
  48832. */
  48833. this.scopedArrays = new Map();
  48834. }
  48835. /**
  48836. * Generates the WGSL snippet for sampled textures.
  48837. *
  48838. * @private
  48839. * @param {Texture} texture - The texture.
  48840. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48841. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48842. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48843. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48844. * @return {string} The WGSL snippet.
  48845. */
  48846. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48847. if ( shaderStage === 'fragment' ) {
  48848. if ( depthSnippet ) {
  48849. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  48850. } else {
  48851. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  48852. }
  48853. } else {
  48854. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  48855. }
  48856. }
  48857. /**
  48858. * Generates the WGSL snippet when sampling textures with explicit mip level.
  48859. *
  48860. * @private
  48861. * @param {Texture} texture - The texture.
  48862. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48863. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48864. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48865. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48866. * @return {string} The WGSL snippet.
  48867. */
  48868. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  48869. if ( this.isUnfilterable( texture ) === false ) {
  48870. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  48871. } else if ( this.isFilteredTexture( texture ) ) {
  48872. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  48873. } else {
  48874. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  48875. }
  48876. }
  48877. /**
  48878. * Generates a wrap function used in context of textures.
  48879. *
  48880. * @param {Texture} texture - The texture to generate the function for.
  48881. * @return {string} The name of the generated function.
  48882. */
  48883. generateWrapFunction( texture ) {
  48884. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  48885. let nodeCode = wgslCodeCache[ functionName ];
  48886. if ( nodeCode === undefined ) {
  48887. const includes = [];
  48888. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  48889. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  48890. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  48891. const addWrapSnippet = ( wrap, axis ) => {
  48892. if ( wrap === RepeatWrapping ) {
  48893. includes.push( wgslPolyfill.repeatWrapping_float );
  48894. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  48895. } else if ( wrap === ClampToEdgeWrapping ) {
  48896. includes.push( wgslPolyfill.clampWrapping_float );
  48897. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  48898. } else if ( wrap === MirroredRepeatWrapping ) {
  48899. includes.push( wgslPolyfill.mirrorWrapping_float );
  48900. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  48901. } else {
  48902. code += `\t\tcoord.${ axis }`;
  48903. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  48904. }
  48905. };
  48906. addWrapSnippet( texture.wrapS, 'x' );
  48907. code += ',\n';
  48908. addWrapSnippet( texture.wrapT, 'y' );
  48909. if ( texture.isData3DTexture ) {
  48910. code += ',\n';
  48911. addWrapSnippet( texture.wrapR, 'z' );
  48912. }
  48913. code += '\n\t);\n\n}\n';
  48914. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  48915. }
  48916. nodeCode.build( this );
  48917. return functionName;
  48918. }
  48919. /**
  48920. * Generates the array declaration string.
  48921. *
  48922. * @param {string} type - The type.
  48923. * @param {?number} [count] - The count.
  48924. * @return {string} The generated value as a shader string.
  48925. */
  48926. generateArrayDeclaration( type, count ) {
  48927. return `array< ${ this.getType( type ) }, ${ count } >`;
  48928. }
  48929. /**
  48930. * Generates a WGSL variable that holds the texture dimension of the given texture.
  48931. * It also returns information about the number of layers (elements) of an arrayed
  48932. * texture as well as the cube face count of cube textures.
  48933. *
  48934. * @param {Texture} texture - The texture to generate the function for.
  48935. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  48936. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48937. * @return {string} The name of the dimension variable.
  48938. */
  48939. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  48940. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  48941. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  48942. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  48943. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  48944. let textureDimensionsParams;
  48945. let dimensionType;
  48946. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  48947. const isMultisampled = primarySamples > 1;
  48948. if ( texture.isData3DTexture ) {
  48949. dimensionType = 'vec3<u32>';
  48950. } else {
  48951. // Regular 2D textures, depth textures, etc.
  48952. dimensionType = 'vec2<u32>';
  48953. }
  48954. // Build parameters string based on texture type and multisampling
  48955. if ( isMultisampled || texture.isStorageTexture ) {
  48956. textureDimensionsParams = textureProperty;
  48957. } else {
  48958. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  48959. }
  48960. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  48961. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  48962. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  48963. textureData.arrayLayerCount = new VarNode(
  48964. new ExpressionNode(
  48965. `textureNumLayers(${textureProperty})`,
  48966. 'u32'
  48967. )
  48968. );
  48969. }
  48970. // For cube textures, we know it's always 6 faces
  48971. if ( texture.isTextureCube ) {
  48972. textureData.cubeFaceCount = new VarNode(
  48973. new ExpressionNode( '6u', 'u32' )
  48974. );
  48975. }
  48976. }
  48977. return textureDimensionNode.build( this );
  48978. }
  48979. /**
  48980. * Generates the WGSL snippet for a manual filtered texture.
  48981. *
  48982. * @param {Texture} texture - The texture.
  48983. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48984. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48985. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48986. * @return {string} The WGSL snippet.
  48987. */
  48988. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  48989. this._include( 'biquadraticTexture' );
  48990. const wrapFunction = this.generateWrapFunction( texture );
  48991. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  48992. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  48993. }
  48994. /**
  48995. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  48996. * Since it's a lookup, no sampling or filtering is applied.
  48997. *
  48998. * @param {Texture} texture - The texture.
  48999. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49000. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49001. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49002. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49003. * @return {string} The WGSL snippet.
  49004. */
  49005. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  49006. const wrapFunction = this.generateWrapFunction( texture );
  49007. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  49008. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  49009. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  49010. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  49011. }
  49012. /**
  49013. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  49014. *
  49015. * @param {Texture} texture - The texture.
  49016. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49017. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49018. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49019. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49020. * @return {string} The WGSL snippet.
  49021. */
  49022. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  49023. let snippet;
  49024. if ( depthSnippet ) {
  49025. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  49026. } else {
  49027. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  49028. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  49029. snippet += '.x';
  49030. }
  49031. }
  49032. return snippet;
  49033. }
  49034. /**
  49035. * Generates the WGSL snippet that writes a single texel to a texture.
  49036. *
  49037. * @param {Texture} texture - The texture.
  49038. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49039. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49040. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49041. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  49042. * @return {string} The WGSL snippet.
  49043. */
  49044. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  49045. let snippet;
  49046. if ( depthSnippet ) {
  49047. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  49048. } else {
  49049. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  49050. }
  49051. return snippet;
  49052. }
  49053. /**
  49054. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  49055. *
  49056. * @param {Texture} texture - The texture.
  49057. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  49058. */
  49059. isSampleCompare( texture ) {
  49060. return texture.isDepthTexture === true && texture.compareFunction !== null;
  49061. }
  49062. /**
  49063. * Returns `true` if the given texture is unfilterable.
  49064. *
  49065. * @param {Texture} texture - The texture.
  49066. * @return {boolean} Whether the given texture is unfilterable or not.
  49067. */
  49068. isUnfilterable( texture ) {
  49069. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  49070. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  49071. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  49072. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  49073. }
  49074. /**
  49075. * Generates the WGSL snippet for sampling/loading the given texture.
  49076. *
  49077. * @param {Texture} texture - The texture.
  49078. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49079. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49080. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49081. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49082. * @return {string} The WGSL snippet.
  49083. */
  49084. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  49085. let snippet = null;
  49086. if ( this.isUnfilterable( texture ) ) {
  49087. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  49088. } else {
  49089. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  49090. }
  49091. return snippet;
  49092. }
  49093. /**
  49094. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  49095. *
  49096. * @param {Texture} texture - The texture.
  49097. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49098. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49099. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  49100. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49101. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49102. * @return {string} The WGSL snippet.
  49103. */
  49104. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  49105. if ( shaderStage === 'fragment' ) {
  49106. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  49107. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  49108. } else {
  49109. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  49110. }
  49111. }
  49112. /**
  49113. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  49114. * against a reference value.
  49115. *
  49116. * @param {Texture} texture - The texture.
  49117. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49118. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49119. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  49120. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49121. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49122. * @return {string} The WGSL snippet.
  49123. */
  49124. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  49125. if ( shaderStage === 'fragment' ) {
  49126. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  49127. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  49128. }
  49129. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  49130. } else {
  49131. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  49132. }
  49133. }
  49134. /**
  49135. * Generates the WGSL snippet when sampling textures with explicit mip level.
  49136. *
  49137. * @param {Texture} texture - The texture.
  49138. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49139. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49140. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49141. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49142. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49143. * @return {string} The WGSL snippet.
  49144. */
  49145. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  49146. if ( this.isUnfilterable( texture ) === false ) {
  49147. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  49148. } else if ( this.isFilteredTexture( texture ) ) {
  49149. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  49150. } else {
  49151. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  49152. }
  49153. }
  49154. /**
  49155. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  49156. *
  49157. * @param {Texture} texture - The texture.
  49158. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49159. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49160. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  49161. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49162. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49163. * @return {string} The WGSL snippet.
  49164. */
  49165. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  49166. if ( shaderStage === 'fragment' ) {
  49167. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  49168. } else {
  49169. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  49170. }
  49171. }
  49172. /**
  49173. * Returns a WGSL snippet that represents the property name of the given node.
  49174. *
  49175. * @param {Node} node - The node.
  49176. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49177. * @return {string} The property name.
  49178. */
  49179. getPropertyName( node, shaderStage = this.shaderStage ) {
  49180. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  49181. if ( shaderStage === 'vertex' ) {
  49182. return `varyings.${ node.name }`;
  49183. }
  49184. } else if ( node.isNodeUniform === true ) {
  49185. const name = node.name;
  49186. const type = node.type;
  49187. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  49188. return name;
  49189. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  49190. if ( this.isCustomStruct( node ) ) {
  49191. return name;
  49192. }
  49193. return name + '.value';
  49194. } else {
  49195. return node.groupNode.name + '.' + name;
  49196. }
  49197. }
  49198. return super.getPropertyName( node );
  49199. }
  49200. /**
  49201. * Returns the output struct name.
  49202. *
  49203. * @return {string} The name of the output struct.
  49204. */
  49205. getOutputStructName() {
  49206. return 'output';
  49207. }
  49208. /**
  49209. * Returns the native shader operator name for a given generic name.
  49210. *
  49211. * @param {string} op - The operator name to resolve.
  49212. * @return {?string} The resolved operator name.
  49213. */
  49214. getFunctionOperator( op ) {
  49215. const fnOp = wgslFnOpLib[ op ];
  49216. if ( fnOp !== undefined ) {
  49217. this._include( fnOp );
  49218. return fnOp;
  49219. }
  49220. return null;
  49221. }
  49222. /**
  49223. * Returns the node access for the given node and shader stage.
  49224. *
  49225. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  49226. * @param {string} shaderStage - The shader stage.
  49227. * @return {string} The node access.
  49228. */
  49229. getNodeAccess( node, shaderStage ) {
  49230. if ( shaderStage !== 'compute' ) {
  49231. if ( node.isAtomic === true ) {
  49232. console.warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  49233. return NodeAccess.READ_WRITE;
  49234. }
  49235. return NodeAccess.READ_ONLY;
  49236. }
  49237. return node.access;
  49238. }
  49239. /**
  49240. * Returns A WGSL snippet representing the storage access.
  49241. *
  49242. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  49243. * @param {string} shaderStage - The shader stage.
  49244. * @return {string} The WGSL snippet representing the storage access.
  49245. */
  49246. getStorageAccess( node, shaderStage ) {
  49247. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  49248. }
  49249. /**
  49250. * This method is one of the more important ones since it's responsible
  49251. * for generating a matching binding instance for the given uniform node.
  49252. *
  49253. * These bindings are later used in the renderer to create bind groups
  49254. * and layouts.
  49255. *
  49256. * @param {UniformNode} node - The uniform node.
  49257. * @param {string} type - The node data type.
  49258. * @param {string} shaderStage - The shader stage.
  49259. * @param {?string} [name=null] - An optional uniform name.
  49260. * @return {NodeUniform} The node uniform object.
  49261. */
  49262. getUniformFromNode( node, type, shaderStage, name = null ) {
  49263. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  49264. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  49265. if ( nodeData.uniformGPU === undefined ) {
  49266. let uniformGPU;
  49267. const group = node.groupNode;
  49268. const groupName = group.name;
  49269. const bindings = this.getBindGroupArray( groupName, shaderStage );
  49270. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  49271. let texture = null;
  49272. const access = this.getNodeAccess( node, shaderStage );
  49273. if ( type === 'texture' || type === 'storageTexture' ) {
  49274. if ( node.value.is3DTexture === true ) {
  49275. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  49276. } else {
  49277. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  49278. }
  49279. } else if ( type === 'cubeTexture' ) {
  49280. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  49281. } else if ( type === 'texture3D' ) {
  49282. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  49283. }
  49284. texture.store = node.isStorageTextureNode === true;
  49285. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49286. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  49287. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  49288. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49289. bindings.push( sampler, texture );
  49290. uniformGPU = [ sampler, texture ];
  49291. } else {
  49292. bindings.push( texture );
  49293. uniformGPU = [ texture ];
  49294. }
  49295. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  49296. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  49297. const buffer = new bufferClass( node, group );
  49298. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49299. bindings.push( buffer );
  49300. uniformGPU = buffer;
  49301. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  49302. } else {
  49303. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  49304. let uniformsGroup = uniformsStage[ groupName ];
  49305. if ( uniformsGroup === undefined ) {
  49306. uniformsGroup = new NodeUniformsGroup( groupName, group );
  49307. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49308. uniformsStage[ groupName ] = uniformsGroup;
  49309. bindings.push( uniformsGroup );
  49310. }
  49311. uniformGPU = this.getNodeUniform( uniformNode, type );
  49312. uniformsGroup.addUniform( uniformGPU );
  49313. }
  49314. nodeData.uniformGPU = uniformGPU;
  49315. }
  49316. return uniformNode;
  49317. }
  49318. /**
  49319. * This method should be used whenever builtins are required in nodes.
  49320. * The internal builtins data structure will make sure builtins are
  49321. * defined in the WGSL source.
  49322. *
  49323. * @param {string} name - The builtin name.
  49324. * @param {string} property - The property name.
  49325. * @param {string} type - The node data type.
  49326. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49327. * @return {string} The property name.
  49328. */
  49329. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  49330. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  49331. if ( map.has( name ) === false ) {
  49332. map.set( name, {
  49333. name,
  49334. property,
  49335. type
  49336. } );
  49337. }
  49338. return property;
  49339. }
  49340. /**
  49341. * Returns `true` if the given builtin is defined in the given shader stage.
  49342. *
  49343. * @param {string} name - The builtin name.
  49344. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49345. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  49346. */
  49347. hasBuiltin( name, shaderStage = this.shaderStage ) {
  49348. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  49349. }
  49350. /**
  49351. * Returns the vertex index builtin.
  49352. *
  49353. * @return {string} The vertex index.
  49354. */
  49355. getVertexIndex() {
  49356. if ( this.shaderStage === 'vertex' ) {
  49357. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  49358. }
  49359. return 'vertexIndex';
  49360. }
  49361. /**
  49362. * Builds the given shader node.
  49363. *
  49364. * @param {ShaderNodeInternal} shaderNode - The shader node.
  49365. * @return {string} The WGSL function code.
  49366. */
  49367. buildFunctionCode( shaderNode ) {
  49368. const layout = shaderNode.layout;
  49369. const flowData = this.flowShaderNode( shaderNode );
  49370. const parameters = [];
  49371. for ( const input of layout.inputs ) {
  49372. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  49373. }
  49374. //
  49375. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  49376. ${ flowData.vars }
  49377. ${ flowData.code }
  49378. `;
  49379. if ( flowData.result ) {
  49380. code += `\treturn ${ flowData.result };\n`;
  49381. }
  49382. code += '\n}\n';
  49383. //
  49384. return code;
  49385. }
  49386. /**
  49387. * Returns the instance index builtin.
  49388. *
  49389. * @return {string} The instance index.
  49390. */
  49391. getInstanceIndex() {
  49392. if ( this.shaderStage === 'vertex' ) {
  49393. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  49394. }
  49395. return 'instanceIndex';
  49396. }
  49397. /**
  49398. * Returns the invocation local index builtin.
  49399. *
  49400. * @return {string} The invocation local index.
  49401. */
  49402. getInvocationLocalIndex() {
  49403. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  49404. }
  49405. /**
  49406. * Returns the subgroup size builtin.
  49407. *
  49408. * @return {string} The subgroup size.
  49409. */
  49410. getSubgroupSize() {
  49411. this.enableSubGroups();
  49412. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  49413. }
  49414. /**
  49415. * Returns the invocation subgroup index builtin.
  49416. *
  49417. * @return {string} The invocation subgroup index.
  49418. */
  49419. getInvocationSubgroupIndex() {
  49420. this.enableSubGroups();
  49421. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  49422. }
  49423. /**
  49424. * Returns the subgroup index builtin.
  49425. *
  49426. * @return {string} The subgroup index.
  49427. */
  49428. getSubgroupIndex() {
  49429. this.enableSubGroups();
  49430. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  49431. }
  49432. /**
  49433. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  49434. *
  49435. * @return {null} Null.
  49436. */
  49437. getDrawIndex() {
  49438. return null;
  49439. }
  49440. /**
  49441. * Returns the front facing builtin.
  49442. *
  49443. * @return {string} The front facing builtin.
  49444. */
  49445. getFrontFacing() {
  49446. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  49447. }
  49448. /**
  49449. * Returns the frag coord builtin.
  49450. *
  49451. * @return {string} The frag coord builtin.
  49452. */
  49453. getFragCoord() {
  49454. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  49455. }
  49456. /**
  49457. * Returns the frag depth builtin.
  49458. *
  49459. * @return {string} The frag depth builtin.
  49460. */
  49461. getFragDepth() {
  49462. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  49463. }
  49464. /**
  49465. * Returns the clip distances builtin.
  49466. *
  49467. * @return {string} The clip distances builtin.
  49468. */
  49469. getClipDistance() {
  49470. return 'varyings.hw_clip_distances';
  49471. }
  49472. /**
  49473. * Whether to flip texture data along its vertical axis or not.
  49474. *
  49475. * @return {boolean} Returns always `false` in context of WGSL.
  49476. */
  49477. isFlipY() {
  49478. return false;
  49479. }
  49480. /**
  49481. * Enables the given directive for the given shader stage.
  49482. *
  49483. * @param {string} name - The directive name.
  49484. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  49485. */
  49486. enableDirective( name, shaderStage = this.shaderStage ) {
  49487. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  49488. stage.add( name );
  49489. }
  49490. /**
  49491. * Returns the directives of the given shader stage as a WGSL string.
  49492. *
  49493. * @param {string} shaderStage - The shader stage.
  49494. * @return {string} A WGSL snippet that enables the directives of the given stage.
  49495. */
  49496. getDirectives( shaderStage ) {
  49497. const snippets = [];
  49498. const directives = this.directives[ shaderStage ];
  49499. if ( directives !== undefined ) {
  49500. for ( const directive of directives ) {
  49501. snippets.push( `enable ${directive};` );
  49502. }
  49503. }
  49504. return snippets.join( '\n' );
  49505. }
  49506. /**
  49507. * Enables the 'subgroups' directive.
  49508. */
  49509. enableSubGroups() {
  49510. this.enableDirective( 'subgroups' );
  49511. }
  49512. /**
  49513. * Enables the 'subgroups-f16' directive.
  49514. */
  49515. enableSubgroupsF16() {
  49516. this.enableDirective( 'subgroups-f16' );
  49517. }
  49518. /**
  49519. * Enables the 'clip_distances' directive.
  49520. */
  49521. enableClipDistances() {
  49522. this.enableDirective( 'clip_distances' );
  49523. }
  49524. /**
  49525. * Enables the 'f16' directive.
  49526. */
  49527. enableShaderF16() {
  49528. this.enableDirective( 'f16' );
  49529. }
  49530. /**
  49531. * Enables the 'dual_source_blending' directive.
  49532. */
  49533. enableDualSourceBlending() {
  49534. this.enableDirective( 'dual_source_blending' );
  49535. }
  49536. /**
  49537. * Enables hardware clipping.
  49538. *
  49539. * @param {string} planeCount - The clipping plane count.
  49540. */
  49541. enableHardwareClipping( planeCount ) {
  49542. this.enableClipDistances();
  49543. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  49544. }
  49545. /**
  49546. * Returns the builtins of the given shader stage as a WGSL string.
  49547. *
  49548. * @param {string} shaderStage - The shader stage.
  49549. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  49550. */
  49551. getBuiltins( shaderStage ) {
  49552. const snippets = [];
  49553. const builtins = this.builtins[ shaderStage ];
  49554. if ( builtins !== undefined ) {
  49555. for ( const { name, property, type } of builtins.values() ) {
  49556. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  49557. }
  49558. }
  49559. return snippets.join( ',\n\t' );
  49560. }
  49561. /**
  49562. * This method should be used when a new scoped buffer is used in context of
  49563. * compute shaders. It adds the array to the internal data structure which is
  49564. * later used to generate the respective WGSL.
  49565. *
  49566. * @param {string} name - The array name.
  49567. * @param {string} scope - The scope.
  49568. * @param {string} bufferType - The buffer type.
  49569. * @param {string} bufferCount - The buffer count.
  49570. * @return {string} The array name.
  49571. */
  49572. getScopedArray( name, scope, bufferType, bufferCount ) {
  49573. if ( this.scopedArrays.has( name ) === false ) {
  49574. this.scopedArrays.set( name, {
  49575. name,
  49576. scope,
  49577. bufferType,
  49578. bufferCount
  49579. } );
  49580. }
  49581. return name;
  49582. }
  49583. /**
  49584. * Returns the scoped arrays of the given shader stage as a WGSL string.
  49585. *
  49586. * @param {string} shaderStage - The shader stage.
  49587. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  49588. * Returns `undefined` when used in the vertex or fragment stage.
  49589. */
  49590. getScopedArrays( shaderStage ) {
  49591. if ( shaderStage !== 'compute' ) {
  49592. return;
  49593. }
  49594. const snippets = [];
  49595. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  49596. const type = this.getType( bufferType );
  49597. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  49598. }
  49599. return snippets.join( '\n' );
  49600. }
  49601. /**
  49602. * Returns the shader attributes of the given shader stage as a WGSL string.
  49603. *
  49604. * @param {string} shaderStage - The shader stage.
  49605. * @return {string} The WGSL snippet that defines the shader attributes.
  49606. */
  49607. getAttributes( shaderStage ) {
  49608. const snippets = [];
  49609. if ( shaderStage === 'compute' ) {
  49610. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  49611. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  49612. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  49613. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  49614. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  49615. this.enableDirective( 'subgroups', shaderStage );
  49616. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  49617. }
  49618. }
  49619. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  49620. const builtins = this.getBuiltins( 'attribute' );
  49621. if ( builtins ) snippets.push( builtins );
  49622. const attributes = this.getAttributesArray();
  49623. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  49624. const attribute = attributes[ index ];
  49625. const name = attribute.name;
  49626. const type = this.getType( attribute.type );
  49627. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  49628. }
  49629. }
  49630. return snippets.join( ',\n\t' );
  49631. }
  49632. /**
  49633. * Returns the members of the given struct type node as a WGSL string.
  49634. *
  49635. * @param {StructTypeNode} struct - The struct type node.
  49636. * @return {string} The WGSL snippet that defines the struct members.
  49637. */
  49638. getStructMembers( struct ) {
  49639. const snippets = [];
  49640. for ( const member of struct.members ) {
  49641. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  49642. let type = this.getType( member.type );
  49643. if ( member.atomic ) {
  49644. type = 'atomic< ' + type + ' >';
  49645. }
  49646. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  49647. }
  49648. if ( struct.output ) {
  49649. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  49650. }
  49651. return snippets.join( ',\n' );
  49652. }
  49653. /**
  49654. * Returns the structs of the given shader stage as a WGSL string.
  49655. *
  49656. * @param {string} shaderStage - The shader stage.
  49657. * @return {string} The WGSL snippet that defines the structs.
  49658. */
  49659. getStructs( shaderStage ) {
  49660. let result = '';
  49661. const structs = this.structs[ shaderStage ];
  49662. if ( structs.length > 0 ) {
  49663. const snippets = [];
  49664. for ( const struct of structs ) {
  49665. let snippet = `struct ${ struct.name } {\n`;
  49666. snippet += this.getStructMembers( struct );
  49667. snippet += '\n};';
  49668. snippets.push( snippet );
  49669. }
  49670. result = '\n' + snippets.join( '\n\n' ) + '\n';
  49671. }
  49672. return result;
  49673. }
  49674. /**
  49675. * Returns a WGSL string representing a variable.
  49676. *
  49677. * @param {string} type - The variable's type.
  49678. * @param {string} name - The variable's name.
  49679. * @param {?number} [count=null] - The array length.
  49680. * @return {string} The WGSL snippet that defines a variable.
  49681. */
  49682. getVar( type, name, count = null ) {
  49683. let snippet = `var ${ name } : `;
  49684. if ( count !== null ) {
  49685. snippet += this.generateArrayDeclaration( type, count );
  49686. } else {
  49687. snippet += this.getType( type );
  49688. }
  49689. return snippet;
  49690. }
  49691. /**
  49692. * Returns the variables of the given shader stage as a WGSL string.
  49693. *
  49694. * @param {string} shaderStage - The shader stage.
  49695. * @return {string} The WGSL snippet that defines the variables.
  49696. */
  49697. getVars( shaderStage ) {
  49698. const snippets = [];
  49699. const vars = this.vars[ shaderStage ];
  49700. if ( vars !== undefined ) {
  49701. for ( const variable of vars ) {
  49702. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  49703. }
  49704. }
  49705. return `\n${ snippets.join( '\n' ) }\n`;
  49706. }
  49707. /**
  49708. * Returns the varyings of the given shader stage as a WGSL string.
  49709. *
  49710. * @param {string} shaderStage - The shader stage.
  49711. * @return {string} The WGSL snippet that defines the varyings.
  49712. */
  49713. getVaryings( shaderStage ) {
  49714. const snippets = [];
  49715. if ( shaderStage === 'vertex' ) {
  49716. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  49717. }
  49718. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  49719. const varyings = this.varyings;
  49720. const vars = this.vars[ shaderStage ];
  49721. for ( let index = 0; index < varyings.length; index ++ ) {
  49722. const varying = varyings[ index ];
  49723. if ( varying.needsInterpolation ) {
  49724. let attributesSnippet = `@location( ${index} )`;
  49725. if ( varying.interpolationType ) {
  49726. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  49727. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  49728. // Otherwise, optimize interpolation when sensible
  49729. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  49730. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  49731. }
  49732. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  49733. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  49734. vars.push( varying );
  49735. }
  49736. }
  49737. }
  49738. const builtins = this.getBuiltins( shaderStage );
  49739. if ( builtins ) snippets.push( builtins );
  49740. const code = snippets.join( ',\n\t' );
  49741. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  49742. }
  49743. isCustomStruct( nodeUniform ) {
  49744. const attribute = nodeUniform.value;
  49745. const bufferNode = nodeUniform.node;
  49746. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  49747. const isStructArray =
  49748. ( bufferNode.value && bufferNode.value.array ) &&
  49749. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  49750. return isAttributeStructType && ! isStructArray;
  49751. }
  49752. /**
  49753. * Returns the uniforms of the given shader stage as a WGSL string.
  49754. *
  49755. * @param {string} shaderStage - The shader stage.
  49756. * @return {string} The WGSL snippet that defines the uniforms.
  49757. */
  49758. getUniforms( shaderStage ) {
  49759. const uniforms = this.uniforms[ shaderStage ];
  49760. const bindingSnippets = [];
  49761. const bufferSnippets = [];
  49762. const structSnippets = [];
  49763. const uniformGroups = {};
  49764. for ( const uniform of uniforms ) {
  49765. const groupName = uniform.groupNode.name;
  49766. const uniformIndexes = this.bindingsIndexes[ groupName ];
  49767. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  49768. const texture = uniform.node.value;
  49769. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  49770. if ( this.isSampleCompare( texture ) ) {
  49771. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  49772. } else {
  49773. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  49774. }
  49775. }
  49776. let textureType;
  49777. let multisampled = '';
  49778. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  49779. if ( primarySamples > 1 ) {
  49780. multisampled = '_multisampled';
  49781. }
  49782. if ( texture.isCubeTexture === true ) {
  49783. textureType = 'texture_cube<f32>';
  49784. } else if ( texture.isDepthTexture === true ) {
  49785. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  49786. textureType = `texture${ multisampled }_2d<f32>`;
  49787. } else {
  49788. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  49789. }
  49790. } else if ( uniform.node.isStorageTextureNode === true ) {
  49791. const format = getFormat( texture );
  49792. const access = this.getStorageAccess( uniform.node, shaderStage );
  49793. const is3D = uniform.node.value.is3DTexture;
  49794. const isArrayTexture = uniform.node.value.isArrayTexture;
  49795. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  49796. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  49797. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  49798. textureType = 'texture_2d_array<f32>';
  49799. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  49800. textureType = 'texture_3d<f32>';
  49801. } else {
  49802. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  49803. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  49804. }
  49805. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  49806. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  49807. const bufferNode = uniform.node;
  49808. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  49809. const bufferCount = bufferNode.bufferCount;
  49810. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  49811. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  49812. if ( this.isCustomStruct( uniform ) ) {
  49813. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  49814. } else {
  49815. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  49816. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  49817. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  49818. }
  49819. } else {
  49820. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  49821. const groupName = uniform.groupNode.name;
  49822. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  49823. index: uniformIndexes.binding ++,
  49824. id: uniformIndexes.group,
  49825. snippets: []
  49826. } );
  49827. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  49828. }
  49829. }
  49830. for ( const name in uniformGroups ) {
  49831. const group = uniformGroups[ name ];
  49832. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  49833. }
  49834. let code = bindingSnippets.join( '\n' );
  49835. code += bufferSnippets.join( '\n' );
  49836. code += structSnippets.join( '\n' );
  49837. return code;
  49838. }
  49839. /**
  49840. * Controls the code build of the shader stages.
  49841. */
  49842. buildCode() {
  49843. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  49844. this.sortBindingGroups();
  49845. for ( const shaderStage in shadersData ) {
  49846. this.shaderStage = shaderStage;
  49847. const stageData = shadersData[ shaderStage ];
  49848. stageData.uniforms = this.getUniforms( shaderStage );
  49849. stageData.attributes = this.getAttributes( shaderStage );
  49850. stageData.varyings = this.getVaryings( shaderStage );
  49851. stageData.structs = this.getStructs( shaderStage );
  49852. stageData.vars = this.getVars( shaderStage );
  49853. stageData.codes = this.getCodes( shaderStage );
  49854. stageData.directives = this.getDirectives( shaderStage );
  49855. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  49856. //
  49857. let flow = '// code\n\n';
  49858. flow += this.flowCode[ shaderStage ];
  49859. const flowNodes = this.flowNodes[ shaderStage ];
  49860. const mainNode = flowNodes[ flowNodes.length - 1 ];
  49861. const outputNode = mainNode.outputNode;
  49862. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  49863. for ( const node of flowNodes ) {
  49864. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  49865. const slotName = node.name;
  49866. if ( slotName ) {
  49867. if ( flow.length > 0 ) flow += '\n';
  49868. flow += `\t// flow -> ${ slotName }\n`;
  49869. }
  49870. flow += `${ flowSlotData.code }\n\t`;
  49871. if ( node === mainNode && shaderStage !== 'compute' ) {
  49872. flow += '// result\n\n\t';
  49873. if ( shaderStage === 'vertex' ) {
  49874. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  49875. } else if ( shaderStage === 'fragment' ) {
  49876. if ( isOutputStruct ) {
  49877. stageData.returnType = outputNode.getNodeType( this );
  49878. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  49879. flow += `return ${ flowSlotData.result };`;
  49880. } else {
  49881. let structSnippet = '\t@location(0) color: vec4<f32>';
  49882. const builtins = this.getBuiltins( 'output' );
  49883. if ( builtins ) structSnippet += ',\n\t' + builtins;
  49884. stageData.returnType = 'OutputStruct';
  49885. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  49886. stageData.structs += '\nvar<private> output : OutputStruct;';
  49887. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  49888. }
  49889. }
  49890. }
  49891. }
  49892. stageData.flow = flow;
  49893. }
  49894. this.shaderStage = null;
  49895. if ( this.material !== null ) {
  49896. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  49897. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  49898. } else {
  49899. // Early strictly validated in computeNode
  49900. const workgroupSize = this.object.workgroupSize;
  49901. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  49902. }
  49903. }
  49904. /**
  49905. * Returns the native shader method name for a given generic name.
  49906. *
  49907. * @param {string} method - The method name to resolve.
  49908. * @param {?string} [output=null] - An optional output.
  49909. * @return {string} The resolved WGSL method name.
  49910. */
  49911. getMethod( method, output = null ) {
  49912. let wgslMethod;
  49913. if ( output !== null ) {
  49914. wgslMethod = this._getWGSLMethod( method + '_' + output );
  49915. }
  49916. if ( wgslMethod === undefined ) {
  49917. wgslMethod = this._getWGSLMethod( method );
  49918. }
  49919. return wgslMethod || method;
  49920. }
  49921. /**
  49922. * Returns the native snippet for a ternary operation.
  49923. *
  49924. * @param {string} condSnippet - The condition determining which expression gets resolved.
  49925. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  49926. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  49927. * @return {string} The resolved method name.
  49928. */
  49929. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  49930. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  49931. }
  49932. /**
  49933. * Returns the WGSL type of the given node data type.
  49934. *
  49935. * @param {string} type - The node data type.
  49936. * @return {string} The WGSL type.
  49937. */
  49938. getType( type ) {
  49939. return wgslTypeLib[ type ] || type;
  49940. }
  49941. /**
  49942. * Whether the requested feature is available or not.
  49943. *
  49944. * @param {string} name - The requested feature.
  49945. * @return {boolean} Whether the requested feature is supported or not.
  49946. */
  49947. isAvailable( name ) {
  49948. let result = supports[ name ];
  49949. if ( result === undefined ) {
  49950. if ( name === 'float32Filterable' ) {
  49951. result = this.renderer.hasFeature( 'float32-filterable' );
  49952. } else if ( name === 'clipDistance' ) {
  49953. result = this.renderer.hasFeature( 'clip-distances' );
  49954. }
  49955. supports[ name ] = result;
  49956. }
  49957. return result;
  49958. }
  49959. /**
  49960. * Returns the native shader method name for a given generic name.
  49961. *
  49962. * @private
  49963. * @param {string} method - The method name to resolve.
  49964. * @return {string} The resolved WGSL method name.
  49965. */
  49966. _getWGSLMethod( method ) {
  49967. if ( wgslPolyfill[ method ] !== undefined ) {
  49968. this._include( method );
  49969. }
  49970. return wgslMethods[ method ];
  49971. }
  49972. /**
  49973. * Includes the given method name into the current
  49974. * function node.
  49975. *
  49976. * @private
  49977. * @param {string} name - The method name to include.
  49978. * @return {CodeNode} The respective code node.
  49979. */
  49980. _include( name ) {
  49981. const codeNode = wgslPolyfill[ name ];
  49982. codeNode.build( this );
  49983. if ( this.currentFunctionNode !== null ) {
  49984. this.currentFunctionNode.includes.push( codeNode );
  49985. }
  49986. return codeNode;
  49987. }
  49988. /**
  49989. * Returns a WGSL vertex shader based on the given shader data.
  49990. *
  49991. * @private
  49992. * @param {Object} shaderData - The shader data.
  49993. * @return {string} The vertex shader.
  49994. */
  49995. _getWGSLVertexCode( shaderData ) {
  49996. return `${ this.getSignature() }
  49997. // directives
  49998. ${shaderData.directives}
  49999. // structs
  50000. ${shaderData.structs}
  50001. // uniforms
  50002. ${shaderData.uniforms}
  50003. // varyings
  50004. ${shaderData.varyings}
  50005. var<private> varyings : VaryingsStruct;
  50006. // codes
  50007. ${shaderData.codes}
  50008. @vertex
  50009. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  50010. // vars
  50011. ${shaderData.vars}
  50012. // flow
  50013. ${shaderData.flow}
  50014. return varyings;
  50015. }
  50016. `;
  50017. }
  50018. /**
  50019. * Returns a WGSL fragment shader based on the given shader data.
  50020. *
  50021. * @private
  50022. * @param {Object} shaderData - The shader data.
  50023. * @return {string} The vertex shader.
  50024. */
  50025. _getWGSLFragmentCode( shaderData ) {
  50026. return `${ this.getSignature() }
  50027. // global
  50028. ${ diagnostics }
  50029. // structs
  50030. ${shaderData.structs}
  50031. // uniforms
  50032. ${shaderData.uniforms}
  50033. // codes
  50034. ${shaderData.codes}
  50035. @fragment
  50036. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  50037. // vars
  50038. ${shaderData.vars}
  50039. // flow
  50040. ${shaderData.flow}
  50041. }
  50042. `;
  50043. }
  50044. /**
  50045. * Returns a WGSL compute shader based on the given shader data.
  50046. *
  50047. * @private
  50048. * @param {Object} shaderData - The shader data.
  50049. * @param {string} workgroupSize - The workgroup size.
  50050. * @return {string} The vertex shader.
  50051. */
  50052. _getWGSLComputeCode( shaderData, workgroupSize ) {
  50053. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  50054. return `${ this.getSignature() }
  50055. // directives
  50056. ${ shaderData.directives }
  50057. // system
  50058. var<private> instanceIndex : u32;
  50059. // locals
  50060. ${ shaderData.scopedArrays }
  50061. // structs
  50062. ${ shaderData.structs }
  50063. // uniforms
  50064. ${ shaderData.uniforms }
  50065. // codes
  50066. ${ shaderData.codes }
  50067. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  50068. fn main( ${ shaderData.attributes } ) {
  50069. // system
  50070. instanceIndex = globalId.x
  50071. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  50072. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  50073. // vars
  50074. ${ shaderData.vars }
  50075. // flow
  50076. ${ shaderData.flow }
  50077. }
  50078. `;
  50079. }
  50080. /**
  50081. * Returns a WGSL struct based on the given name and variables.
  50082. *
  50083. * @private
  50084. * @param {string} name - The struct name.
  50085. * @param {string} vars - The struct variables.
  50086. * @return {string} The WGSL snippet representing a struct.
  50087. */
  50088. _getWGSLStruct( name, vars ) {
  50089. return `
  50090. struct ${name} {
  50091. ${vars}
  50092. };`;
  50093. }
  50094. /**
  50095. * Returns a WGSL struct binding.
  50096. *
  50097. * @private
  50098. * @param {string} name - The struct name.
  50099. * @param {string} vars - The struct variables.
  50100. * @param {string} access - The access.
  50101. * @param {number} [binding=0] - The binding index.
  50102. * @param {number} [group=0] - The group index.
  50103. * @return {string} The WGSL snippet representing a struct binding.
  50104. */
  50105. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  50106. const structName = name + 'Struct';
  50107. const structSnippet = this._getWGSLStruct( structName, vars );
  50108. return `${structSnippet}
  50109. @binding( ${ binding } ) @group( ${ group } )
  50110. var<${access}> ${ name } : ${ structName };`;
  50111. }
  50112. }
  50113. /**
  50114. * A WebGPU backend utility module with common helpers.
  50115. *
  50116. * @private
  50117. */
  50118. class WebGPUUtils {
  50119. /**
  50120. * Constructs a new utility object.
  50121. *
  50122. * @param {WebGPUBackend} backend - The WebGPU backend.
  50123. */
  50124. constructor( backend ) {
  50125. /**
  50126. * A reference to the WebGPU backend.
  50127. *
  50128. * @type {WebGPUBackend}
  50129. */
  50130. this.backend = backend;
  50131. }
  50132. /**
  50133. * Returns the depth/stencil GPU format for the given render context.
  50134. *
  50135. * @param {RenderContext} renderContext - The render context.
  50136. * @return {string} The depth/stencil GPU texture format.
  50137. */
  50138. getCurrentDepthStencilFormat( renderContext ) {
  50139. let format;
  50140. if ( renderContext.depthTexture !== null ) {
  50141. format = this.getTextureFormatGPU( renderContext.depthTexture );
  50142. } else if ( renderContext.depth && renderContext.stencil ) {
  50143. format = GPUTextureFormat.Depth24PlusStencil8;
  50144. } else if ( renderContext.depth ) {
  50145. format = GPUTextureFormat.Depth24Plus;
  50146. }
  50147. return format;
  50148. }
  50149. /**
  50150. * Returns the GPU format for the given texture.
  50151. *
  50152. * @param {Texture} texture - The texture.
  50153. * @return {string} The GPU texture format.
  50154. */
  50155. getTextureFormatGPU( texture ) {
  50156. return this.backend.get( texture ).format;
  50157. }
  50158. /**
  50159. * Returns an object that defines the multi-sampling state of the given texture.
  50160. *
  50161. * @param {Texture} texture - The texture.
  50162. * @return {Object} The multi-sampling state.
  50163. */
  50164. getTextureSampleData( texture ) {
  50165. let samples;
  50166. if ( texture.isFramebufferTexture ) {
  50167. samples = 1;
  50168. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  50169. const renderer = this.backend.renderer;
  50170. const renderTarget = renderer.getRenderTarget();
  50171. samples = renderTarget ? renderTarget.samples : renderer.samples;
  50172. } else if ( texture.renderTarget ) {
  50173. samples = texture.renderTarget.samples;
  50174. }
  50175. samples = samples || 1;
  50176. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  50177. const primarySamples = isMSAA ? 1 : samples;
  50178. return { samples, primarySamples, isMSAA };
  50179. }
  50180. /**
  50181. * Returns the default color attachment's GPU format of the current render context.
  50182. *
  50183. * @param {RenderContext} renderContext - The render context.
  50184. * @return {string} The GPU texture format of the default color attachment.
  50185. */
  50186. getCurrentColorFormat( renderContext ) {
  50187. let format;
  50188. if ( renderContext.textures !== null ) {
  50189. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  50190. } else {
  50191. format = this.getPreferredCanvasFormat(); // default context format
  50192. }
  50193. return format;
  50194. }
  50195. /**
  50196. * Returns the output color space of the current render context.
  50197. *
  50198. * @param {RenderContext} renderContext - The render context.
  50199. * @return {string} The output color space.
  50200. */
  50201. getCurrentColorSpace( renderContext ) {
  50202. if ( renderContext.textures !== null ) {
  50203. return renderContext.textures[ 0 ].colorSpace;
  50204. }
  50205. return this.backend.renderer.outputColorSpace;
  50206. }
  50207. /**
  50208. * Returns GPU primitive topology for the given object and material.
  50209. *
  50210. * @param {Object3D} object - The 3D object.
  50211. * @param {Material} material - The material.
  50212. * @return {string} The GPU primitive topology.
  50213. */
  50214. getPrimitiveTopology( object, material ) {
  50215. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  50216. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  50217. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  50218. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  50219. }
  50220. /**
  50221. * Returns a modified sample count from the given sample count value.
  50222. *
  50223. * That is required since WebGPU only supports either 1 or 4.
  50224. *
  50225. * @param {number} sampleCount - The input sample count.
  50226. * @return {number} The (potentially updated) output sample count.
  50227. */
  50228. getSampleCount( sampleCount ) {
  50229. return sampleCount >= 4 ? 4 : 1;
  50230. }
  50231. /**
  50232. * Returns the sample count of the given render context.
  50233. *
  50234. * @param {RenderContext} renderContext - The render context.
  50235. * @return {number} The sample count.
  50236. */
  50237. getSampleCountRenderContext( renderContext ) {
  50238. if ( renderContext.textures !== null ) {
  50239. return this.getSampleCount( renderContext.sampleCount );
  50240. }
  50241. return this.getSampleCount( this.backend.renderer.samples );
  50242. }
  50243. /**
  50244. * Returns the preferred canvas format.
  50245. *
  50246. * There is a separate method for this so it's possible to
  50247. * honor edge cases for specific devices.
  50248. *
  50249. * @return {string} The GPU texture format of the canvas.
  50250. */
  50251. getPreferredCanvasFormat() {
  50252. const outputType = this.backend.parameters.outputType;
  50253. if ( outputType === undefined ) {
  50254. return navigator.gpu.getPreferredCanvasFormat();
  50255. } else if ( outputType === UnsignedByteType ) {
  50256. return GPUTextureFormat.BGRA8Unorm;
  50257. } else if ( outputType === HalfFloatType ) {
  50258. return GPUTextureFormat.RGBA16Float;
  50259. } else {
  50260. throw new Error( 'Unsupported outputType' );
  50261. }
  50262. }
  50263. }
  50264. const typedArraysToVertexFormatPrefix = new Map( [
  50265. [ Int8Array, [ 'sint8', 'snorm8' ]],
  50266. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  50267. [ Int16Array, [ 'sint16', 'snorm16' ]],
  50268. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  50269. [ Int32Array, [ 'sint32', 'snorm32' ]],
  50270. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  50271. [ Float32Array, [ 'float32', ]],
  50272. ] );
  50273. if ( typeof Float16Array !== 'undefined' ) {
  50274. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  50275. }
  50276. const typedAttributeToVertexFormatPrefix = new Map( [
  50277. [ Float16BufferAttribute, [ 'float16', ]],
  50278. ] );
  50279. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  50280. [ Int32Array, 'sint32' ],
  50281. [ Int16Array, 'sint32' ], // patch for INT16
  50282. [ Uint32Array, 'uint32' ],
  50283. [ Uint16Array, 'uint32' ], // patch for UINT16
  50284. [ Float32Array, 'float32' ]
  50285. ] );
  50286. /**
  50287. * A WebGPU backend utility module for managing shader attributes.
  50288. *
  50289. * @private
  50290. */
  50291. class WebGPUAttributeUtils {
  50292. /**
  50293. * Constructs a new utility object.
  50294. *
  50295. * @param {WebGPUBackend} backend - The WebGPU backend.
  50296. */
  50297. constructor( backend ) {
  50298. /**
  50299. * A reference to the WebGPU backend.
  50300. *
  50301. * @type {WebGPUBackend}
  50302. */
  50303. this.backend = backend;
  50304. }
  50305. /**
  50306. * Creates the GPU buffer for the given buffer attribute.
  50307. *
  50308. * @param {BufferAttribute} attribute - The buffer attribute.
  50309. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  50310. */
  50311. createAttribute( attribute, usage ) {
  50312. const bufferAttribute = this._getBufferAttribute( attribute );
  50313. const backend = this.backend;
  50314. const bufferData = backend.get( bufferAttribute );
  50315. let buffer = bufferData.buffer;
  50316. if ( buffer === undefined ) {
  50317. const device = backend.device;
  50318. let array = bufferAttribute.array;
  50319. // patch for INT16 and UINT16
  50320. if ( attribute.normalized === false ) {
  50321. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  50322. array = new Int32Array( array );
  50323. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  50324. array = new Uint32Array( array );
  50325. if ( usage & GPUBufferUsage.INDEX ) {
  50326. for ( let i = 0; i < array.length; i ++ ) {
  50327. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  50328. }
  50329. }
  50330. }
  50331. }
  50332. bufferAttribute.array = array;
  50333. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  50334. array = new array.constructor( bufferAttribute.count * 4 );
  50335. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  50336. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  50337. }
  50338. // Update BufferAttribute
  50339. bufferAttribute.itemSize = 4;
  50340. bufferAttribute.array = array;
  50341. bufferData._force3to4BytesAlignment = true;
  50342. }
  50343. // ensure 4 byte alignment
  50344. const byteLength = array.byteLength;
  50345. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  50346. buffer = device.createBuffer( {
  50347. label: bufferAttribute.name,
  50348. size: size,
  50349. usage: usage,
  50350. mappedAtCreation: true
  50351. } );
  50352. new array.constructor( buffer.getMappedRange() ).set( array );
  50353. buffer.unmap();
  50354. bufferData.buffer = buffer;
  50355. }
  50356. }
  50357. /**
  50358. * Updates the GPU buffer of the given buffer attribute.
  50359. *
  50360. * @param {BufferAttribute} attribute - The buffer attribute.
  50361. */
  50362. updateAttribute( attribute ) {
  50363. const bufferAttribute = this._getBufferAttribute( attribute );
  50364. const backend = this.backend;
  50365. const device = backend.device;
  50366. const bufferData = backend.get( bufferAttribute );
  50367. const buffer = backend.get( bufferAttribute ).buffer;
  50368. let array = bufferAttribute.array;
  50369. // if storage buffer ensure 4 byte alignment
  50370. if ( bufferData._force3to4BytesAlignment === true ) {
  50371. array = new array.constructor( bufferAttribute.count * 4 );
  50372. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  50373. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  50374. }
  50375. bufferAttribute.array = array;
  50376. }
  50377. const isTypedArray = this._isTypedArray( array );
  50378. const updateRanges = bufferAttribute.updateRanges;
  50379. if ( updateRanges.length === 0 ) {
  50380. // Not using update ranges
  50381. device.queue.writeBuffer(
  50382. buffer,
  50383. 0,
  50384. array,
  50385. 0
  50386. );
  50387. } else {
  50388. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  50389. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  50390. const range = updateRanges[ i ];
  50391. let dataOffset, size;
  50392. if ( bufferData._force3to4BytesAlignment === true ) {
  50393. const vertexStart = Math.floor( range.start / 3 );
  50394. const vertexCount = Math.ceil( range.count / 3 );
  50395. dataOffset = vertexStart * 4 * byteOffsetFactor;
  50396. size = vertexCount * 4 * byteOffsetFactor;
  50397. } else {
  50398. dataOffset = range.start * byteOffsetFactor;
  50399. size = range.count * byteOffsetFactor;
  50400. }
  50401. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  50402. device.queue.writeBuffer(
  50403. buffer,
  50404. bufferOffset,
  50405. array,
  50406. dataOffset,
  50407. size
  50408. );
  50409. }
  50410. bufferAttribute.clearUpdateRanges();
  50411. }
  50412. }
  50413. /**
  50414. * This method creates the vertex buffer layout data which are
  50415. * require when creating a render pipeline for the given render object.
  50416. *
  50417. * @param {RenderObject} renderObject - The render object.
  50418. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  50419. */
  50420. createShaderVertexBuffers( renderObject ) {
  50421. const attributes = renderObject.getAttributes();
  50422. const vertexBuffers = new Map();
  50423. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  50424. const geometryAttribute = attributes[ slot ];
  50425. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  50426. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  50427. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  50428. if ( vertexBufferLayout === undefined ) {
  50429. let arrayStride, stepMode;
  50430. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  50431. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  50432. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  50433. } else {
  50434. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  50435. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  50436. }
  50437. // patch for INT16 and UINT16
  50438. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  50439. arrayStride = 4;
  50440. }
  50441. vertexBufferLayout = {
  50442. arrayStride,
  50443. attributes: [],
  50444. stepMode
  50445. };
  50446. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  50447. }
  50448. const format = this._getVertexFormat( geometryAttribute );
  50449. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  50450. vertexBufferLayout.attributes.push( {
  50451. shaderLocation: slot,
  50452. offset,
  50453. format
  50454. } );
  50455. }
  50456. return Array.from( vertexBuffers.values() );
  50457. }
  50458. /**
  50459. * Destroys the GPU buffer of the given buffer attribute.
  50460. *
  50461. * @param {BufferAttribute} attribute - The buffer attribute.
  50462. */
  50463. destroyAttribute( attribute ) {
  50464. const backend = this.backend;
  50465. const data = backend.get( this._getBufferAttribute( attribute ) );
  50466. data.buffer.destroy();
  50467. backend.delete( attribute );
  50468. }
  50469. /**
  50470. * This method performs a readback operation by moving buffer data from
  50471. * a storage buffer attribute from the GPU to the CPU.
  50472. *
  50473. * @async
  50474. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  50475. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  50476. */
  50477. async getArrayBufferAsync( attribute ) {
  50478. const backend = this.backend;
  50479. const device = backend.device;
  50480. const data = backend.get( this._getBufferAttribute( attribute ) );
  50481. const bufferGPU = data.buffer;
  50482. const size = bufferGPU.size;
  50483. const readBufferGPU = device.createBuffer( {
  50484. label: `${ attribute.name }_readback`,
  50485. size,
  50486. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50487. } );
  50488. const cmdEncoder = device.createCommandEncoder( {
  50489. label: `readback_encoder_${ attribute.name }`
  50490. } );
  50491. cmdEncoder.copyBufferToBuffer(
  50492. bufferGPU,
  50493. 0,
  50494. readBufferGPU,
  50495. 0,
  50496. size
  50497. );
  50498. const gpuCommands = cmdEncoder.finish();
  50499. device.queue.submit( [ gpuCommands ] );
  50500. await readBufferGPU.mapAsync( GPUMapMode.READ );
  50501. const arrayBuffer = readBufferGPU.getMappedRange();
  50502. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  50503. readBufferGPU.unmap();
  50504. return dstBuffer.buffer;
  50505. }
  50506. /**
  50507. * Returns the vertex format of the given buffer attribute.
  50508. *
  50509. * @private
  50510. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  50511. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  50512. */
  50513. _getVertexFormat( geometryAttribute ) {
  50514. const { itemSize, normalized } = geometryAttribute;
  50515. const ArrayType = geometryAttribute.array.constructor;
  50516. const AttributeType = geometryAttribute.constructor;
  50517. let format;
  50518. if ( itemSize === 1 ) {
  50519. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  50520. } else {
  50521. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  50522. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  50523. if ( prefix ) {
  50524. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  50525. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  50526. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  50527. if ( paddedItemSize % 1 ) {
  50528. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  50529. }
  50530. format = `${prefix}x${paddedItemSize}`;
  50531. }
  50532. }
  50533. if ( ! format ) {
  50534. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  50535. }
  50536. return format;
  50537. }
  50538. /**
  50539. * Returns `true` if the given array is a typed array.
  50540. *
  50541. * @private
  50542. * @param {any} array - The array.
  50543. * @return {boolean} Whether the given array is a typed array or not.
  50544. */
  50545. _isTypedArray( array ) {
  50546. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  50547. }
  50548. /**
  50549. * Utility method for handling interleaved buffer attributes correctly.
  50550. * To process them, their `InterleavedBuffer` is returned.
  50551. *
  50552. * @private
  50553. * @param {BufferAttribute} attribute - The attribute.
  50554. * @return {BufferAttribute|InterleavedBuffer}
  50555. */
  50556. _getBufferAttribute( attribute ) {
  50557. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  50558. return attribute;
  50559. }
  50560. }
  50561. /**
  50562. * A WebGPU backend utility module for managing bindings.
  50563. *
  50564. * When reading the documentation it's helpful to keep in mind that
  50565. * all class definitions starting with 'GPU*' are modules from the
  50566. * WebGPU API. So for example `BindGroup` is a class from the engine
  50567. * whereas `GPUBindGroup` is a class from WebGPU.
  50568. *
  50569. * @private
  50570. */
  50571. class WebGPUBindingUtils {
  50572. /**
  50573. * Constructs a new utility object.
  50574. *
  50575. * @param {WebGPUBackend} backend - The WebGPU backend.
  50576. */
  50577. constructor( backend ) {
  50578. /**
  50579. * A reference to the WebGPU backend.
  50580. *
  50581. * @type {WebGPUBackend}
  50582. */
  50583. this.backend = backend;
  50584. /**
  50585. * A cache for managing bind group layouts.
  50586. *
  50587. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  50588. */
  50589. this.bindGroupLayoutCache = new WeakMap();
  50590. }
  50591. /**
  50592. * Creates a GPU bind group layout for the given bind group.
  50593. *
  50594. * @param {BindGroup} bindGroup - The bind group.
  50595. * @return {GPUBindGroupLayout} The GPU bind group layout.
  50596. */
  50597. createBindingsLayout( bindGroup ) {
  50598. const backend = this.backend;
  50599. const device = backend.device;
  50600. const entries = [];
  50601. let index = 0;
  50602. for ( const binding of bindGroup.bindings ) {
  50603. const bindingGPU = {
  50604. binding: index ++,
  50605. visibility: binding.visibility
  50606. };
  50607. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  50608. const buffer = {}; // GPUBufferBindingLayout
  50609. if ( binding.isStorageBuffer ) {
  50610. if ( binding.visibility & 4 ) {
  50611. // compute
  50612. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  50613. buffer.type = GPUBufferBindingType.Storage;
  50614. } else {
  50615. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  50616. }
  50617. } else {
  50618. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  50619. }
  50620. }
  50621. bindingGPU.buffer = buffer;
  50622. } else if ( binding.isSampledTexture && binding.store ) {
  50623. const storageTexture = {}; // GPUStorageTextureBindingLayout
  50624. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  50625. const access = binding.access;
  50626. if ( access === NodeAccess.READ_WRITE ) {
  50627. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  50628. } else if ( access === NodeAccess.WRITE_ONLY ) {
  50629. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  50630. } else {
  50631. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  50632. }
  50633. if ( binding.texture.isArrayTexture ) {
  50634. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  50635. } else if ( binding.texture.is3DTexture ) {
  50636. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  50637. }
  50638. bindingGPU.storageTexture = storageTexture;
  50639. } else if ( binding.isSampledTexture ) {
  50640. const texture = {}; // GPUTextureBindingLayout
  50641. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  50642. if ( primarySamples > 1 ) {
  50643. texture.multisampled = true;
  50644. if ( ! binding.texture.isDepthTexture ) {
  50645. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  50646. }
  50647. }
  50648. if ( binding.texture.isDepthTexture ) {
  50649. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  50650. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  50651. } else {
  50652. texture.sampleType = GPUTextureSampleType.Depth;
  50653. }
  50654. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  50655. const type = binding.texture.type;
  50656. if ( type === IntType ) {
  50657. texture.sampleType = GPUTextureSampleType.SInt;
  50658. } else if ( type === UnsignedIntType ) {
  50659. texture.sampleType = GPUTextureSampleType.UInt;
  50660. } else if ( type === FloatType ) {
  50661. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  50662. texture.sampleType = GPUTextureSampleType.Float;
  50663. } else {
  50664. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  50665. }
  50666. }
  50667. }
  50668. if ( binding.isSampledCubeTexture ) {
  50669. texture.viewDimension = GPUTextureViewDimension.Cube;
  50670. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  50671. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  50672. } else if ( binding.isSampledTexture3D ) {
  50673. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  50674. }
  50675. bindingGPU.texture = texture;
  50676. } else if ( binding.isSampler ) {
  50677. const sampler = {}; // GPUSamplerBindingLayout
  50678. if ( binding.texture.isDepthTexture ) {
  50679. if ( binding.texture.compareFunction !== null ) {
  50680. sampler.type = GPUSamplerBindingType.Comparison;
  50681. } else if ( backend.compatibilityMode ) {
  50682. sampler.type = GPUSamplerBindingType.NonFiltering;
  50683. }
  50684. }
  50685. bindingGPU.sampler = sampler;
  50686. } else {
  50687. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  50688. }
  50689. entries.push( bindingGPU );
  50690. }
  50691. return device.createBindGroupLayout( { entries } );
  50692. }
  50693. /**
  50694. * Creates bindings from the given bind group definition.
  50695. *
  50696. * @param {BindGroup} bindGroup - The bind group.
  50697. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50698. * @param {number} cacheIndex - The cache index.
  50699. * @param {number} version - The version.
  50700. */
  50701. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  50702. const { backend, bindGroupLayoutCache } = this;
  50703. const bindingsData = backend.get( bindGroup );
  50704. // setup (static) binding layout and (dynamic) binding group
  50705. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  50706. if ( bindLayoutGPU === undefined ) {
  50707. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  50708. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  50709. }
  50710. let bindGroupGPU;
  50711. if ( cacheIndex > 0 ) {
  50712. if ( bindingsData.groups === undefined ) {
  50713. bindingsData.groups = [];
  50714. bindingsData.versions = [];
  50715. }
  50716. if ( bindingsData.versions[ cacheIndex ] === version ) {
  50717. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  50718. }
  50719. }
  50720. if ( bindGroupGPU === undefined ) {
  50721. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  50722. if ( cacheIndex > 0 ) {
  50723. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  50724. bindingsData.versions[ cacheIndex ] = version;
  50725. }
  50726. }
  50727. bindingsData.group = bindGroupGPU;
  50728. bindingsData.layout = bindLayoutGPU;
  50729. }
  50730. /**
  50731. * Updates a buffer binding.
  50732. *
  50733. * @param {Buffer} binding - The buffer binding to update.
  50734. */
  50735. updateBinding( binding ) {
  50736. const backend = this.backend;
  50737. const device = backend.device;
  50738. const buffer = binding.buffer;
  50739. const bufferGPU = backend.get( binding ).buffer;
  50740. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  50741. }
  50742. /**
  50743. * Creates a GPU bind group for the camera index.
  50744. *
  50745. * @param {Uint32Array} data - The index data.
  50746. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  50747. * @return {GPUBindGroup} The GPU bind group.
  50748. */
  50749. createBindGroupIndex( data, layout ) {
  50750. const backend = this.backend;
  50751. const device = backend.device;
  50752. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  50753. const index = data[ 0 ];
  50754. const buffer = device.createBuffer( {
  50755. label: 'bindingCameraIndex_' + index,
  50756. size: 16, // uint(4) * 4
  50757. usage: usage
  50758. } );
  50759. device.queue.writeBuffer( buffer, 0, data, 0 );
  50760. const entries = [ { binding: 0, resource: { buffer } } ];
  50761. return device.createBindGroup( {
  50762. label: 'bindGroupCameraIndex_' + index,
  50763. layout,
  50764. entries
  50765. } );
  50766. }
  50767. /**
  50768. * Creates a GPU bind group for the given bind group and GPU layout.
  50769. *
  50770. * @param {BindGroup} bindGroup - The bind group.
  50771. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  50772. * @return {GPUBindGroup} The GPU bind group.
  50773. */
  50774. createBindGroup( bindGroup, layoutGPU ) {
  50775. const backend = this.backend;
  50776. const device = backend.device;
  50777. let bindingPoint = 0;
  50778. const entriesGPU = [];
  50779. for ( const binding of bindGroup.bindings ) {
  50780. if ( binding.isUniformBuffer ) {
  50781. const bindingData = backend.get( binding );
  50782. if ( bindingData.buffer === undefined ) {
  50783. const byteLength = binding.byteLength;
  50784. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  50785. const bufferGPU = device.createBuffer( {
  50786. label: 'bindingBuffer_' + binding.name,
  50787. size: byteLength,
  50788. usage: usage
  50789. } );
  50790. bindingData.buffer = bufferGPU;
  50791. }
  50792. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  50793. } else if ( binding.isStorageBuffer ) {
  50794. const bindingData = backend.get( binding );
  50795. if ( bindingData.buffer === undefined ) {
  50796. const attribute = binding.attribute;
  50797. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  50798. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  50799. bindingData.buffer = backend.get( attribute ).buffer;
  50800. }
  50801. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  50802. } else if ( binding.isSampledTexture ) {
  50803. const textureData = backend.get( binding.texture );
  50804. let resourceGPU;
  50805. if ( textureData.externalTexture !== undefined ) {
  50806. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  50807. } else {
  50808. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  50809. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  50810. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  50811. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  50812. }
  50813. propertyName += `-${ mipLevelCount }`;
  50814. resourceGPU = textureData[ propertyName ];
  50815. if ( resourceGPU === undefined ) {
  50816. const aspectGPU = GPUTextureAspect.All;
  50817. let dimensionViewGPU;
  50818. if ( binding.isSampledCubeTexture ) {
  50819. dimensionViewGPU = GPUTextureViewDimension.Cube;
  50820. } else if ( binding.isSampledTexture3D ) {
  50821. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  50822. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  50823. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  50824. } else {
  50825. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  50826. }
  50827. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  50828. }
  50829. }
  50830. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  50831. } else if ( binding.isSampler ) {
  50832. const textureGPU = backend.get( binding.texture );
  50833. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  50834. }
  50835. bindingPoint ++;
  50836. }
  50837. return device.createBindGroup( {
  50838. label: 'bindGroup_' + bindGroup.name,
  50839. layout: layoutGPU,
  50840. entries: entriesGPU
  50841. } );
  50842. }
  50843. }
  50844. /**
  50845. * A WebGPU backend utility module for managing pipelines.
  50846. *
  50847. * @private
  50848. */
  50849. class WebGPUPipelineUtils {
  50850. /**
  50851. * Constructs a new utility object.
  50852. *
  50853. * @param {WebGPUBackend} backend - The WebGPU backend.
  50854. */
  50855. constructor( backend ) {
  50856. /**
  50857. * A reference to the WebGPU backend.
  50858. *
  50859. * @type {WebGPUBackend}
  50860. */
  50861. this.backend = backend;
  50862. /**
  50863. * A Weak Map that tracks the active pipeline for render or compute passes.
  50864. *
  50865. * @private
  50866. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  50867. */
  50868. this._activePipelines = new WeakMap();
  50869. }
  50870. /**
  50871. * Sets the given pipeline for the given pass. The method makes sure to only set the
  50872. * pipeline when necessary.
  50873. *
  50874. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  50875. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  50876. */
  50877. setPipeline( pass, pipeline ) {
  50878. const currentPipeline = this._activePipelines.get( pass );
  50879. if ( currentPipeline !== pipeline ) {
  50880. pass.setPipeline( pipeline );
  50881. this._activePipelines.set( pass, pipeline );
  50882. }
  50883. }
  50884. /**
  50885. * Returns the sample count derived from the given render context.
  50886. *
  50887. * @private
  50888. * @param {RenderContext} renderContext - The render context.
  50889. * @return {number} The sample count.
  50890. */
  50891. _getSampleCount( renderContext ) {
  50892. return this.backend.utils.getSampleCountRenderContext( renderContext );
  50893. }
  50894. /**
  50895. * Creates a render pipeline for the given render object.
  50896. *
  50897. * @param {RenderObject} renderObject - The render object.
  50898. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  50899. */
  50900. createRenderPipeline( renderObject, promises ) {
  50901. const { object, material, geometry, pipeline } = renderObject;
  50902. const { vertexProgram, fragmentProgram } = pipeline;
  50903. const backend = this.backend;
  50904. const device = backend.device;
  50905. const utils = backend.utils;
  50906. const pipelineData = backend.get( pipeline );
  50907. // bind group layouts
  50908. const bindGroupLayouts = [];
  50909. for ( const bindGroup of renderObject.getBindings() ) {
  50910. const bindingsData = backend.get( bindGroup );
  50911. bindGroupLayouts.push( bindingsData.layout );
  50912. }
  50913. // vertex buffers
  50914. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  50915. // blending
  50916. let blending;
  50917. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  50918. blending = this._getBlending( material );
  50919. }
  50920. // stencil
  50921. let stencilFront = {};
  50922. if ( material.stencilWrite === true ) {
  50923. stencilFront = {
  50924. compare: this._getStencilCompare( material ),
  50925. failOp: this._getStencilOperation( material.stencilFail ),
  50926. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  50927. passOp: this._getStencilOperation( material.stencilZPass )
  50928. };
  50929. }
  50930. const colorWriteMask = this._getColorWriteMask( material );
  50931. const targets = [];
  50932. if ( renderObject.context.textures !== null ) {
  50933. const textures = renderObject.context.textures;
  50934. for ( let i = 0; i < textures.length; i ++ ) {
  50935. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  50936. targets.push( {
  50937. format: colorFormat,
  50938. blend: blending,
  50939. writeMask: colorWriteMask
  50940. } );
  50941. }
  50942. } else {
  50943. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  50944. targets.push( {
  50945. format: colorFormat,
  50946. blend: blending,
  50947. writeMask: colorWriteMask
  50948. } );
  50949. }
  50950. const vertexModule = backend.get( vertexProgram ).module;
  50951. const fragmentModule = backend.get( fragmentProgram ).module;
  50952. const primitiveState = this._getPrimitiveState( object, geometry, material );
  50953. const depthCompare = this._getDepthCompare( material );
  50954. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  50955. const sampleCount = this._getSampleCount( renderObject.context );
  50956. const pipelineDescriptor = {
  50957. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  50958. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  50959. fragment: Object.assign( {}, fragmentModule, { targets } ),
  50960. primitive: primitiveState,
  50961. multisample: {
  50962. count: sampleCount,
  50963. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  50964. },
  50965. layout: device.createPipelineLayout( {
  50966. bindGroupLayouts
  50967. } )
  50968. };
  50969. const depthStencil = {};
  50970. const renderDepth = renderObject.context.depth;
  50971. const renderStencil = renderObject.context.stencil;
  50972. if ( renderDepth === true || renderStencil === true ) {
  50973. if ( renderDepth === true ) {
  50974. depthStencil.format = depthStencilFormat;
  50975. depthStencil.depthWriteEnabled = material.depthWrite;
  50976. depthStencil.depthCompare = depthCompare;
  50977. }
  50978. if ( renderStencil === true ) {
  50979. depthStencil.stencilFront = stencilFront;
  50980. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  50981. depthStencil.stencilReadMask = material.stencilFuncMask;
  50982. depthStencil.stencilWriteMask = material.stencilWriteMask;
  50983. }
  50984. if ( material.polygonOffset === true ) {
  50985. depthStencil.depthBias = material.polygonOffsetUnits;
  50986. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  50987. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  50988. }
  50989. pipelineDescriptor.depthStencil = depthStencil;
  50990. }
  50991. if ( promises === null ) {
  50992. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  50993. } else {
  50994. const p = new Promise( ( resolve /*, reject*/ ) => {
  50995. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  50996. pipelineData.pipeline = pipeline;
  50997. resolve();
  50998. } );
  50999. } );
  51000. promises.push( p );
  51001. }
  51002. }
  51003. /**
  51004. * Creates GPU render bundle encoder for the given render context.
  51005. *
  51006. * @param {RenderContext} renderContext - The render context.
  51007. * @param {?string} [label='renderBundleEncoder'] - The label.
  51008. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  51009. */
  51010. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  51011. const backend = this.backend;
  51012. const { utils, device } = backend;
  51013. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  51014. const colorFormat = utils.getCurrentColorFormat( renderContext );
  51015. const sampleCount = this._getSampleCount( renderContext );
  51016. const descriptor = {
  51017. label: label,
  51018. colorFormats: [ colorFormat ],
  51019. depthStencilFormat,
  51020. sampleCount
  51021. };
  51022. return device.createRenderBundleEncoder( descriptor );
  51023. }
  51024. /**
  51025. * Creates a compute pipeline for the given compute node.
  51026. *
  51027. * @param {ComputePipeline} pipeline - The compute pipeline.
  51028. * @param {Array<BindGroup>} bindings - The bindings.
  51029. */
  51030. createComputePipeline( pipeline, bindings ) {
  51031. const backend = this.backend;
  51032. const device = backend.device;
  51033. const computeProgram = backend.get( pipeline.computeProgram ).module;
  51034. const pipelineGPU = backend.get( pipeline );
  51035. // bind group layouts
  51036. const bindGroupLayouts = [];
  51037. for ( const bindingsGroup of bindings ) {
  51038. const bindingsData = backend.get( bindingsGroup );
  51039. bindGroupLayouts.push( bindingsData.layout );
  51040. }
  51041. pipelineGPU.pipeline = device.createComputePipeline( {
  51042. compute: computeProgram,
  51043. layout: device.createPipelineLayout( {
  51044. bindGroupLayouts
  51045. } )
  51046. } );
  51047. }
  51048. /**
  51049. * Returns the blending state as a descriptor object required
  51050. * for the pipeline creation.
  51051. *
  51052. * @private
  51053. * @param {Material} material - The material.
  51054. * @return {Object} The blending state.
  51055. */
  51056. _getBlending( material ) {
  51057. let color, alpha;
  51058. const blending = material.blending;
  51059. const blendSrc = material.blendSrc;
  51060. const blendDst = material.blendDst;
  51061. const blendEquation = material.blendEquation;
  51062. if ( blending === CustomBlending ) {
  51063. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  51064. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  51065. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  51066. color = {
  51067. srcFactor: this._getBlendFactor( blendSrc ),
  51068. dstFactor: this._getBlendFactor( blendDst ),
  51069. operation: this._getBlendOperation( blendEquation )
  51070. };
  51071. alpha = {
  51072. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  51073. dstFactor: this._getBlendFactor( blendDstAlpha ),
  51074. operation: this._getBlendOperation( blendEquationAlpha )
  51075. };
  51076. } else {
  51077. const premultipliedAlpha = material.premultipliedAlpha;
  51078. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  51079. color = {
  51080. srcFactor: srcRGB,
  51081. dstFactor: dstRGB,
  51082. operation: GPUBlendOperation.Add
  51083. };
  51084. alpha = {
  51085. srcFactor: srcAlpha,
  51086. dstFactor: dstAlpha,
  51087. operation: GPUBlendOperation.Add
  51088. };
  51089. };
  51090. if ( premultipliedAlpha ) {
  51091. switch ( blending ) {
  51092. case NormalBlending:
  51093. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  51094. break;
  51095. case AdditiveBlending:
  51096. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  51097. break;
  51098. case SubtractiveBlending:
  51099. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  51100. break;
  51101. case MultiplyBlending:
  51102. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  51103. break;
  51104. }
  51105. } else {
  51106. switch ( blending ) {
  51107. case NormalBlending:
  51108. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  51109. break;
  51110. case AdditiveBlending:
  51111. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  51112. break;
  51113. case SubtractiveBlending:
  51114. console.error( 'THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  51115. break;
  51116. case MultiplyBlending:
  51117. console.error( 'THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  51118. break;
  51119. }
  51120. }
  51121. }
  51122. if ( color !== undefined && alpha !== undefined ) {
  51123. return { color, alpha };
  51124. } else {
  51125. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  51126. }
  51127. }
  51128. /**
  51129. * Returns the GPU blend factor which is required for the pipeline creation.
  51130. *
  51131. * @private
  51132. * @param {number} blend - The blend factor as a three.js constant.
  51133. * @return {string} The GPU blend factor.
  51134. */
  51135. _getBlendFactor( blend ) {
  51136. let blendFactor;
  51137. switch ( blend ) {
  51138. case ZeroFactor:
  51139. blendFactor = GPUBlendFactor.Zero;
  51140. break;
  51141. case OneFactor:
  51142. blendFactor = GPUBlendFactor.One;
  51143. break;
  51144. case SrcColorFactor:
  51145. blendFactor = GPUBlendFactor.Src;
  51146. break;
  51147. case OneMinusSrcColorFactor:
  51148. blendFactor = GPUBlendFactor.OneMinusSrc;
  51149. break;
  51150. case SrcAlphaFactor:
  51151. blendFactor = GPUBlendFactor.SrcAlpha;
  51152. break;
  51153. case OneMinusSrcAlphaFactor:
  51154. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  51155. break;
  51156. case DstColorFactor:
  51157. blendFactor = GPUBlendFactor.Dst;
  51158. break;
  51159. case OneMinusDstColorFactor:
  51160. blendFactor = GPUBlendFactor.OneMinusDst;
  51161. break;
  51162. case DstAlphaFactor:
  51163. blendFactor = GPUBlendFactor.DstAlpha;
  51164. break;
  51165. case OneMinusDstAlphaFactor:
  51166. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  51167. break;
  51168. case SrcAlphaSaturateFactor:
  51169. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  51170. break;
  51171. case BlendColorFactor:
  51172. blendFactor = GPUBlendFactor.Constant;
  51173. break;
  51174. case OneMinusBlendColorFactor:
  51175. blendFactor = GPUBlendFactor.OneMinusConstant;
  51176. break;
  51177. default:
  51178. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  51179. }
  51180. return blendFactor;
  51181. }
  51182. /**
  51183. * Returns the GPU stencil compare function which is required for the pipeline creation.
  51184. *
  51185. * @private
  51186. * @param {Material} material - The material.
  51187. * @return {string} The GPU stencil compare function.
  51188. */
  51189. _getStencilCompare( material ) {
  51190. let stencilCompare;
  51191. const stencilFunc = material.stencilFunc;
  51192. switch ( stencilFunc ) {
  51193. case NeverStencilFunc:
  51194. stencilCompare = GPUCompareFunction.Never;
  51195. break;
  51196. case AlwaysStencilFunc:
  51197. stencilCompare = GPUCompareFunction.Always;
  51198. break;
  51199. case LessStencilFunc:
  51200. stencilCompare = GPUCompareFunction.Less;
  51201. break;
  51202. case LessEqualStencilFunc:
  51203. stencilCompare = GPUCompareFunction.LessEqual;
  51204. break;
  51205. case EqualStencilFunc:
  51206. stencilCompare = GPUCompareFunction.Equal;
  51207. break;
  51208. case GreaterEqualStencilFunc:
  51209. stencilCompare = GPUCompareFunction.GreaterEqual;
  51210. break;
  51211. case GreaterStencilFunc:
  51212. stencilCompare = GPUCompareFunction.Greater;
  51213. break;
  51214. case NotEqualStencilFunc:
  51215. stencilCompare = GPUCompareFunction.NotEqual;
  51216. break;
  51217. default:
  51218. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  51219. }
  51220. return stencilCompare;
  51221. }
  51222. /**
  51223. * Returns the GPU stencil operation which is required for the pipeline creation.
  51224. *
  51225. * @private
  51226. * @param {number} op - A three.js constant defining the stencil operation.
  51227. * @return {string} The GPU stencil operation.
  51228. */
  51229. _getStencilOperation( op ) {
  51230. let stencilOperation;
  51231. switch ( op ) {
  51232. case KeepStencilOp:
  51233. stencilOperation = GPUStencilOperation.Keep;
  51234. break;
  51235. case ZeroStencilOp:
  51236. stencilOperation = GPUStencilOperation.Zero;
  51237. break;
  51238. case ReplaceStencilOp:
  51239. stencilOperation = GPUStencilOperation.Replace;
  51240. break;
  51241. case InvertStencilOp:
  51242. stencilOperation = GPUStencilOperation.Invert;
  51243. break;
  51244. case IncrementStencilOp:
  51245. stencilOperation = GPUStencilOperation.IncrementClamp;
  51246. break;
  51247. case DecrementStencilOp:
  51248. stencilOperation = GPUStencilOperation.DecrementClamp;
  51249. break;
  51250. case IncrementWrapStencilOp:
  51251. stencilOperation = GPUStencilOperation.IncrementWrap;
  51252. break;
  51253. case DecrementWrapStencilOp:
  51254. stencilOperation = GPUStencilOperation.DecrementWrap;
  51255. break;
  51256. default:
  51257. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  51258. }
  51259. return stencilOperation;
  51260. }
  51261. /**
  51262. * Returns the GPU blend operation which is required for the pipeline creation.
  51263. *
  51264. * @private
  51265. * @param {number} blendEquation - A three.js constant defining the blend equation.
  51266. * @return {string} The GPU blend operation.
  51267. */
  51268. _getBlendOperation( blendEquation ) {
  51269. let blendOperation;
  51270. switch ( blendEquation ) {
  51271. case AddEquation:
  51272. blendOperation = GPUBlendOperation.Add;
  51273. break;
  51274. case SubtractEquation:
  51275. blendOperation = GPUBlendOperation.Subtract;
  51276. break;
  51277. case ReverseSubtractEquation:
  51278. blendOperation = GPUBlendOperation.ReverseSubtract;
  51279. break;
  51280. case MinEquation:
  51281. blendOperation = GPUBlendOperation.Min;
  51282. break;
  51283. case MaxEquation:
  51284. blendOperation = GPUBlendOperation.Max;
  51285. break;
  51286. default:
  51287. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  51288. }
  51289. return blendOperation;
  51290. }
  51291. /**
  51292. * Returns the primitive state as a descriptor object required
  51293. * for the pipeline creation.
  51294. *
  51295. * @private
  51296. * @param {Object3D} object - The 3D object.
  51297. * @param {BufferGeometry} geometry - The geometry.
  51298. * @param {Material} material - The material.
  51299. * @return {Object} The primitive state.
  51300. */
  51301. _getPrimitiveState( object, geometry, material ) {
  51302. const descriptor = {};
  51303. const utils = this.backend.utils;
  51304. descriptor.topology = utils.getPrimitiveTopology( object, material );
  51305. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  51306. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  51307. }
  51308. switch ( material.side ) {
  51309. case FrontSide:
  51310. descriptor.frontFace = GPUFrontFace.CCW;
  51311. descriptor.cullMode = GPUCullMode.Back;
  51312. break;
  51313. case BackSide:
  51314. descriptor.frontFace = GPUFrontFace.CCW;
  51315. descriptor.cullMode = GPUCullMode.Front;
  51316. break;
  51317. case DoubleSide:
  51318. descriptor.frontFace = GPUFrontFace.CCW;
  51319. descriptor.cullMode = GPUCullMode.None;
  51320. break;
  51321. default:
  51322. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  51323. break;
  51324. }
  51325. return descriptor;
  51326. }
  51327. /**
  51328. * Returns the GPU color write mask which is required for the pipeline creation.
  51329. *
  51330. * @private
  51331. * @param {Material} material - The material.
  51332. * @return {number} The GPU color write mask.
  51333. */
  51334. _getColorWriteMask( material ) {
  51335. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  51336. }
  51337. /**
  51338. * Returns the GPU depth compare function which is required for the pipeline creation.
  51339. *
  51340. * @private
  51341. * @param {Material} material - The material.
  51342. * @return {string} The GPU depth compare function.
  51343. */
  51344. _getDepthCompare( material ) {
  51345. let depthCompare;
  51346. if ( material.depthTest === false ) {
  51347. depthCompare = GPUCompareFunction.Always;
  51348. } else {
  51349. const depthFunc = material.depthFunc;
  51350. switch ( depthFunc ) {
  51351. case NeverDepth:
  51352. depthCompare = GPUCompareFunction.Never;
  51353. break;
  51354. case AlwaysDepth:
  51355. depthCompare = GPUCompareFunction.Always;
  51356. break;
  51357. case LessDepth:
  51358. depthCompare = GPUCompareFunction.Less;
  51359. break;
  51360. case LessEqualDepth:
  51361. depthCompare = GPUCompareFunction.LessEqual;
  51362. break;
  51363. case EqualDepth:
  51364. depthCompare = GPUCompareFunction.Equal;
  51365. break;
  51366. case GreaterEqualDepth:
  51367. depthCompare = GPUCompareFunction.GreaterEqual;
  51368. break;
  51369. case GreaterDepth:
  51370. depthCompare = GPUCompareFunction.Greater;
  51371. break;
  51372. case NotEqualDepth:
  51373. depthCompare = GPUCompareFunction.NotEqual;
  51374. break;
  51375. default:
  51376. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  51377. }
  51378. }
  51379. return depthCompare;
  51380. }
  51381. }
  51382. /**
  51383. * Manages a pool of WebGPU timestamp queries for performance measurement.
  51384. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  51385. *
  51386. * @augments TimestampQueryPool
  51387. */
  51388. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  51389. /**
  51390. * Creates a new WebGPU timestamp query pool.
  51391. *
  51392. * @param {GPUDevice} device - The WebGPU device to create queries on.
  51393. * @param {string} type - The type identifier for this query pool.
  51394. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  51395. */
  51396. constructor( device, type, maxQueries = 2048 ) {
  51397. super( maxQueries );
  51398. this.device = device;
  51399. this.type = type;
  51400. this.querySet = this.device.createQuerySet( {
  51401. type: 'timestamp',
  51402. count: this.maxQueries,
  51403. label: `queryset_global_timestamp_${type}`
  51404. } );
  51405. const bufferSize = this.maxQueries * 8;
  51406. this.resolveBuffer = this.device.createBuffer( {
  51407. label: `buffer_timestamp_resolve_${type}`,
  51408. size: bufferSize,
  51409. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  51410. } );
  51411. this.resultBuffer = this.device.createBuffer( {
  51412. label: `buffer_timestamp_result_${type}`,
  51413. size: bufferSize,
  51414. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51415. } );
  51416. }
  51417. /**
  51418. * Allocates a pair of queries for a given render context.
  51419. *
  51420. * @param {Object} renderContext - The render context to allocate queries for.
  51421. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  51422. */
  51423. allocateQueriesForContext( renderContext ) {
  51424. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  51425. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  51426. 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() } ).` );
  51427. return null;
  51428. }
  51429. const baseOffset = this.currentQueryIndex;
  51430. this.currentQueryIndex += 2;
  51431. this.queryOffsets.set( renderContext.id, baseOffset );
  51432. return baseOffset;
  51433. }
  51434. /**
  51435. * Asynchronously resolves all pending queries and returns the total duration.
  51436. * If there's already a pending resolve operation, returns that promise instead.
  51437. *
  51438. * @async
  51439. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  51440. */
  51441. async resolveQueriesAsync() {
  51442. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  51443. return this.lastValue;
  51444. }
  51445. if ( this.pendingResolve ) {
  51446. return this.pendingResolve;
  51447. }
  51448. this.pendingResolve = this._resolveQueries();
  51449. try {
  51450. const result = await this.pendingResolve;
  51451. return result;
  51452. } finally {
  51453. this.pendingResolve = null;
  51454. }
  51455. }
  51456. /**
  51457. * Internal method to resolve queries and calculate total duration.
  51458. *
  51459. * @async
  51460. * @private
  51461. * @returns {Promise<number>} The total duration in milliseconds.
  51462. */
  51463. async _resolveQueries() {
  51464. if ( this.isDisposed ) {
  51465. return this.lastValue;
  51466. }
  51467. try {
  51468. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  51469. return this.lastValue;
  51470. }
  51471. const currentOffsets = new Map( this.queryOffsets );
  51472. const queryCount = this.currentQueryIndex;
  51473. const bytesUsed = queryCount * 8;
  51474. // Reset state before GPU work
  51475. this.currentQueryIndex = 0;
  51476. this.queryOffsets.clear();
  51477. const commandEncoder = this.device.createCommandEncoder();
  51478. commandEncoder.resolveQuerySet(
  51479. this.querySet,
  51480. 0,
  51481. queryCount,
  51482. this.resolveBuffer,
  51483. 0
  51484. );
  51485. commandEncoder.copyBufferToBuffer(
  51486. this.resolveBuffer,
  51487. 0,
  51488. this.resultBuffer,
  51489. 0,
  51490. bytesUsed
  51491. );
  51492. const commandBuffer = commandEncoder.finish();
  51493. this.device.queue.submit( [ commandBuffer ] );
  51494. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  51495. return this.lastValue;
  51496. }
  51497. // Create and track the mapping operation
  51498. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  51499. if ( this.isDisposed ) {
  51500. if ( this.resultBuffer.mapState === 'mapped' ) {
  51501. this.resultBuffer.unmap();
  51502. }
  51503. return this.lastValue;
  51504. }
  51505. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  51506. let totalDuration = 0;
  51507. for ( const [ , baseOffset ] of currentOffsets ) {
  51508. const startTime = times[ baseOffset ];
  51509. const endTime = times[ baseOffset + 1 ];
  51510. const duration = Number( endTime - startTime ) / 1e6;
  51511. totalDuration += duration;
  51512. }
  51513. this.resultBuffer.unmap();
  51514. this.lastValue = totalDuration;
  51515. return totalDuration;
  51516. } catch ( error ) {
  51517. console.error( 'Error resolving queries:', error );
  51518. if ( this.resultBuffer.mapState === 'mapped' ) {
  51519. this.resultBuffer.unmap();
  51520. }
  51521. return this.lastValue;
  51522. }
  51523. }
  51524. /**
  51525. * Dispose of the query pool.
  51526. *
  51527. * @async
  51528. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  51529. */
  51530. async dispose() {
  51531. if ( this.isDisposed ) {
  51532. return;
  51533. }
  51534. this.isDisposed = true;
  51535. // Wait for pending resolve operation
  51536. if ( this.pendingResolve ) {
  51537. try {
  51538. await this.pendingResolve;
  51539. } catch ( error ) {
  51540. console.error( 'Error waiting for pending resolve:', error );
  51541. }
  51542. }
  51543. // Ensure buffer is unmapped before destroying
  51544. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  51545. try {
  51546. this.resultBuffer.unmap();
  51547. } catch ( error ) {
  51548. console.error( 'Error unmapping buffer:', error );
  51549. }
  51550. }
  51551. // Destroy resources
  51552. if ( this.querySet ) {
  51553. this.querySet.destroy();
  51554. this.querySet = null;
  51555. }
  51556. if ( this.resolveBuffer ) {
  51557. this.resolveBuffer.destroy();
  51558. this.resolveBuffer = null;
  51559. }
  51560. if ( this.resultBuffer ) {
  51561. this.resultBuffer.destroy();
  51562. this.resultBuffer = null;
  51563. }
  51564. this.queryOffsets.clear();
  51565. this.pendingResolve = null;
  51566. }
  51567. }
  51568. /*// debugger tools
  51569. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  51570. //*/
  51571. /**
  51572. * A backend implementation targeting WebGPU.
  51573. *
  51574. * @private
  51575. * @augments Backend
  51576. */
  51577. class WebGPUBackend extends Backend {
  51578. /**
  51579. * WebGPUBackend options.
  51580. *
  51581. * @typedef {Object} WebGPUBackend~Options
  51582. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  51583. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  51584. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  51585. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  51586. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  51587. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  51588. * @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.
  51589. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  51590. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  51591. * @property {string} [powerPreference=undefined] - The power preference.
  51592. * @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.
  51593. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  51594. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  51595. */
  51596. /**
  51597. * Constructs a new WebGPU backend.
  51598. *
  51599. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  51600. */
  51601. constructor( parameters = {} ) {
  51602. super( parameters );
  51603. /**
  51604. * This flag can be used for type testing.
  51605. *
  51606. * @type {boolean}
  51607. * @readonly
  51608. * @default true
  51609. */
  51610. this.isWebGPUBackend = true;
  51611. // some parameters require default values other than "undefined"
  51612. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  51613. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  51614. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  51615. /**
  51616. * Indicates whether the backend is in compatibility mode or not.
  51617. * @type {boolean}
  51618. * @default false
  51619. */
  51620. this.compatibilityMode = this.parameters.compatibilityMode;
  51621. /**
  51622. * A reference to the device.
  51623. *
  51624. * @type {?GPUDevice}
  51625. * @default null
  51626. */
  51627. this.device = null;
  51628. /**
  51629. * A reference to the context.
  51630. *
  51631. * @type {?GPUCanvasContext}
  51632. * @default null
  51633. */
  51634. this.context = null;
  51635. /**
  51636. * A reference to the color attachment of the default framebuffer.
  51637. *
  51638. * @type {?GPUTexture}
  51639. * @default null
  51640. */
  51641. this.colorBuffer = null;
  51642. /**
  51643. * A reference to the default render pass descriptor.
  51644. *
  51645. * @type {?Object}
  51646. * @default null
  51647. */
  51648. this.defaultRenderPassdescriptor = null;
  51649. /**
  51650. * A reference to a backend module holding common utility functions.
  51651. *
  51652. * @type {WebGPUUtils}
  51653. */
  51654. this.utils = new WebGPUUtils( this );
  51655. /**
  51656. * A reference to a backend module holding shader attribute-related
  51657. * utility functions.
  51658. *
  51659. * @type {WebGPUAttributeUtils}
  51660. */
  51661. this.attributeUtils = new WebGPUAttributeUtils( this );
  51662. /**
  51663. * A reference to a backend module holding shader binding-related
  51664. * utility functions.
  51665. *
  51666. * @type {WebGPUBindingUtils}
  51667. */
  51668. this.bindingUtils = new WebGPUBindingUtils( this );
  51669. /**
  51670. * A reference to a backend module holding shader pipeline-related
  51671. * utility functions.
  51672. *
  51673. * @type {WebGPUPipelineUtils}
  51674. */
  51675. this.pipelineUtils = new WebGPUPipelineUtils( this );
  51676. /**
  51677. * A reference to a backend module holding shader texture-related
  51678. * utility functions.
  51679. *
  51680. * @type {WebGPUTextureUtils}
  51681. */
  51682. this.textureUtils = new WebGPUTextureUtils( this );
  51683. /**
  51684. * A map that manages the resolve buffers for occlusion queries.
  51685. *
  51686. * @type {Map<number,GPUBuffer>}
  51687. */
  51688. this.occludedResolveCache = new Map();
  51689. }
  51690. /**
  51691. * Initializes the backend so it is ready for usage.
  51692. *
  51693. * @async
  51694. * @param {Renderer} renderer - The renderer.
  51695. * @return {Promise} A Promise that resolves when the backend has been initialized.
  51696. */
  51697. async init( renderer ) {
  51698. await super.init( renderer );
  51699. //
  51700. const parameters = this.parameters;
  51701. // create the device if it is not passed with parameters
  51702. let device;
  51703. if ( parameters.device === undefined ) {
  51704. const adapterOptions = {
  51705. powerPreference: parameters.powerPreference,
  51706. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  51707. };
  51708. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  51709. if ( adapter === null ) {
  51710. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  51711. }
  51712. // feature support
  51713. const features = Object.values( GPUFeatureName );
  51714. const supportedFeatures = [];
  51715. for ( const name of features ) {
  51716. if ( adapter.features.has( name ) ) {
  51717. supportedFeatures.push( name );
  51718. }
  51719. }
  51720. const deviceDescriptor = {
  51721. requiredFeatures: supportedFeatures,
  51722. requiredLimits: parameters.requiredLimits
  51723. };
  51724. device = await adapter.requestDevice( deviceDescriptor );
  51725. } else {
  51726. device = parameters.device;
  51727. }
  51728. device.lost.then( ( info ) => {
  51729. const deviceLossInfo = {
  51730. api: 'WebGPU',
  51731. message: info.message || 'Unknown reason',
  51732. reason: info.reason || null,
  51733. originalEvent: info
  51734. };
  51735. renderer.onDeviceLost( deviceLossInfo );
  51736. } );
  51737. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  51738. this.device = device;
  51739. this.context = context;
  51740. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  51741. const toneMappingMode = ColorManagement.getToneMappingMode( this.renderer.outputColorSpace );
  51742. this.context.configure( {
  51743. device: this.device,
  51744. format: this.utils.getPreferredCanvasFormat(),
  51745. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  51746. alphaMode: alphaMode,
  51747. toneMapping: {
  51748. mode: toneMappingMode
  51749. }
  51750. } );
  51751. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  51752. this.updateSize();
  51753. }
  51754. /**
  51755. * The coordinate system of the backend.
  51756. *
  51757. * @type {number}
  51758. * @readonly
  51759. */
  51760. get coordinateSystem() {
  51761. return WebGPUCoordinateSystem;
  51762. }
  51763. /**
  51764. * This method performs a readback operation by moving buffer data from
  51765. * a storage buffer attribute from the GPU to the CPU.
  51766. *
  51767. * @async
  51768. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  51769. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  51770. */
  51771. async getArrayBufferAsync( attribute ) {
  51772. return await this.attributeUtils.getArrayBufferAsync( attribute );
  51773. }
  51774. /**
  51775. * Returns the backend's rendering context.
  51776. *
  51777. * @return {GPUCanvasContext} The rendering context.
  51778. */
  51779. getContext() {
  51780. return this.context;
  51781. }
  51782. /**
  51783. * Returns the default render pass descriptor.
  51784. *
  51785. * In WebGPU, the default framebuffer must be configured
  51786. * like custom framebuffers so the backend needs a render
  51787. * pass descriptor even when rendering directly to screen.
  51788. *
  51789. * @private
  51790. * @return {Object} The render pass descriptor.
  51791. */
  51792. _getDefaultRenderPassDescriptor() {
  51793. let descriptor = this.defaultRenderPassdescriptor;
  51794. if ( descriptor === null ) {
  51795. const renderer = this.renderer;
  51796. descriptor = {
  51797. colorAttachments: [ {
  51798. view: null
  51799. } ],
  51800. };
  51801. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  51802. descriptor.depthStencilAttachment = {
  51803. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  51804. };
  51805. }
  51806. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51807. if ( this.renderer.samples > 0 ) {
  51808. colorAttachment.view = this.colorBuffer.createView();
  51809. } else {
  51810. colorAttachment.resolveTarget = undefined;
  51811. }
  51812. this.defaultRenderPassdescriptor = descriptor;
  51813. }
  51814. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51815. if ( this.renderer.samples > 0 ) {
  51816. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  51817. } else {
  51818. colorAttachment.view = this.context.getCurrentTexture().createView();
  51819. }
  51820. return descriptor;
  51821. }
  51822. /**
  51823. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  51824. *
  51825. * @param {RenderContext} renderContext - The render context.
  51826. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  51827. *
  51828. * @private
  51829. */
  51830. _isRenderCameraDepthArray( renderContext ) {
  51831. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  51832. }
  51833. /**
  51834. * Returns the render pass descriptor for the given render context.
  51835. *
  51836. * @private
  51837. * @param {RenderContext} renderContext - The render context.
  51838. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  51839. * @return {Object} The render pass descriptor.
  51840. */
  51841. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  51842. const renderTarget = renderContext.renderTarget;
  51843. const renderTargetData = this.get( renderTarget );
  51844. let descriptors = renderTargetData.descriptors;
  51845. if ( descriptors === undefined ||
  51846. renderTargetData.width !== renderTarget.width ||
  51847. renderTargetData.height !== renderTarget.height ||
  51848. renderTargetData.samples !== renderTarget.samples
  51849. ) {
  51850. descriptors = {};
  51851. renderTargetData.descriptors = descriptors;
  51852. }
  51853. const cacheKey = renderContext.getCacheKey();
  51854. let descriptorBase = descriptors[ cacheKey ];
  51855. if ( descriptorBase === undefined ) {
  51856. const textures = renderContext.textures;
  51857. const textureViews = [];
  51858. let sliceIndex;
  51859. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  51860. for ( let i = 0; i < textures.length; i ++ ) {
  51861. const textureData = this.get( textures[ i ] );
  51862. const viewDescriptor = {
  51863. label: `colorAttachment_${ i }`,
  51864. baseMipLevel: renderContext.activeMipmapLevel,
  51865. mipLevelCount: 1,
  51866. baseArrayLayer: renderContext.activeCubeFace,
  51867. arrayLayerCount: 1,
  51868. dimension: GPUTextureViewDimension.TwoD
  51869. };
  51870. if ( renderTarget.isRenderTarget3D ) {
  51871. sliceIndex = renderContext.activeCubeFace;
  51872. viewDescriptor.baseArrayLayer = 0;
  51873. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  51874. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  51875. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  51876. if ( isRenderCameraDepthArray === true ) {
  51877. const cameras = renderContext.camera.cameras;
  51878. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  51879. const layerViewDescriptor = {
  51880. ...viewDescriptor,
  51881. baseArrayLayer: layer,
  51882. arrayLayerCount: 1,
  51883. dimension: GPUTextureViewDimension.TwoD
  51884. };
  51885. const textureView = textureData.texture.createView( layerViewDescriptor );
  51886. textureViews.push( {
  51887. view: textureView,
  51888. resolveTarget: undefined,
  51889. depthSlice: undefined
  51890. } );
  51891. }
  51892. } else {
  51893. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  51894. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  51895. }
  51896. }
  51897. if ( isRenderCameraDepthArray !== true ) {
  51898. const textureView = textureData.texture.createView( viewDescriptor );
  51899. let view, resolveTarget;
  51900. if ( textureData.msaaTexture !== undefined ) {
  51901. view = textureData.msaaTexture.createView();
  51902. resolveTarget = textureView;
  51903. } else {
  51904. view = textureView;
  51905. resolveTarget = undefined;
  51906. }
  51907. textureViews.push( {
  51908. view,
  51909. resolveTarget,
  51910. depthSlice: sliceIndex
  51911. } );
  51912. }
  51913. }
  51914. descriptorBase = { textureViews };
  51915. if ( renderContext.depth ) {
  51916. const depthTextureData = this.get( renderContext.depthTexture );
  51917. const options = {};
  51918. if ( renderContext.depthTexture.isArrayTexture ) {
  51919. options.dimension = GPUTextureViewDimension.TwoD;
  51920. options.arrayLayerCount = 1;
  51921. options.baseArrayLayer = renderContext.activeCubeFace;
  51922. }
  51923. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  51924. }
  51925. descriptors[ cacheKey ] = descriptorBase;
  51926. renderTargetData.width = renderTarget.width;
  51927. renderTargetData.height = renderTarget.height;
  51928. renderTargetData.samples = renderTarget.samples;
  51929. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  51930. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  51931. }
  51932. const descriptor = {
  51933. colorAttachments: []
  51934. };
  51935. // Apply dynamic properties to cached views
  51936. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  51937. const viewInfo = descriptorBase.textureViews[ i ];
  51938. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  51939. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  51940. clearValue = colorAttachmentsConfig.clearValue;
  51941. }
  51942. descriptor.colorAttachments.push( {
  51943. view: viewInfo.view,
  51944. depthSlice: viewInfo.depthSlice,
  51945. resolveTarget: viewInfo.resolveTarget,
  51946. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  51947. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  51948. clearValue: clearValue
  51949. } );
  51950. }
  51951. if ( descriptorBase.depthStencilView ) {
  51952. descriptor.depthStencilAttachment = {
  51953. view: descriptorBase.depthStencilView
  51954. };
  51955. }
  51956. return descriptor;
  51957. }
  51958. /**
  51959. * This method is executed at the beginning of a render call and prepares
  51960. * the WebGPU state for upcoming render calls
  51961. *
  51962. * @param {RenderContext} renderContext - The render context.
  51963. */
  51964. beginRender( renderContext ) {
  51965. const renderContextData = this.get( renderContext );
  51966. const device = this.device;
  51967. const occlusionQueryCount = renderContext.occlusionQueryCount;
  51968. let occlusionQuerySet;
  51969. if ( occlusionQueryCount > 0 ) {
  51970. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  51971. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  51972. // Get a reference to the array of objects with queries. The renderContextData property
  51973. // can be changed by another render pass before the buffer.mapAsyc() completes.
  51974. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  51975. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  51976. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  51977. //
  51978. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  51979. renderContextData.occlusionQuerySet = occlusionQuerySet;
  51980. renderContextData.occlusionQueryIndex = 0;
  51981. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  51982. renderContextData.lastOcclusionObject = null;
  51983. }
  51984. let descriptor;
  51985. if ( renderContext.textures === null ) {
  51986. descriptor = this._getDefaultRenderPassDescriptor();
  51987. } else {
  51988. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  51989. }
  51990. this.initTimestampQuery( renderContext, descriptor );
  51991. descriptor.occlusionQuerySet = occlusionQuerySet;
  51992. const depthStencilAttachment = descriptor.depthStencilAttachment;
  51993. if ( renderContext.textures !== null ) {
  51994. const colorAttachments = descriptor.colorAttachments;
  51995. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  51996. const colorAttachment = colorAttachments[ i ];
  51997. if ( renderContext.clearColor ) {
  51998. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  51999. colorAttachment.loadOp = GPULoadOp.Clear;
  52000. } else {
  52001. colorAttachment.loadOp = GPULoadOp.Load;
  52002. }
  52003. colorAttachment.storeOp = GPUStoreOp.Store;
  52004. }
  52005. } else {
  52006. const colorAttachment = descriptor.colorAttachments[ 0 ];
  52007. if ( renderContext.clearColor ) {
  52008. colorAttachment.clearValue = renderContext.clearColorValue;
  52009. colorAttachment.loadOp = GPULoadOp.Clear;
  52010. } else {
  52011. colorAttachment.loadOp = GPULoadOp.Load;
  52012. }
  52013. colorAttachment.storeOp = GPUStoreOp.Store;
  52014. }
  52015. //
  52016. if ( renderContext.depth ) {
  52017. if ( renderContext.clearDepth ) {
  52018. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  52019. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  52020. } else {
  52021. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  52022. }
  52023. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52024. }
  52025. if ( renderContext.stencil ) {
  52026. if ( renderContext.clearStencil ) {
  52027. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  52028. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  52029. } else {
  52030. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  52031. }
  52032. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52033. }
  52034. //
  52035. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  52036. // shadow arrays - prepare bundle encoders for each camera in an array camera
  52037. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  52038. const cameras = renderContext.camera.cameras;
  52039. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  52040. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  52041. } else {
  52042. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  52043. }
  52044. // Create bundle encoders for each layer
  52045. renderContextData.bundleEncoders = [];
  52046. renderContextData.bundleSets = [];
  52047. // Create separate bundle encoders for each camera in the array
  52048. for ( let i = 0; i < cameras.length; i ++ ) {
  52049. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  52050. renderContext,
  52051. 'renderBundleArrayCamera_' + i
  52052. );
  52053. // Initialize state tracking for this bundle
  52054. const bundleSets = {
  52055. attributes: {},
  52056. bindingGroups: [],
  52057. pipeline: null,
  52058. index: null
  52059. };
  52060. renderContextData.bundleEncoders.push( bundleEncoder );
  52061. renderContextData.bundleSets.push( bundleSets );
  52062. }
  52063. // We'll complete the bundles in finishRender
  52064. renderContextData.currentPass = null;
  52065. } else {
  52066. const currentPass = encoder.beginRenderPass( descriptor );
  52067. renderContextData.currentPass = currentPass;
  52068. if ( renderContext.viewport ) {
  52069. this.updateViewport( renderContext );
  52070. }
  52071. if ( renderContext.scissor ) {
  52072. const { x, y, width, height } = renderContext.scissorValue;
  52073. currentPass.setScissorRect( x, y, width, height );
  52074. }
  52075. }
  52076. //
  52077. renderContextData.descriptor = descriptor;
  52078. renderContextData.encoder = encoder;
  52079. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52080. renderContextData.renderBundles = [];
  52081. }
  52082. /**
  52083. * This method creates layer descriptors for each camera in an array camera
  52084. * to prepare for rendering to a depth array texture.
  52085. *
  52086. * @param {RenderContext} renderContext - The render context.
  52087. * @param {Object} renderContextData - The render context data.
  52088. * @param {Object} descriptor - The render pass descriptor.
  52089. * @param {ArrayCamera} cameras - The array camera.
  52090. *
  52091. * @private
  52092. */
  52093. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  52094. const depthStencilAttachment = descriptor.depthStencilAttachment;
  52095. renderContextData.layerDescriptors = [];
  52096. const depthTextureData = this.get( renderContext.depthTexture );
  52097. if ( ! depthTextureData.viewCache ) {
  52098. depthTextureData.viewCache = [];
  52099. }
  52100. for ( let i = 0; i < cameras.length; i ++ ) {
  52101. const layerDescriptor = {
  52102. ...descriptor,
  52103. colorAttachments: [ {
  52104. ...descriptor.colorAttachments[ 0 ],
  52105. view: descriptor.colorAttachments[ i ].view
  52106. } ]
  52107. };
  52108. if ( descriptor.depthStencilAttachment ) {
  52109. const layerIndex = i;
  52110. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  52111. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  52112. dimension: GPUTextureViewDimension.TwoD,
  52113. baseArrayLayer: i,
  52114. arrayLayerCount: 1
  52115. } );
  52116. }
  52117. layerDescriptor.depthStencilAttachment = {
  52118. view: depthTextureData.viewCache[ layerIndex ],
  52119. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  52120. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  52121. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  52122. };
  52123. if ( renderContext.stencil ) {
  52124. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  52125. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  52126. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  52127. }
  52128. } else {
  52129. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  52130. }
  52131. renderContextData.layerDescriptors.push( layerDescriptor );
  52132. }
  52133. }
  52134. /**
  52135. * This method updates the layer descriptors for each camera in an array camera
  52136. * to prepare for rendering to a depth array texture.
  52137. *
  52138. * @param {RenderContext} renderContext - The render context.
  52139. * @param {Object} renderContextData - The render context data.
  52140. * @param {ArrayCamera} cameras - The array camera.
  52141. *
  52142. */
  52143. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  52144. for ( let i = 0; i < cameras.length; i ++ ) {
  52145. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  52146. if ( layerDescriptor.depthStencilAttachment ) {
  52147. const depthAttachment = layerDescriptor.depthStencilAttachment;
  52148. if ( renderContext.depth ) {
  52149. if ( renderContext.clearDepth ) {
  52150. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  52151. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  52152. } else {
  52153. depthAttachment.depthLoadOp = GPULoadOp.Load;
  52154. }
  52155. }
  52156. if ( renderContext.stencil ) {
  52157. if ( renderContext.clearStencil ) {
  52158. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  52159. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  52160. } else {
  52161. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  52162. }
  52163. }
  52164. }
  52165. }
  52166. }
  52167. /**
  52168. * This method is executed at the end of a render call and finalizes work
  52169. * after draw calls.
  52170. *
  52171. * @param {RenderContext} renderContext - The render context.
  52172. */
  52173. finishRender( renderContext ) {
  52174. const renderContextData = this.get( renderContext );
  52175. const occlusionQueryCount = renderContext.occlusionQueryCount;
  52176. if ( renderContextData.renderBundles.length > 0 ) {
  52177. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  52178. }
  52179. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  52180. renderContextData.currentPass.endOcclusionQuery();
  52181. }
  52182. // shadow arrays - Execute bundles for each layer
  52183. const encoder = renderContextData.encoder;
  52184. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  52185. const bundles = [];
  52186. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  52187. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  52188. bundles.push( bundleEncoder.finish() );
  52189. }
  52190. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  52191. if ( i < bundles.length ) {
  52192. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  52193. const renderPass = encoder.beginRenderPass( layerDescriptor );
  52194. if ( renderContext.viewport ) {
  52195. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  52196. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  52197. }
  52198. if ( renderContext.scissor ) {
  52199. const { x, y, width, height } = renderContext.scissorValue;
  52200. renderPass.setScissorRect( x, y, width, height );
  52201. }
  52202. renderPass.executeBundles( [ bundles[ i ] ] );
  52203. renderPass.end();
  52204. }
  52205. }
  52206. } else if ( renderContextData.currentPass ) {
  52207. renderContextData.currentPass.end();
  52208. }
  52209. if ( occlusionQueryCount > 0 ) {
  52210. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  52211. //
  52212. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  52213. if ( queryResolveBuffer === undefined ) {
  52214. queryResolveBuffer = this.device.createBuffer(
  52215. {
  52216. size: bufferSize,
  52217. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  52218. }
  52219. );
  52220. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  52221. }
  52222. //
  52223. const readBuffer = this.device.createBuffer(
  52224. {
  52225. size: bufferSize,
  52226. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52227. }
  52228. );
  52229. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  52230. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  52231. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  52232. renderContextData.occlusionQueryBuffer = readBuffer;
  52233. //
  52234. this.resolveOccludedAsync( renderContext );
  52235. }
  52236. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  52237. //
  52238. if ( renderContext.textures !== null ) {
  52239. const textures = renderContext.textures;
  52240. for ( let i = 0; i < textures.length; i ++ ) {
  52241. const texture = textures[ i ];
  52242. if ( texture.generateMipmaps === true ) {
  52243. this.textureUtils.generateMipmaps( texture );
  52244. }
  52245. }
  52246. }
  52247. }
  52248. /**
  52249. * Returns `true` if the given 3D object is fully occluded by other
  52250. * 3D objects in the scene.
  52251. *
  52252. * @param {RenderContext} renderContext - The render context.
  52253. * @param {Object3D} object - The 3D object to test.
  52254. * @return {boolean} Whether the 3D object is fully occluded or not.
  52255. */
  52256. isOccluded( renderContext, object ) {
  52257. const renderContextData = this.get( renderContext );
  52258. return renderContextData.occluded && renderContextData.occluded.has( object );
  52259. }
  52260. /**
  52261. * This method processes the result of occlusion queries and writes it
  52262. * into render context data.
  52263. *
  52264. * @async
  52265. * @param {RenderContext} renderContext - The render context.
  52266. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  52267. */
  52268. async resolveOccludedAsync( renderContext ) {
  52269. const renderContextData = this.get( renderContext );
  52270. // handle occlusion query results
  52271. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  52272. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  52273. const occluded = new WeakSet();
  52274. renderContextData.currentOcclusionQueryObjects = null;
  52275. renderContextData.currentOcclusionQueryBuffer = null;
  52276. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  52277. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  52278. const results = new BigUint64Array( buffer );
  52279. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  52280. if ( results[ i ] === BigInt( 0 ) ) {
  52281. occluded.add( currentOcclusionQueryObjects[ i ] );
  52282. }
  52283. }
  52284. currentOcclusionQueryBuffer.destroy();
  52285. renderContextData.occluded = occluded;
  52286. }
  52287. }
  52288. /**
  52289. * Updates the viewport with the values from the given render context.
  52290. *
  52291. * @param {RenderContext} renderContext - The render context.
  52292. */
  52293. updateViewport( renderContext ) {
  52294. const { currentPass } = this.get( renderContext );
  52295. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  52296. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  52297. }
  52298. /**
  52299. * Returns the clear color and alpha into a single
  52300. * color object.
  52301. *
  52302. * @return {Color4} The clear color.
  52303. */
  52304. getClearColor() {
  52305. const clearColor = super.getClearColor();
  52306. // only premultiply alpha when alphaMode is "premultiplied"
  52307. if ( this.renderer.alpha === true ) {
  52308. clearColor.r *= clearColor.a;
  52309. clearColor.g *= clearColor.a;
  52310. clearColor.b *= clearColor.a;
  52311. }
  52312. return clearColor;
  52313. }
  52314. /**
  52315. * Performs a clear operation.
  52316. *
  52317. * @param {boolean} color - Whether the color buffer should be cleared or not.
  52318. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  52319. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  52320. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  52321. */
  52322. clear( color, depth, stencil, renderTargetContext = null ) {
  52323. const device = this.device;
  52324. const renderer = this.renderer;
  52325. let colorAttachments = [];
  52326. let depthStencilAttachment;
  52327. let clearValue;
  52328. let supportsDepth;
  52329. let supportsStencil;
  52330. if ( color ) {
  52331. const clearColor = this.getClearColor();
  52332. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  52333. }
  52334. if ( renderTargetContext === null ) {
  52335. supportsDepth = renderer.depth;
  52336. supportsStencil = renderer.stencil;
  52337. const descriptor = this._getDefaultRenderPassDescriptor();
  52338. if ( color ) {
  52339. colorAttachments = descriptor.colorAttachments;
  52340. const colorAttachment = colorAttachments[ 0 ];
  52341. colorAttachment.clearValue = clearValue;
  52342. colorAttachment.loadOp = GPULoadOp.Clear;
  52343. colorAttachment.storeOp = GPUStoreOp.Store;
  52344. }
  52345. if ( supportsDepth || supportsStencil ) {
  52346. depthStencilAttachment = descriptor.depthStencilAttachment;
  52347. }
  52348. } else {
  52349. supportsDepth = renderTargetContext.depth;
  52350. supportsStencil = renderTargetContext.stencil;
  52351. const clearConfig = {
  52352. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  52353. clearValue: color ? clearValue : undefined
  52354. };
  52355. if ( supportsDepth ) {
  52356. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  52357. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  52358. clearConfig.depthStoreOp = GPUStoreOp.Store;
  52359. }
  52360. if ( supportsStencil ) {
  52361. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  52362. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  52363. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  52364. }
  52365. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  52366. colorAttachments = descriptor.colorAttachments;
  52367. depthStencilAttachment = descriptor.depthStencilAttachment;
  52368. }
  52369. if ( supportsDepth && depthStencilAttachment ) {
  52370. if ( depth ) {
  52371. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  52372. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  52373. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52374. } else {
  52375. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  52376. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52377. }
  52378. }
  52379. //
  52380. if ( supportsStencil && depthStencilAttachment ) {
  52381. if ( stencil ) {
  52382. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  52383. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  52384. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52385. } else {
  52386. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  52387. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52388. }
  52389. }
  52390. //
  52391. const encoder = device.createCommandEncoder( { label: 'clear' } );
  52392. const currentPass = encoder.beginRenderPass( {
  52393. colorAttachments,
  52394. depthStencilAttachment
  52395. } );
  52396. currentPass.end();
  52397. device.queue.submit( [ encoder.finish() ] );
  52398. }
  52399. // compute
  52400. /**
  52401. * This method is executed at the beginning of a compute call and
  52402. * prepares the state for upcoming compute tasks.
  52403. *
  52404. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  52405. */
  52406. beginCompute( computeGroup ) {
  52407. const groupGPU = this.get( computeGroup );
  52408. const descriptor = {
  52409. label: 'computeGroup_' + computeGroup.id
  52410. };
  52411. this.initTimestampQuery( computeGroup, descriptor );
  52412. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  52413. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  52414. }
  52415. /**
  52416. * Executes a compute command for the given compute node.
  52417. *
  52418. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  52419. * @param {Node} computeNode - The compute node.
  52420. * @param {Array<BindGroup>} bindings - The bindings.
  52421. * @param {ComputePipeline} pipeline - The compute pipeline.
  52422. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  52423. */
  52424. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  52425. const computeNodeData = this.get( computeNode );
  52426. const { passEncoderGPU } = this.get( computeGroup );
  52427. // pipeline
  52428. const pipelineGPU = this.get( pipeline ).pipeline;
  52429. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  52430. // bind groups
  52431. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  52432. const bindGroup = bindings[ i ];
  52433. const bindingsData = this.get( bindGroup );
  52434. passEncoderGPU.setBindGroup( i, bindingsData.group );
  52435. }
  52436. let dispatchSize;
  52437. if ( dispatchSizeOrCount === null ) {
  52438. dispatchSizeOrCount = computeNode.count;
  52439. }
  52440. if ( typeof dispatchSizeOrCount === 'number' ) {
  52441. // If a single number is given, we calculate the dispatch size based on the workgroup size
  52442. const count = dispatchSizeOrCount;
  52443. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  52444. // cache dispatch size to avoid recalculating it every time
  52445. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  52446. computeNodeData.count = count;
  52447. const workgroupSize = computeNode.workgroupSize;
  52448. let size = workgroupSize[ 0 ];
  52449. for ( let i = 1; i < workgroupSize.length; i ++ )
  52450. size *= workgroupSize[ i ];
  52451. const dispatchCount = Math.ceil( count / size );
  52452. //
  52453. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  52454. dispatchSize = [ dispatchCount, 1, 1 ];
  52455. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  52456. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  52457. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  52458. }
  52459. computeNodeData.dispatchSize = dispatchSize;
  52460. }
  52461. dispatchSize = computeNodeData.dispatchSize;
  52462. } else {
  52463. dispatchSize = dispatchSizeOrCount;
  52464. }
  52465. //
  52466. passEncoderGPU.dispatchWorkgroups(
  52467. dispatchSize[ 0 ],
  52468. dispatchSize[ 1 ] || 1,
  52469. dispatchSize[ 2 ] || 1
  52470. );
  52471. }
  52472. /**
  52473. * This method is executed at the end of a compute call and
  52474. * finalizes work after compute tasks.
  52475. *
  52476. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  52477. */
  52478. finishCompute( computeGroup ) {
  52479. const groupData = this.get( computeGroup );
  52480. groupData.passEncoderGPU.end();
  52481. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  52482. }
  52483. /**
  52484. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  52485. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  52486. *
  52487. * @async
  52488. * @return {Promise} A Promise that resolves when synchronization has been finished.
  52489. */
  52490. async waitForGPU() {
  52491. await this.device.queue.onSubmittedWorkDone();
  52492. }
  52493. // render object
  52494. /**
  52495. * Executes a draw command for the given render object.
  52496. *
  52497. * @param {RenderObject} renderObject - The render object to draw.
  52498. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  52499. */
  52500. draw( renderObject, info ) {
  52501. const { object, material, context, pipeline } = renderObject;
  52502. const bindings = renderObject.getBindings();
  52503. const renderContextData = this.get( context );
  52504. const pipelineGPU = this.get( pipeline ).pipeline;
  52505. const index = renderObject.getIndex();
  52506. const hasIndex = ( index !== null );
  52507. const drawParams = renderObject.getDrawParameters();
  52508. if ( drawParams === null ) return;
  52509. // pipeline
  52510. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  52511. // pipeline
  52512. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  52513. currentSets.pipeline = pipelineGPU;
  52514. // bind groups
  52515. const currentBindingGroups = currentSets.bindingGroups;
  52516. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  52517. const bindGroup = bindings[ i ];
  52518. const bindingsData = this.get( bindGroup );
  52519. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  52520. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  52521. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  52522. }
  52523. }
  52524. // attributes
  52525. // index
  52526. if ( hasIndex === true ) {
  52527. if ( currentSets.index !== index ) {
  52528. const buffer = this.get( index ).buffer;
  52529. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  52530. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  52531. currentSets.index = index;
  52532. }
  52533. }
  52534. // vertex buffers
  52535. const vertexBuffers = renderObject.getVertexBuffers();
  52536. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  52537. const vertexBuffer = vertexBuffers[ i ];
  52538. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  52539. const buffer = this.get( vertexBuffer ).buffer;
  52540. passEncoderGPU.setVertexBuffer( i, buffer );
  52541. currentSets.attributes[ i ] = vertexBuffer;
  52542. }
  52543. }
  52544. // stencil
  52545. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  52546. passEncoderGPU.setStencilReference( material.stencilRef );
  52547. renderContextData.currentStencilRef = material.stencilRef;
  52548. }
  52549. };
  52550. // Define draw function
  52551. const draw = ( passEncoderGPU, currentSets ) => {
  52552. setPipelineAndBindings( passEncoderGPU, currentSets );
  52553. if ( object.isBatchedMesh === true ) {
  52554. const starts = object._multiDrawStarts;
  52555. const counts = object._multiDrawCounts;
  52556. const drawCount = object._multiDrawCount;
  52557. const drawInstances = object._multiDrawInstances;
  52558. if ( drawInstances !== null ) {
  52559. // @deprecated, r174
  52560. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  52561. }
  52562. for ( let i = 0; i < drawCount; i ++ ) {
  52563. const count = drawInstances ? drawInstances[ i ] : 1;
  52564. const firstInstance = count > 1 ? 0 : i;
  52565. if ( hasIndex === true ) {
  52566. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  52567. } else {
  52568. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  52569. }
  52570. info.update( object, counts[ i ], count );
  52571. }
  52572. } else if ( hasIndex === true ) {
  52573. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  52574. const indirect = renderObject.getIndirect();
  52575. if ( indirect !== null ) {
  52576. const buffer = this.get( indirect ).buffer;
  52577. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  52578. } else {
  52579. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  52580. }
  52581. info.update( object, indexCount, instanceCount );
  52582. } else {
  52583. const { vertexCount, instanceCount, firstVertex } = drawParams;
  52584. const indirect = renderObject.getIndirect();
  52585. if ( indirect !== null ) {
  52586. const buffer = this.get( indirect ).buffer;
  52587. passEncoderGPU.drawIndirect( buffer, 0 );
  52588. } else {
  52589. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  52590. }
  52591. info.update( object, vertexCount, instanceCount );
  52592. }
  52593. };
  52594. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  52595. const cameraData = this.get( renderObject.camera );
  52596. const cameras = renderObject.camera.cameras;
  52597. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  52598. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  52599. const bindingsData = this.get( cameraIndex );
  52600. const indexesGPU = [];
  52601. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  52602. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  52603. data[ 0 ] = i;
  52604. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  52605. indexesGPU.push( bindGroupIndex );
  52606. }
  52607. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  52608. }
  52609. const pixelRatio = this.renderer.getPixelRatio();
  52610. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  52611. const subCamera = cameras[ i ];
  52612. if ( object.layers.test( subCamera.layers ) ) {
  52613. const vp = subCamera.viewport;
  52614. let pass = renderContextData.currentPass;
  52615. let sets = renderContextData.currentSets;
  52616. if ( renderContextData.bundleEncoders ) {
  52617. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  52618. const bundleSets = renderContextData.bundleSets[ i ];
  52619. pass = bundleEncoder;
  52620. sets = bundleSets;
  52621. }
  52622. if ( vp ) {
  52623. pass.setViewport(
  52624. Math.floor( vp.x * pixelRatio ),
  52625. Math.floor( vp.y * pixelRatio ),
  52626. Math.floor( vp.width * pixelRatio ),
  52627. Math.floor( vp.height * pixelRatio ),
  52628. context.viewportValue.minDepth,
  52629. context.viewportValue.maxDepth
  52630. );
  52631. }
  52632. // Set camera index binding for this layer
  52633. if ( cameraIndex && cameraData.indexesGPU ) {
  52634. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  52635. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  52636. }
  52637. draw( pass, sets );
  52638. }
  52639. }
  52640. } else {
  52641. // Regular single camera rendering
  52642. if ( renderContextData.currentPass ) {
  52643. // Handle occlusion queries
  52644. if ( renderContextData.occlusionQuerySet !== undefined ) {
  52645. const lastObject = renderContextData.lastOcclusionObject;
  52646. if ( lastObject !== object ) {
  52647. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  52648. renderContextData.currentPass.endOcclusionQuery();
  52649. renderContextData.occlusionQueryIndex ++;
  52650. }
  52651. if ( object.occlusionTest === true ) {
  52652. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  52653. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  52654. }
  52655. renderContextData.lastOcclusionObject = object;
  52656. }
  52657. }
  52658. draw( renderContextData.currentPass, renderContextData.currentSets );
  52659. }
  52660. }
  52661. }
  52662. // cache key
  52663. /**
  52664. * Returns `true` if the render pipeline requires an update.
  52665. *
  52666. * @param {RenderObject} renderObject - The render object.
  52667. * @return {boolean} Whether the render pipeline requires an update or not.
  52668. */
  52669. needsRenderUpdate( renderObject ) {
  52670. const data = this.get( renderObject );
  52671. const { object, material } = renderObject;
  52672. const utils = this.utils;
  52673. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  52674. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  52675. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  52676. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  52677. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  52678. let needsUpdate = false;
  52679. if ( data.material !== material || data.materialVersion !== material.version ||
  52680. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  52681. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  52682. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  52683. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  52684. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  52685. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  52686. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  52687. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  52688. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  52689. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  52690. data.primitiveTopology !== primitiveTopology ||
  52691. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  52692. ) {
  52693. data.material = material; data.materialVersion = material.version;
  52694. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  52695. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  52696. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  52697. data.colorWrite = material.colorWrite;
  52698. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  52699. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  52700. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  52701. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  52702. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  52703. data.sampleCount = sampleCount;
  52704. data.colorSpace = colorSpace;
  52705. data.colorFormat = colorFormat;
  52706. data.depthStencilFormat = depthStencilFormat;
  52707. data.primitiveTopology = primitiveTopology;
  52708. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  52709. needsUpdate = true;
  52710. }
  52711. return needsUpdate;
  52712. }
  52713. /**
  52714. * Returns a cache key that is used to identify render pipelines.
  52715. *
  52716. * @param {RenderObject} renderObject - The render object.
  52717. * @return {string} The cache key.
  52718. */
  52719. getRenderCacheKey( renderObject ) {
  52720. const { object, material } = renderObject;
  52721. const utils = this.utils;
  52722. const renderContext = renderObject.context;
  52723. return [
  52724. material.transparent, material.blending, material.premultipliedAlpha,
  52725. material.blendSrc, material.blendDst, material.blendEquation,
  52726. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  52727. material.colorWrite,
  52728. material.depthWrite, material.depthTest, material.depthFunc,
  52729. material.stencilWrite, material.stencilFunc,
  52730. material.stencilFail, material.stencilZFail, material.stencilZPass,
  52731. material.stencilFuncMask, material.stencilWriteMask,
  52732. material.side,
  52733. utils.getSampleCountRenderContext( renderContext ),
  52734. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  52735. utils.getPrimitiveTopology( object, material ),
  52736. renderObject.getGeometryCacheKey(),
  52737. renderObject.clippingContextCacheKey
  52738. ].join();
  52739. }
  52740. // textures
  52741. /**
  52742. * Creates a GPU sampler for the given texture.
  52743. *
  52744. * @param {Texture} texture - The texture to create the sampler for.
  52745. */
  52746. createSampler( texture ) {
  52747. this.textureUtils.createSampler( texture );
  52748. }
  52749. /**
  52750. * Destroys the GPU sampler for the given texture.
  52751. *
  52752. * @param {Texture} texture - The texture to destroy the sampler for.
  52753. */
  52754. destroySampler( texture ) {
  52755. this.textureUtils.destroySampler( texture );
  52756. }
  52757. /**
  52758. * Creates a default texture for the given texture that can be used
  52759. * as a placeholder until the actual texture is ready for usage.
  52760. *
  52761. * @param {Texture} texture - The texture to create a default texture for.
  52762. */
  52763. createDefaultTexture( texture ) {
  52764. this.textureUtils.createDefaultTexture( texture );
  52765. }
  52766. /**
  52767. * Defines a texture on the GPU for the given texture object.
  52768. *
  52769. * @param {Texture} texture - The texture.
  52770. * @param {Object} [options={}] - Optional configuration parameter.
  52771. */
  52772. createTexture( texture, options ) {
  52773. this.textureUtils.createTexture( texture, options );
  52774. }
  52775. /**
  52776. * Uploads the updated texture data to the GPU.
  52777. *
  52778. * @param {Texture} texture - The texture.
  52779. * @param {Object} [options={}] - Optional configuration parameter.
  52780. */
  52781. updateTexture( texture, options ) {
  52782. this.textureUtils.updateTexture( texture, options );
  52783. }
  52784. /**
  52785. * Generates mipmaps for the given texture.
  52786. *
  52787. * @param {Texture} texture - The texture.
  52788. */
  52789. generateMipmaps( texture ) {
  52790. this.textureUtils.generateMipmaps( texture );
  52791. }
  52792. /**
  52793. * Destroys the GPU data for the given texture object.
  52794. *
  52795. * @param {Texture} texture - The texture.
  52796. */
  52797. destroyTexture( texture ) {
  52798. this.textureUtils.destroyTexture( texture );
  52799. }
  52800. /**
  52801. * Returns texture data as a typed array.
  52802. *
  52803. * @async
  52804. * @param {Texture} texture - The texture to copy.
  52805. * @param {number} x - The x coordinate of the copy origin.
  52806. * @param {number} y - The y coordinate of the copy origin.
  52807. * @param {number} width - The width of the copy.
  52808. * @param {number} height - The height of the copy.
  52809. * @param {number} faceIndex - The face index.
  52810. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  52811. */
  52812. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  52813. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  52814. }
  52815. /**
  52816. * Inits a time stamp query for the given render context.
  52817. *
  52818. * @param {RenderContext} renderContext - The render context.
  52819. * @param {Object} descriptor - The query descriptor.
  52820. */
  52821. initTimestampQuery( renderContext, descriptor ) {
  52822. if ( ! this.trackTimestamp ) return;
  52823. const type = renderContext.isComputeNode ? 'compute' : 'render';
  52824. if ( ! this.timestampQueryPool[ type ] ) {
  52825. // TODO: Variable maxQueries?
  52826. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  52827. }
  52828. const timestampQueryPool = this.timestampQueryPool[ type ];
  52829. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  52830. descriptor.timestampWrites = {
  52831. querySet: timestampQueryPool.querySet,
  52832. beginningOfPassWriteIndex: baseOffset,
  52833. endOfPassWriteIndex: baseOffset + 1,
  52834. };
  52835. }
  52836. // node builder
  52837. /**
  52838. * Returns a node builder for the given render object.
  52839. *
  52840. * @param {RenderObject} object - The render object.
  52841. * @param {Renderer} renderer - The renderer.
  52842. * @return {WGSLNodeBuilder} The node builder.
  52843. */
  52844. createNodeBuilder( object, renderer ) {
  52845. return new WGSLNodeBuilder( object, renderer );
  52846. }
  52847. // program
  52848. /**
  52849. * Creates a shader program from the given programmable stage.
  52850. *
  52851. * @param {ProgrammableStage} program - The programmable stage.
  52852. */
  52853. createProgram( program ) {
  52854. const programGPU = this.get( program );
  52855. programGPU.module = {
  52856. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  52857. entryPoint: 'main'
  52858. };
  52859. }
  52860. /**
  52861. * Destroys the shader program of the given programmable stage.
  52862. *
  52863. * @param {ProgrammableStage} program - The programmable stage.
  52864. */
  52865. destroyProgram( program ) {
  52866. this.delete( program );
  52867. }
  52868. // pipelines
  52869. /**
  52870. * Creates a render pipeline for the given render object.
  52871. *
  52872. * @param {RenderObject} renderObject - The render object.
  52873. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  52874. */
  52875. createRenderPipeline( renderObject, promises ) {
  52876. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  52877. }
  52878. /**
  52879. * Creates a compute pipeline for the given compute node.
  52880. *
  52881. * @param {ComputePipeline} computePipeline - The compute pipeline.
  52882. * @param {Array<BindGroup>} bindings - The bindings.
  52883. */
  52884. createComputePipeline( computePipeline, bindings ) {
  52885. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  52886. }
  52887. /**
  52888. * Prepares the state for encoding render bundles.
  52889. *
  52890. * @param {RenderContext} renderContext - The render context.
  52891. */
  52892. beginBundle( renderContext ) {
  52893. const renderContextData = this.get( renderContext );
  52894. renderContextData._currentPass = renderContextData.currentPass;
  52895. renderContextData._currentSets = renderContextData.currentSets;
  52896. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52897. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  52898. }
  52899. /**
  52900. * After processing render bundles this method finalizes related work.
  52901. *
  52902. * @param {RenderContext} renderContext - The render context.
  52903. * @param {RenderBundle} bundle - The render bundle.
  52904. */
  52905. finishBundle( renderContext, bundle ) {
  52906. const renderContextData = this.get( renderContext );
  52907. const bundleEncoder = renderContextData.currentPass;
  52908. const bundleGPU = bundleEncoder.finish();
  52909. this.get( bundle ).bundleGPU = bundleGPU;
  52910. // restore render pass state
  52911. renderContextData.currentSets = renderContextData._currentSets;
  52912. renderContextData.currentPass = renderContextData._currentPass;
  52913. }
  52914. /**
  52915. * Adds a render bundle to the render context data.
  52916. *
  52917. * @param {RenderContext} renderContext - The render context.
  52918. * @param {RenderBundle} bundle - The render bundle to add.
  52919. */
  52920. addBundle( renderContext, bundle ) {
  52921. const renderContextData = this.get( renderContext );
  52922. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  52923. }
  52924. // bindings
  52925. /**
  52926. * Creates bindings from the given bind group definition.
  52927. *
  52928. * @param {BindGroup} bindGroup - The bind group.
  52929. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52930. * @param {number} cacheIndex - The cache index.
  52931. * @param {number} version - The version.
  52932. */
  52933. createBindings( bindGroup, bindings, cacheIndex, version ) {
  52934. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  52935. }
  52936. /**
  52937. * Updates the given bind group definition.
  52938. *
  52939. * @param {BindGroup} bindGroup - The bind group.
  52940. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52941. * @param {number} cacheIndex - The cache index.
  52942. * @param {number} version - The version.
  52943. */
  52944. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  52945. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  52946. }
  52947. /**
  52948. * Updates a buffer binding.
  52949. *
  52950. * @param {Buffer} binding - The buffer binding to update.
  52951. */
  52952. updateBinding( binding ) {
  52953. this.bindingUtils.updateBinding( binding );
  52954. }
  52955. // attributes
  52956. /**
  52957. * Creates the buffer of an indexed shader attribute.
  52958. *
  52959. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  52960. */
  52961. createIndexAttribute( attribute ) {
  52962. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  52963. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  52964. usage |= GPUBufferUsage.STORAGE;
  52965. }
  52966. this.attributeUtils.createAttribute( attribute, usage );
  52967. }
  52968. /**
  52969. * Creates the GPU buffer of a shader attribute.
  52970. *
  52971. * @param {BufferAttribute} attribute - The buffer attribute.
  52972. */
  52973. createAttribute( attribute ) {
  52974. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  52975. }
  52976. /**
  52977. * Creates the GPU buffer of a storage attribute.
  52978. *
  52979. * @param {BufferAttribute} attribute - The buffer attribute.
  52980. */
  52981. createStorageAttribute( attribute ) {
  52982. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  52983. }
  52984. /**
  52985. * Creates the GPU buffer of an indirect storage attribute.
  52986. *
  52987. * @param {BufferAttribute} attribute - The buffer attribute.
  52988. */
  52989. createIndirectStorageAttribute( attribute ) {
  52990. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  52991. }
  52992. /**
  52993. * Updates the GPU buffer of a shader attribute.
  52994. *
  52995. * @param {BufferAttribute} attribute - The buffer attribute to update.
  52996. */
  52997. updateAttribute( attribute ) {
  52998. this.attributeUtils.updateAttribute( attribute );
  52999. }
  53000. /**
  53001. * Destroys the GPU buffer of a shader attribute.
  53002. *
  53003. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  53004. */
  53005. destroyAttribute( attribute ) {
  53006. this.attributeUtils.destroyAttribute( attribute );
  53007. }
  53008. // canvas
  53009. /**
  53010. * Triggers an update of the default render pass descriptor.
  53011. */
  53012. updateSize() {
  53013. this.colorBuffer = this.textureUtils.getColorBuffer();
  53014. this.defaultRenderPassdescriptor = null;
  53015. }
  53016. // utils public
  53017. /**
  53018. * Returns the maximum anisotropy texture filtering value.
  53019. *
  53020. * @return {number} The maximum anisotropy texture filtering value.
  53021. */
  53022. getMaxAnisotropy() {
  53023. return 16;
  53024. }
  53025. /**
  53026. * Checks if the given feature is supported by the backend.
  53027. *
  53028. * @param {string} name - The feature's name.
  53029. * @return {boolean} Whether the feature is supported or not.
  53030. */
  53031. hasFeature( name ) {
  53032. return this.device.features.has( name );
  53033. }
  53034. /**
  53035. * Copies data of the given source texture to the given destination texture.
  53036. *
  53037. * @param {Texture} srcTexture - The source texture.
  53038. * @param {Texture} dstTexture - The destination texture.
  53039. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  53040. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  53041. * @param {number} [srcLevel=0] - The mipmap level to copy.
  53042. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  53043. */
  53044. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  53045. let dstX = 0;
  53046. let dstY = 0;
  53047. let dstZ = 0;
  53048. let srcX = 0;
  53049. let srcY = 0;
  53050. let srcZ = 0;
  53051. let srcWidth = srcTexture.image.width;
  53052. let srcHeight = srcTexture.image.height;
  53053. let srcDepth = 1;
  53054. if ( srcRegion !== null ) {
  53055. if ( srcRegion.isBox3 === true ) {
  53056. srcX = srcRegion.min.x;
  53057. srcY = srcRegion.min.y;
  53058. srcZ = srcRegion.min.z;
  53059. srcWidth = srcRegion.max.x - srcRegion.min.x;
  53060. srcHeight = srcRegion.max.y - srcRegion.min.y;
  53061. srcDepth = srcRegion.max.z - srcRegion.min.z;
  53062. } else {
  53063. // Assume it's a Box2
  53064. srcX = srcRegion.min.x;
  53065. srcY = srcRegion.min.y;
  53066. srcWidth = srcRegion.max.x - srcRegion.min.x;
  53067. srcHeight = srcRegion.max.y - srcRegion.min.y;
  53068. srcDepth = 1;
  53069. }
  53070. }
  53071. if ( dstPosition !== null ) {
  53072. dstX = dstPosition.x;
  53073. dstY = dstPosition.y;
  53074. dstZ = dstPosition.z || 0;
  53075. }
  53076. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  53077. const sourceGPU = this.get( srcTexture ).texture;
  53078. const destinationGPU = this.get( dstTexture ).texture;
  53079. encoder.copyTextureToTexture(
  53080. {
  53081. texture: sourceGPU,
  53082. mipLevel: srcLevel,
  53083. origin: { x: srcX, y: srcY, z: srcZ }
  53084. },
  53085. {
  53086. texture: destinationGPU,
  53087. mipLevel: dstLevel,
  53088. origin: { x: dstX, y: dstY, z: dstZ }
  53089. },
  53090. [
  53091. srcWidth,
  53092. srcHeight,
  53093. srcDepth
  53094. ]
  53095. );
  53096. this.device.queue.submit( [ encoder.finish() ] );
  53097. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  53098. this.textureUtils.generateMipmaps( dstTexture );
  53099. }
  53100. }
  53101. /**
  53102. * Copies the current bound framebuffer to the given texture.
  53103. *
  53104. * @param {Texture} texture - The destination texture.
  53105. * @param {RenderContext} renderContext - The render context.
  53106. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  53107. */
  53108. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  53109. const renderContextData = this.get( renderContext );
  53110. let sourceGPU = null;
  53111. if ( renderContext.renderTarget ) {
  53112. if ( texture.isDepthTexture ) {
  53113. sourceGPU = this.get( renderContext.depthTexture ).texture;
  53114. } else {
  53115. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  53116. }
  53117. } else {
  53118. if ( texture.isDepthTexture ) {
  53119. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  53120. } else {
  53121. sourceGPU = this.context.getCurrentTexture();
  53122. }
  53123. }
  53124. const destinationGPU = this.get( texture ).texture;
  53125. if ( sourceGPU.format !== destinationGPU.format ) {
  53126. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  53127. return;
  53128. }
  53129. let encoder;
  53130. if ( renderContextData.currentPass ) {
  53131. renderContextData.currentPass.end();
  53132. encoder = renderContextData.encoder;
  53133. } else {
  53134. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  53135. }
  53136. encoder.copyTextureToTexture(
  53137. {
  53138. texture: sourceGPU,
  53139. origin: [ rectangle.x, rectangle.y, 0 ],
  53140. },
  53141. {
  53142. texture: destinationGPU
  53143. },
  53144. [
  53145. rectangle.z,
  53146. rectangle.w
  53147. ]
  53148. );
  53149. if ( renderContextData.currentPass ) {
  53150. const { descriptor } = renderContextData;
  53151. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  53152. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  53153. }
  53154. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53155. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53156. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  53157. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53158. if ( renderContext.viewport ) {
  53159. this.updateViewport( renderContext );
  53160. }
  53161. if ( renderContext.scissor ) {
  53162. const { x, y, width, height } = renderContext.scissorValue;
  53163. renderContextData.currentPass.setScissorRect( x, y, width, height );
  53164. }
  53165. } else {
  53166. this.device.queue.submit( [ encoder.finish() ] );
  53167. }
  53168. if ( texture.generateMipmaps ) {
  53169. this.textureUtils.generateMipmaps( texture );
  53170. }
  53171. }
  53172. }
  53173. /**
  53174. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  53175. *
  53176. * @augments SpotLight
  53177. */
  53178. class IESSpotLight extends SpotLight {
  53179. /**
  53180. * Constructs a new IES spot light.
  53181. *
  53182. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  53183. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  53184. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  53185. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  53186. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  53187. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  53188. */
  53189. constructor( color, intensity, distance, angle, penumbra, decay ) {
  53190. super( color, intensity, distance, angle, penumbra, decay );
  53191. /**
  53192. * TODO
  53193. *
  53194. * @type {?Texture}
  53195. * @default null
  53196. */
  53197. this.iesMap = null;
  53198. }
  53199. copy( source, recursive ) {
  53200. super.copy( source, recursive );
  53201. this.iesMap = source.iesMap;
  53202. return this;
  53203. }
  53204. }
  53205. /**
  53206. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  53207. *
  53208. * @augments SpotLight
  53209. */
  53210. class ProjectorLight extends SpotLight {
  53211. /**
  53212. * Constructs a new projector light.
  53213. *
  53214. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  53215. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  53216. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  53217. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  53218. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  53219. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  53220. */
  53221. constructor( color, intensity, distance, angle, penumbra, decay ) {
  53222. super( color, intensity, distance, angle, penumbra, decay );
  53223. /**
  53224. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  53225. *
  53226. * @type {number}
  53227. * @default null
  53228. */
  53229. this.aspect = null;
  53230. }
  53231. copy( source, recursive ) {
  53232. super.copy( source, recursive );
  53233. this.aspect = source.aspect;
  53234. return this;
  53235. }
  53236. }
  53237. /**
  53238. * This version of a node library represents the standard version
  53239. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  53240. * techniques and materials to node-based implementations.
  53241. *
  53242. * @private
  53243. * @augments NodeLibrary
  53244. */
  53245. class StandardNodeLibrary extends NodeLibrary {
  53246. /**
  53247. * Constructs a new standard node library.
  53248. */
  53249. constructor() {
  53250. super();
  53251. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  53252. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  53253. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  53254. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  53255. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  53256. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  53257. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  53258. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  53259. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  53260. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  53261. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  53262. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  53263. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  53264. this.addLight( PointLightNode, PointLight );
  53265. this.addLight( DirectionalLightNode, DirectionalLight );
  53266. this.addLight( RectAreaLightNode, RectAreaLight );
  53267. this.addLight( SpotLightNode, SpotLight );
  53268. this.addLight( AmbientLightNode, AmbientLight );
  53269. this.addLight( HemisphereLightNode, HemisphereLight );
  53270. this.addLight( LightProbeNode, LightProbe );
  53271. this.addLight( IESSpotLightNode, IESSpotLight );
  53272. this.addLight( ProjectorLightNode, ProjectorLight );
  53273. this.addToneMapping( linearToneMapping, LinearToneMapping );
  53274. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  53275. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  53276. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  53277. this.addToneMapping( agxToneMapping, AgXToneMapping );
  53278. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  53279. }
  53280. }
  53281. /*
  53282. const debugHandler = {
  53283. get: function ( target, name ) {
  53284. // Add |update
  53285. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  53286. return target[ name ];
  53287. }
  53288. };
  53289. */
  53290. /**
  53291. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  53292. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  53293. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  53294. *
  53295. * @augments Renderer
  53296. */
  53297. class WebGPURenderer extends Renderer {
  53298. /**
  53299. * WebGPURenderer options.
  53300. *
  53301. * @typedef {Object} WebGPURenderer~Options
  53302. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  53303. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  53304. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  53305. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  53306. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  53307. * @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.
  53308. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  53309. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  53310. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  53311. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  53312. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  53313. */
  53314. /**
  53315. * Constructs a new WebGPU renderer.
  53316. *
  53317. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  53318. */
  53319. constructor( parameters = {} ) {
  53320. let BackendClass;
  53321. if ( parameters.forceWebGL ) {
  53322. BackendClass = WebGLBackend;
  53323. } else {
  53324. BackendClass = WebGPUBackend;
  53325. parameters.getFallback = () => {
  53326. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  53327. return new WebGLBackend( parameters );
  53328. };
  53329. }
  53330. const backend = new BackendClass( parameters );
  53331. //super( new Proxy( backend, debugHandler ) );
  53332. super( backend, parameters );
  53333. /**
  53334. * The generic default value is overwritten with the
  53335. * standard node library for type mapping.
  53336. *
  53337. * @type {StandardNodeLibrary}
  53338. */
  53339. this.library = new StandardNodeLibrary();
  53340. /**
  53341. * This flag can be used for type testing.
  53342. *
  53343. * @type {boolean}
  53344. * @readonly
  53345. * @default true
  53346. */
  53347. this.isWebGPURenderer = true;
  53348. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  53349. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  53350. }
  53351. }
  53352. }
  53353. /**
  53354. * A specialized group which enables applications access to the
  53355. * Render Bundle API of WebGPU. The group with all its descendant nodes
  53356. * are considered as one render bundle and processed as such by
  53357. * the renderer.
  53358. *
  53359. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  53360. * With a WebGL backend, the group can technically be rendered but without
  53361. * any performance improvements.
  53362. *
  53363. * @augments Group
  53364. */
  53365. class BundleGroup extends Group {
  53366. /**
  53367. * Constructs a new bundle group.
  53368. */
  53369. constructor() {
  53370. super();
  53371. /**
  53372. * This flag can be used for type testing.
  53373. *
  53374. * @type {boolean}
  53375. * @readonly
  53376. * @default true
  53377. */
  53378. this.isBundleGroup = true;
  53379. /**
  53380. * This property is only relevant for detecting types
  53381. * during serialization/deserialization. It should always
  53382. * match the class name.
  53383. *
  53384. * @type {string}
  53385. * @readonly
  53386. * @default 'BundleGroup'
  53387. */
  53388. this.type = 'BundleGroup';
  53389. /**
  53390. * Whether the bundle is static or not. When set to `true`, the structure
  53391. * is assumed to be static and does not change. E.g. no new objects are
  53392. * added to the group
  53393. *
  53394. * If a change is required, an update can still be forced by setting the
  53395. * `needsUpdate` flag to `true`.
  53396. *
  53397. * @type {boolean}
  53398. * @default true
  53399. */
  53400. this.static = true;
  53401. /**
  53402. * The bundle group's version.
  53403. *
  53404. * @type {number}
  53405. * @readonly
  53406. * @default 0
  53407. */
  53408. this.version = 0;
  53409. }
  53410. /**
  53411. * Set this property to `true` when the bundle group has changed.
  53412. *
  53413. * @type {boolean}
  53414. * @default false
  53415. * @param {boolean} value
  53416. */
  53417. set needsUpdate( value ) {
  53418. if ( value === true ) this.version ++;
  53419. }
  53420. }
  53421. /**
  53422. * This module is responsible to manage the post processing setups in apps.
  53423. * You usually create a single instance of this class and use it to define
  53424. * the output of your post processing effect chain.
  53425. * ```js
  53426. * const postProcessing = new PostProcessing( renderer );
  53427. *
  53428. * const scenePass = pass( scene, camera );
  53429. *
  53430. * postProcessing.outputNode = scenePass;
  53431. * ```
  53432. *
  53433. * Note: This module can only be used with `WebGPURenderer`.
  53434. */
  53435. class PostProcessing {
  53436. /**
  53437. * Constructs a new post processing management module.
  53438. *
  53439. * @param {Renderer} renderer - A reference to the renderer.
  53440. * @param {Node<vec4>} outputNode - An optional output node.
  53441. */
  53442. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  53443. /**
  53444. * A reference to the renderer.
  53445. *
  53446. * @type {Renderer}
  53447. */
  53448. this.renderer = renderer;
  53449. /**
  53450. * A node which defines the final output of the post
  53451. * processing. This is usually the last node in a chain
  53452. * of effect nodes.
  53453. *
  53454. * @type {Node<vec4>}
  53455. */
  53456. this.outputNode = outputNode;
  53457. /**
  53458. * Whether the default output tone mapping and color
  53459. * space transformation should be enabled or not.
  53460. *
  53461. * It is enabled by default by it must be disabled when
  53462. * effects must be executed after tone mapping and color
  53463. * space conversion. A typical example is FXAA which
  53464. * requires sRGB input.
  53465. *
  53466. * When set to `false`, the app must control the output
  53467. * transformation with `RenderOutputNode`.
  53468. *
  53469. * ```js
  53470. * const outputPass = renderOutput( scenePass );
  53471. * ```
  53472. *
  53473. * @type {boolean}
  53474. */
  53475. this.outputColorTransform = true;
  53476. /**
  53477. * Must be set to `true` when the output node changes.
  53478. *
  53479. * @type {Node<vec4>}
  53480. */
  53481. this.needsUpdate = true;
  53482. const material = new NodeMaterial();
  53483. material.name = 'PostProcessing';
  53484. /**
  53485. * The full screen quad that is used to render
  53486. * the effects.
  53487. *
  53488. * @private
  53489. * @type {QuadMesh}
  53490. */
  53491. this._quadMesh = new QuadMesh( material );
  53492. /**
  53493. * The context of the post processing stack.
  53494. *
  53495. * @private
  53496. * @type {?Object}
  53497. * @default null
  53498. */
  53499. this._context = null;
  53500. }
  53501. /**
  53502. * When `PostProcessing` is used to apply post processing effects,
  53503. * the application must use this version of `render()` inside
  53504. * its animation loop (not the one from the renderer).
  53505. */
  53506. render() {
  53507. const renderer = this.renderer;
  53508. this._update();
  53509. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  53510. const toneMapping = renderer.toneMapping;
  53511. const outputColorSpace = renderer.outputColorSpace;
  53512. renderer.toneMapping = NoToneMapping;
  53513. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  53514. //
  53515. const currentXR = renderer.xr.enabled;
  53516. renderer.xr.enabled = false;
  53517. this._quadMesh.render( renderer );
  53518. renderer.xr.enabled = currentXR;
  53519. //
  53520. renderer.toneMapping = toneMapping;
  53521. renderer.outputColorSpace = outputColorSpace;
  53522. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  53523. }
  53524. /**
  53525. * Returns the current context of the post processing stack.
  53526. *
  53527. * @readonly
  53528. * @type {?Object}
  53529. */
  53530. get context() {
  53531. return this._context;
  53532. }
  53533. /**
  53534. * Frees internal resources.
  53535. */
  53536. dispose() {
  53537. this._quadMesh.material.dispose();
  53538. }
  53539. /**
  53540. * Updates the state of the module.
  53541. *
  53542. * @private
  53543. */
  53544. _update() {
  53545. if ( this.needsUpdate === true ) {
  53546. const renderer = this.renderer;
  53547. const toneMapping = renderer.toneMapping;
  53548. const outputColorSpace = renderer.outputColorSpace;
  53549. const context = {
  53550. postProcessing: this,
  53551. onBeforePostProcessing: null,
  53552. onAfterPostProcessing: null
  53553. };
  53554. let outputNode = this.outputNode;
  53555. if ( this.outputColorTransform === true ) {
  53556. outputNode = outputNode.context( context );
  53557. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  53558. } else {
  53559. context.toneMapping = toneMapping;
  53560. context.outputColorSpace = outputColorSpace;
  53561. outputNode = outputNode.context( context );
  53562. }
  53563. this._context = context;
  53564. this._quadMesh.material.fragmentNode = outputNode;
  53565. this._quadMesh.material.needsUpdate = true;
  53566. this.needsUpdate = false;
  53567. }
  53568. }
  53569. /**
  53570. * When `PostProcessing` is used to apply post processing effects,
  53571. * the application must use this version of `renderAsync()` inside
  53572. * its animation loop (not the one from the renderer).
  53573. *
  53574. * @async
  53575. * @return {Promise} A Promise that resolves when the render has been finished.
  53576. */
  53577. async renderAsync() {
  53578. this._update();
  53579. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  53580. const renderer = this.renderer;
  53581. const toneMapping = renderer.toneMapping;
  53582. const outputColorSpace = renderer.outputColorSpace;
  53583. renderer.toneMapping = NoToneMapping;
  53584. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  53585. //
  53586. const currentXR = renderer.xr.enabled;
  53587. renderer.xr.enabled = false;
  53588. await this._quadMesh.renderAsync( renderer );
  53589. renderer.xr.enabled = currentXR;
  53590. //
  53591. renderer.toneMapping = toneMapping;
  53592. renderer.outputColorSpace = outputColorSpace;
  53593. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  53594. }
  53595. }
  53596. /**
  53597. * This special type of texture is intended for compute shaders.
  53598. * It can be used to compute the data of a texture with a compute shader.
  53599. *
  53600. * Note: This type of texture can only be used with `WebGPURenderer`
  53601. * and a WebGPU backend.
  53602. *
  53603. * @augments Texture
  53604. */
  53605. class StorageTexture extends Texture {
  53606. /**
  53607. * Constructs a new storage texture.
  53608. *
  53609. * @param {number} [width=1] - The storage texture's width.
  53610. * @param {number} [height=1] - The storage texture's height.
  53611. */
  53612. constructor( width = 1, height = 1 ) {
  53613. super();
  53614. /**
  53615. * The image object which just represents the texture's dimension.
  53616. *
  53617. * @type {{width: number, height: number}}
  53618. */
  53619. this.image = { width, height };
  53620. /**
  53621. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  53622. *
  53623. * @type {number}
  53624. */
  53625. this.magFilter = LinearFilter;
  53626. /**
  53627. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  53628. *
  53629. * @type {number}
  53630. */
  53631. this.minFilter = LinearFilter;
  53632. /**
  53633. * This flag can be used for type testing.
  53634. *
  53635. * @type {boolean}
  53636. * @readonly
  53637. * @default true
  53638. */
  53639. this.isStorageTexture = true;
  53640. }
  53641. /**
  53642. * Sets the size of the storage texture.
  53643. *
  53644. * @param {number} width - The new width of the storage texture.
  53645. * @param {number} height - The new height of the storage texture.
  53646. */
  53647. setSize( width, height ) {
  53648. if ( this.image.width !== width || this.image.height !== height ) {
  53649. this.image.width = width;
  53650. this.image.height = height;
  53651. this.dispose();
  53652. }
  53653. }
  53654. }
  53655. /**
  53656. * This special type of texture is intended for compute shaders.
  53657. * It can be used to compute the data of a texture with a compute shader.
  53658. *
  53659. * Note: This type of texture can only be used with `WebGPURenderer`
  53660. * and a WebGPU backend.
  53661. *
  53662. * @augments Texture
  53663. */
  53664. class Storage3DTexture extends Texture {
  53665. /**
  53666. * Constructs a new storage texture.
  53667. *
  53668. * @param {number} [width=1] - The storage texture's width.
  53669. * @param {number} [height=1] - The storage texture's height.
  53670. * @param {number} [depth=1] - The storage texture's depth.
  53671. */
  53672. constructor( width = 1, height = 1, depth = 1 ) {
  53673. super();
  53674. //inherited from texture. Must be false for 3DTexture
  53675. this.isArrayTexture = false;
  53676. /**
  53677. * The image object which just represents the texture's dimension.
  53678. *
  53679. * @type {{width: number, height: number, depth: number}}
  53680. */
  53681. this.image = { width, height, depth };
  53682. /**
  53683. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  53684. *
  53685. * @type {number}
  53686. */
  53687. this.magFilter = LinearFilter;
  53688. /**
  53689. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  53690. *
  53691. * @type {number}
  53692. */
  53693. this.minFilter = LinearFilter;
  53694. /**
  53695. * This defines how the texture is wrapped in the depth direction and corresponds to
  53696. * *W* in UVW mapping.
  53697. *
  53698. * @type {number}
  53699. */
  53700. this.wrapR = ClampToEdgeWrapping;
  53701. /**
  53702. * This flag can be used for type testing.
  53703. *
  53704. * @type {boolean}
  53705. * @readonly
  53706. * @default true
  53707. */
  53708. this.isStorageTexture = true;
  53709. /**
  53710. * Indicates whether this texture is a 3D texture.
  53711. *
  53712. * @type {boolean}
  53713. *
  53714. */
  53715. this.is3DTexture = true;
  53716. }
  53717. /**
  53718. * Sets the size of the storage 3d texture.
  53719. *
  53720. * @param {number} width - The new width of the storage texture.
  53721. * @param {number} height - The new height of the storage texture.
  53722. * @param {number} depth - The new depth of the storage texture.
  53723. */
  53724. setSize( width, height, depth ) {
  53725. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  53726. this.image.width = width;
  53727. this.image.height = height;
  53728. this.image.depth = depth;
  53729. this.dispose();
  53730. }
  53731. }
  53732. }
  53733. /**
  53734. * This special type of texture is intended for compute shaders.
  53735. * It can be used to compute the data of a texture with a compute shader.
  53736. *
  53737. * Note: This type of texture can only be used with `WebGPURenderer`
  53738. * and a WebGPU backend.
  53739. *
  53740. * @augments Texture
  53741. */
  53742. class StorageArrayTexture extends Texture {
  53743. /**
  53744. * Constructs a new storage texture.
  53745. *
  53746. * @param {number} [width=1] - The storage texture's width.
  53747. * @param {number} [height=1] - The storage texture's height.
  53748. * @param {number} [depth=1] - The storage texture's depth.
  53749. */
  53750. constructor( width = 1, height = 1, depth = 1 ) {
  53751. super();
  53752. //inherited from texture
  53753. this.isArrayTexture = true;
  53754. /**
  53755. * The image object which just represents the texture's dimension.
  53756. *
  53757. * @type {{width: number, height: number, depth: number}}
  53758. */
  53759. this.image = { width, height, depth };
  53760. /**
  53761. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  53762. *
  53763. * @type {number}
  53764. */
  53765. this.magFilter = LinearFilter;
  53766. /**
  53767. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  53768. *
  53769. * @type {number}
  53770. */
  53771. this.minFilter = LinearFilter;
  53772. /**
  53773. * This flag can be used for type testing.
  53774. *
  53775. * @type {boolean}
  53776. * @readonly
  53777. * @default true
  53778. */
  53779. this.isStorageTexture = true;
  53780. }
  53781. /**
  53782. * Sets the size of the storage array texture.
  53783. *
  53784. * @param {number} width - The new width of the storage texture.
  53785. * @param {number} height - The new height of the storage texture.
  53786. * @param {number} depth - The new depth of the storage texture.
  53787. */
  53788. setSize( width, height, depth ) {
  53789. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  53790. this.image.width = width;
  53791. this.image.height = height;
  53792. this.image.depth = depth;
  53793. this.dispose();
  53794. }
  53795. }
  53796. }
  53797. /**
  53798. * This special type of buffer attribute is intended for compute shaders.
  53799. * It can be used to encode draw parameters for indirect draw calls.
  53800. *
  53801. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  53802. * and a WebGPU backend.
  53803. *
  53804. * @augments StorageBufferAttribute
  53805. */
  53806. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  53807. /**
  53808. * Constructs a new storage buffer attribute.
  53809. *
  53810. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  53811. * The subsequent parameter is then obsolete.
  53812. * @param {number} itemSize - The item size.
  53813. */
  53814. constructor( count, itemSize ) {
  53815. super( count, itemSize, Uint32Array );
  53816. /**
  53817. * This flag can be used for type testing.
  53818. *
  53819. * @type {boolean}
  53820. * @readonly
  53821. * @default true
  53822. */
  53823. this.isIndirectStorageBufferAttribute = true;
  53824. }
  53825. }
  53826. /**
  53827. * A loader for loading node objects in the three.js JSON Object/Scene format.
  53828. *
  53829. * @augments Loader
  53830. */
  53831. class NodeLoader extends Loader {
  53832. /**
  53833. * Constructs a new node loader.
  53834. *
  53835. * @param {LoadingManager} [manager] - A reference to a loading manager.
  53836. */
  53837. constructor( manager ) {
  53838. super( manager );
  53839. /**
  53840. * Represents a dictionary of textures.
  53841. *
  53842. * @type {Object<string,Texture>}
  53843. */
  53844. this.textures = {};
  53845. /**
  53846. * Represents a dictionary of node types.
  53847. *
  53848. * @type {Object<string,Node.constructor>}
  53849. */
  53850. this.nodes = {};
  53851. }
  53852. /**
  53853. * Loads the node definitions from the given URL.
  53854. *
  53855. * @param {string} url - The path/URL of the file to be loaded.
  53856. * @param {Function} onLoad - Will be called when load completes.
  53857. * @param {Function} onProgress - Will be called while load progresses.
  53858. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  53859. */
  53860. load( url, onLoad, onProgress, onError ) {
  53861. const loader = new FileLoader( this.manager );
  53862. loader.setPath( this.path );
  53863. loader.setRequestHeader( this.requestHeader );
  53864. loader.setWithCredentials( this.withCredentials );
  53865. loader.load( url, ( text ) => {
  53866. try {
  53867. onLoad( this.parse( JSON.parse( text ) ) );
  53868. } catch ( e ) {
  53869. if ( onError ) {
  53870. onError( e );
  53871. } else {
  53872. console.error( e );
  53873. }
  53874. this.manager.itemError( url );
  53875. }
  53876. }, onProgress, onError );
  53877. }
  53878. /**
  53879. * Parse the node dependencies for the loaded node.
  53880. *
  53881. * @param {Array<Object>} [json] - The JSON definition
  53882. * @return {Object<string,Node>} A dictionary with node dependencies.
  53883. */
  53884. parseNodes( json ) {
  53885. const nodes = {};
  53886. if ( json !== undefined ) {
  53887. for ( const nodeJSON of json ) {
  53888. const { uuid, type } = nodeJSON;
  53889. nodes[ uuid ] = this.createNodeFromType( type );
  53890. nodes[ uuid ].uuid = uuid;
  53891. }
  53892. const meta = { nodes, textures: this.textures };
  53893. for ( const nodeJSON of json ) {
  53894. nodeJSON.meta = meta;
  53895. const node = nodes[ nodeJSON.uuid ];
  53896. node.deserialize( nodeJSON );
  53897. delete nodeJSON.meta;
  53898. }
  53899. }
  53900. return nodes;
  53901. }
  53902. /**
  53903. * Parses the node from the given JSON.
  53904. *
  53905. * @param {Object} json - The JSON definition
  53906. * @param {string} json.type - The node type.
  53907. * @param {string} json.uuid - The node UUID.
  53908. * @param {Array<Object>} [json.nodes] - The node dependencies.
  53909. * @param {Object} [json.meta] - The meta data.
  53910. * @return {Node} The parsed node.
  53911. */
  53912. parse( json ) {
  53913. const node = this.createNodeFromType( json.type );
  53914. node.uuid = json.uuid;
  53915. const nodes = this.parseNodes( json.nodes );
  53916. const meta = { nodes, textures: this.textures };
  53917. json.meta = meta;
  53918. node.deserialize( json );
  53919. delete json.meta;
  53920. return node;
  53921. }
  53922. /**
  53923. * Defines the dictionary of textures.
  53924. *
  53925. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  53926. * @return {NodeLoader} A reference to this loader.
  53927. */
  53928. setTextures( value ) {
  53929. this.textures = value;
  53930. return this;
  53931. }
  53932. /**
  53933. * Defines the dictionary of node types.
  53934. *
  53935. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  53936. * @return {NodeLoader} A reference to this loader.
  53937. */
  53938. setNodes( value ) {
  53939. this.nodes = value;
  53940. return this;
  53941. }
  53942. /**
  53943. * Creates a node object from the given type.
  53944. *
  53945. * @param {string} type - The node type.
  53946. * @return {Node} The created node instance.
  53947. */
  53948. createNodeFromType( type ) {
  53949. if ( this.nodes[ type ] === undefined ) {
  53950. console.error( 'THREE.NodeLoader: Node type not found:', type );
  53951. return float();
  53952. }
  53953. return nodeObject( new this.nodes[ type ]() );
  53954. }
  53955. }
  53956. /**
  53957. * A special type of material loader for loading node materials.
  53958. *
  53959. * @augments MaterialLoader
  53960. */
  53961. class NodeMaterialLoader extends MaterialLoader {
  53962. /**
  53963. * Constructs a new node material loader.
  53964. *
  53965. * @param {LoadingManager} [manager] - A reference to a loading manager.
  53966. */
  53967. constructor( manager ) {
  53968. super( manager );
  53969. /**
  53970. * Represents a dictionary of node types.
  53971. *
  53972. * @type {Object<string,Node.constructor>}
  53973. */
  53974. this.nodes = {};
  53975. /**
  53976. * Represents a dictionary of node material types.
  53977. *
  53978. * @type {Object<string,NodeMaterial.constructor>}
  53979. */
  53980. this.nodeMaterials = {};
  53981. }
  53982. /**
  53983. * Parses the node material from the given JSON.
  53984. *
  53985. * @param {Object} json - The JSON definition
  53986. * @return {NodeMaterial}. The parsed material.
  53987. */
  53988. parse( json ) {
  53989. const material = super.parse( json );
  53990. const nodes = this.nodes;
  53991. const inputNodes = json.inputNodes;
  53992. for ( const property in inputNodes ) {
  53993. const uuid = inputNodes[ property ];
  53994. material[ property ] = nodes[ uuid ];
  53995. }
  53996. return material;
  53997. }
  53998. /**
  53999. * Defines the dictionary of node types.
  54000. *
  54001. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54002. * @return {NodeLoader} A reference to this loader.
  54003. */
  54004. setNodes( value ) {
  54005. this.nodes = value;
  54006. return this;
  54007. }
  54008. /**
  54009. * Defines the dictionary of node material types.
  54010. *
  54011. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  54012. * @return {NodeLoader} A reference to this loader.
  54013. */
  54014. setNodeMaterials( value ) {
  54015. this.nodeMaterials = value;
  54016. return this;
  54017. }
  54018. /**
  54019. * Creates a node material from the given type.
  54020. *
  54021. * @param {string} type - The node material type.
  54022. * @return {Node} The created node material instance.
  54023. */
  54024. createMaterialFromType( type ) {
  54025. const materialClass = this.nodeMaterials[ type ];
  54026. if ( materialClass !== undefined ) {
  54027. return new materialClass();
  54028. }
  54029. return super.createMaterialFromType( type );
  54030. }
  54031. }
  54032. /**
  54033. * A special type of object loader for loading 3D objects using
  54034. * node materials.
  54035. *
  54036. * @augments ObjectLoader
  54037. */
  54038. class NodeObjectLoader extends ObjectLoader {
  54039. /**
  54040. * Constructs a new node object loader.
  54041. *
  54042. * @param {LoadingManager} [manager] - A reference to a loading manager.
  54043. */
  54044. constructor( manager ) {
  54045. super( manager );
  54046. /**
  54047. * Represents a dictionary of node types.
  54048. *
  54049. * @type {Object<string,Node.constructor>}
  54050. */
  54051. this.nodes = {};
  54052. /**
  54053. * Represents a dictionary of node material types.
  54054. *
  54055. * @type {Object<string,NodeMaterial.constructor>}
  54056. */
  54057. this.nodeMaterials = {};
  54058. /**
  54059. * A reference to hold the `nodes` JSON property.
  54060. *
  54061. * @private
  54062. * @type {?Object[]}
  54063. */
  54064. this._nodesJSON = null;
  54065. }
  54066. /**
  54067. * Defines the dictionary of node types.
  54068. *
  54069. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54070. * @return {NodeObjectLoader} A reference to this loader.
  54071. */
  54072. setNodes( value ) {
  54073. this.nodes = value;
  54074. return this;
  54075. }
  54076. /**
  54077. * Defines the dictionary of node material types.
  54078. *
  54079. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  54080. * @return {NodeObjectLoader} A reference to this loader.
  54081. */
  54082. setNodeMaterials( value ) {
  54083. this.nodeMaterials = value;
  54084. return this;
  54085. }
  54086. /**
  54087. * Parses the node objects from the given JSON.
  54088. *
  54089. * @param {Object} json - The JSON definition
  54090. * @param {Function} onLoad - The onLoad callback function.
  54091. * @return {Object3D}. The parsed 3D object.
  54092. */
  54093. parse( json, onLoad ) {
  54094. this._nodesJSON = json.nodes;
  54095. const data = super.parse( json, onLoad );
  54096. this._nodesJSON = null; // dispose
  54097. return data;
  54098. }
  54099. /**
  54100. * Parses the node objects from the given JSON and textures.
  54101. *
  54102. * @param {Object[]} json - The JSON definition
  54103. * @param {Object<string,Texture>} textures - The texture library.
  54104. * @return {Object<string,Node>}. The parsed nodes.
  54105. */
  54106. parseNodes( json, textures ) {
  54107. if ( json !== undefined ) {
  54108. const loader = new NodeLoader();
  54109. loader.setNodes( this.nodes );
  54110. loader.setTextures( textures );
  54111. return loader.parseNodes( json );
  54112. }
  54113. return {};
  54114. }
  54115. /**
  54116. * Parses the node objects from the given JSON and textures.
  54117. *
  54118. * @param {Object} json - The JSON definition
  54119. * @param {Object<string,Texture>} textures - The texture library.
  54120. * @return {Object<string,NodeMaterial>}. The parsed materials.
  54121. */
  54122. parseMaterials( json, textures ) {
  54123. const materials = {};
  54124. if ( json !== undefined ) {
  54125. const nodes = this.parseNodes( this._nodesJSON, textures );
  54126. const loader = new NodeMaterialLoader();
  54127. loader.setTextures( textures );
  54128. loader.setNodes( nodes );
  54129. loader.setNodeMaterials( this.nodeMaterials );
  54130. for ( let i = 0, l = json.length; i < l; i ++ ) {
  54131. const data = json[ i ];
  54132. materials[ data.uuid ] = loader.parse( data );
  54133. }
  54134. }
  54135. return materials;
  54136. }
  54137. }
  54138. /**
  54139. * In earlier three.js versions, clipping was defined globally
  54140. * on the renderer or on material level. This special version of
  54141. * `THREE.Group` allows to encode the clipping state into the scene
  54142. * graph. Meaning if you create an instance of this group, all
  54143. * descendant 3D objects will be affected by the respective clipping
  54144. * planes.
  54145. *
  54146. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  54147. *
  54148. * @augments Group
  54149. */
  54150. class ClippingGroup extends Group {
  54151. /**
  54152. * Constructs a new clipping group.
  54153. */
  54154. constructor() {
  54155. super();
  54156. /**
  54157. * This flag can be used for type testing.
  54158. *
  54159. * @type {boolean}
  54160. * @readonly
  54161. * @default true
  54162. */
  54163. this.isClippingGroup = true;
  54164. /**
  54165. * An array with clipping planes.
  54166. *
  54167. * @type {Array<Plane>}
  54168. */
  54169. this.clippingPlanes = [];
  54170. /**
  54171. * Whether clipping should be enabled or not.
  54172. *
  54173. * @type {boolean}
  54174. * @default true
  54175. */
  54176. this.enabled = true;
  54177. /**
  54178. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  54179. *
  54180. * @type {boolean}
  54181. * @default false
  54182. */
  54183. this.clipIntersection = false;
  54184. /**
  54185. * Whether shadows should be clipped or not.
  54186. *
  54187. * @type {boolean}
  54188. * @default false
  54189. */
  54190. this.clipShadows = false;
  54191. }
  54192. }
  54193. 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, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号