three.webgpu.js 1.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385
  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, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, 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. /**
  1801. * Returns the scope of the node.
  1802. *
  1803. * @return {Node} The scope of the node.
  1804. */
  1805. getScope() {
  1806. return this.node.getScope();
  1807. }
  1808. generate( builder, output ) {
  1809. const node = this.node;
  1810. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1811. let snippet = null;
  1812. if ( nodeTypeLength > 1 ) {
  1813. let type = null;
  1814. const componentsLength = this.getVectorLength();
  1815. if ( componentsLength >= nodeTypeLength ) {
  1816. // needed expand the input node
  1817. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1818. }
  1819. const nodeSnippet = node.build( builder, type );
  1820. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1821. // unnecessary swizzle
  1822. snippet = builder.format( nodeSnippet, type, output );
  1823. } else {
  1824. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1825. }
  1826. } else {
  1827. // ignore .components if .node returns float/integer
  1828. snippet = node.build( builder, output );
  1829. }
  1830. return snippet;
  1831. }
  1832. serialize( data ) {
  1833. super.serialize( data );
  1834. data.components = this.components;
  1835. }
  1836. deserialize( data ) {
  1837. super.deserialize( data );
  1838. this.components = data.components;
  1839. }
  1840. }
  1841. /**
  1842. * This module is part of the TSL core and usually not used in app level code.
  1843. * `SetNode` represents a set operation which means it is used to implement any
  1844. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1845. * For example:
  1846. * ```js
  1847. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1848. * ```
  1849. *
  1850. * @augments TempNode
  1851. */
  1852. class SetNode extends TempNode {
  1853. static get type() {
  1854. return 'SetNode';
  1855. }
  1856. /**
  1857. * Constructs a new set node.
  1858. *
  1859. * @param {Node} sourceNode - The node that should be updated.
  1860. * @param {string} components - The components that should be updated.
  1861. * @param {Node} targetNode - The value node.
  1862. */
  1863. constructor( sourceNode, components, targetNode ) {
  1864. super();
  1865. /**
  1866. * The node that should be updated.
  1867. *
  1868. * @type {Node}
  1869. */
  1870. this.sourceNode = sourceNode;
  1871. /**
  1872. * The components that should be updated.
  1873. *
  1874. * @type {string}
  1875. */
  1876. this.components = components;
  1877. /**
  1878. * The value node.
  1879. *
  1880. * @type {Node}
  1881. */
  1882. this.targetNode = targetNode;
  1883. }
  1884. /**
  1885. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1886. *
  1887. * @param {NodeBuilder} builder - The current node builder.
  1888. * @return {string} The node type.
  1889. */
  1890. getNodeType( builder ) {
  1891. return this.sourceNode.getNodeType( builder );
  1892. }
  1893. generate( builder ) {
  1894. const { sourceNode, components, targetNode } = this;
  1895. const sourceType = this.getNodeType( builder );
  1896. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1897. const targetType = builder.getTypeFromLength( components.length, componentType );
  1898. const targetSnippet = targetNode.build( builder, targetType );
  1899. const sourceSnippet = sourceNode.build( builder, sourceType );
  1900. const length = builder.getTypeLength( sourceType );
  1901. const snippetValues = [];
  1902. for ( let i = 0; i < length; i ++ ) {
  1903. const component = vectorComponents[ i ];
  1904. if ( component === components[ 0 ] ) {
  1905. snippetValues.push( targetSnippet );
  1906. i += components.length - 1;
  1907. } else {
  1908. snippetValues.push( sourceSnippet + '.' + component );
  1909. }
  1910. }
  1911. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1912. }
  1913. }
  1914. /**
  1915. * This module is part of the TSL core and usually not used in app level code.
  1916. * It represents a flip operation during the shader generation process
  1917. * meaning it flips normalized values with the following formula:
  1918. * ```
  1919. * x = 1 - x;
  1920. * ```
  1921. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1922. * `flipSTPQ()` method invocations on node objects. For example:
  1923. * ```js
  1924. * uvNode = uvNode.flipY();
  1925. * ```
  1926. *
  1927. * @augments TempNode
  1928. */
  1929. class FlipNode extends TempNode {
  1930. static get type() {
  1931. return 'FlipNode';
  1932. }
  1933. /**
  1934. * Constructs a new flip node.
  1935. *
  1936. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1937. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1938. */
  1939. constructor( sourceNode, components ) {
  1940. super();
  1941. /**
  1942. * The node which component(s) should be flipped.
  1943. *
  1944. * @type {Node}
  1945. */
  1946. this.sourceNode = sourceNode;
  1947. /**
  1948. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1949. *
  1950. * @type {string}
  1951. */
  1952. this.components = components;
  1953. }
  1954. /**
  1955. * This method is overwritten since the node type is inferred from the source node.
  1956. *
  1957. * @param {NodeBuilder} builder - The current node builder.
  1958. * @return {string} The node type.
  1959. */
  1960. getNodeType( builder ) {
  1961. return this.sourceNode.getNodeType( builder );
  1962. }
  1963. generate( builder ) {
  1964. const { components, sourceNode } = this;
  1965. const sourceType = this.getNodeType( builder );
  1966. const sourceSnippet = sourceNode.build( builder );
  1967. const sourceCache = builder.getVarFromNode( this );
  1968. const sourceProperty = builder.getPropertyName( sourceCache );
  1969. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1970. const length = builder.getTypeLength( sourceType );
  1971. const snippetValues = [];
  1972. let componentIndex = 0;
  1973. for ( let i = 0; i < length; i ++ ) {
  1974. const component = vectorComponents[ i ];
  1975. if ( component === components[ componentIndex ] ) {
  1976. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1977. componentIndex ++;
  1978. } else {
  1979. snippetValues.push( sourceProperty + '.' + component );
  1980. }
  1981. }
  1982. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1983. }
  1984. }
  1985. /**
  1986. * Base class for representing data input nodes.
  1987. *
  1988. * @augments Node
  1989. */
  1990. class InputNode extends Node {
  1991. static get type() {
  1992. return 'InputNode';
  1993. }
  1994. /**
  1995. * Constructs a new input node.
  1996. *
  1997. * @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).
  1998. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1999. */
  2000. constructor( value, nodeType = null ) {
  2001. super( nodeType );
  2002. /**
  2003. * This flag can be used for type testing.
  2004. *
  2005. * @type {boolean}
  2006. * @readonly
  2007. * @default true
  2008. */
  2009. this.isInputNode = true;
  2010. /**
  2011. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2012. *
  2013. * @type {any}
  2014. */
  2015. this.value = value;
  2016. /**
  2017. * The precision of the value in the shader.
  2018. *
  2019. * @type {?('low'|'medium'|'high')}
  2020. * @default null
  2021. */
  2022. this.precision = null;
  2023. }
  2024. getNodeType( /*builder*/ ) {
  2025. if ( this.nodeType === null ) {
  2026. return getValueType( this.value );
  2027. }
  2028. return this.nodeType;
  2029. }
  2030. /**
  2031. * Returns the input type of the node which is by default the node type. Derived modules
  2032. * might overwrite this method and use a fixed type or compute one analytically.
  2033. *
  2034. * A typical example for different input and node types are textures. The input type of a
  2035. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2036. *
  2037. * @param {NodeBuilder} builder - The current node builder.
  2038. * @return {string} The input type.
  2039. */
  2040. getInputType( builder ) {
  2041. return this.getNodeType( builder );
  2042. }
  2043. /**
  2044. * Sets the precision to the given value. The method can be
  2045. * overwritten in derived classes if the final precision must be computed
  2046. * analytically.
  2047. *
  2048. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2049. * @return {InputNode} A reference to this node.
  2050. */
  2051. setPrecision( precision ) {
  2052. this.precision = precision;
  2053. return this;
  2054. }
  2055. serialize( data ) {
  2056. super.serialize( data );
  2057. data.value = this.value;
  2058. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2059. data.valueType = getValueType( this.value );
  2060. data.nodeType = this.nodeType;
  2061. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2062. data.precision = this.precision;
  2063. }
  2064. deserialize( data ) {
  2065. super.deserialize( data );
  2066. this.nodeType = data.nodeType;
  2067. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2068. this.precision = data.precision || null;
  2069. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2070. }
  2071. generate( /*builder, output*/ ) {
  2072. console.warn( 'Abstract function.' );
  2073. }
  2074. }
  2075. const _regNum = /float|u?int/;
  2076. /**
  2077. * Class for representing a constant value in the shader.
  2078. *
  2079. * @augments InputNode
  2080. */
  2081. class ConstNode extends InputNode {
  2082. static get type() {
  2083. return 'ConstNode';
  2084. }
  2085. /**
  2086. * Constructs a new input node.
  2087. *
  2088. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2089. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2090. */
  2091. constructor( value, nodeType = null ) {
  2092. super( value, nodeType );
  2093. /**
  2094. * This flag can be used for type testing.
  2095. *
  2096. * @type {boolean}
  2097. * @readonly
  2098. * @default true
  2099. */
  2100. this.isConstNode = true;
  2101. }
  2102. /**
  2103. * Generates the shader string of the value with the current node builder.
  2104. *
  2105. * @param {NodeBuilder} builder - The current node builder.
  2106. * @return {string} The generated value as a shader string.
  2107. */
  2108. generateConst( builder ) {
  2109. return builder.generateConst( this.getNodeType( builder ), this.value );
  2110. }
  2111. generate( builder, output ) {
  2112. const type = this.getNodeType( builder );
  2113. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2114. return builder.generateConst( output, this.value );
  2115. }
  2116. return builder.format( this.generateConst( builder ), type, output );
  2117. }
  2118. }
  2119. /**
  2120. * Base class for representing member access on an object-like
  2121. * node data structures.
  2122. *
  2123. * @augments Node
  2124. */
  2125. class MemberNode extends Node {
  2126. static get type() {
  2127. return 'MemberNode';
  2128. }
  2129. /**
  2130. * Constructs an array element node.
  2131. *
  2132. * @param {Node} node - The array-like node.
  2133. * @param {string} property - The property name.
  2134. */
  2135. constructor( node, property ) {
  2136. super();
  2137. /**
  2138. * The array-like node.
  2139. *
  2140. * @type {Node}
  2141. */
  2142. this.node = node;
  2143. /**
  2144. * The property name.
  2145. *
  2146. * @type {Node}
  2147. */
  2148. this.property = property;
  2149. /**
  2150. * This flag can be used for type testing.
  2151. *
  2152. * @type {boolean}
  2153. * @readonly
  2154. * @default true
  2155. */
  2156. this.isMemberNode = true;
  2157. }
  2158. getNodeType( builder ) {
  2159. return this.node.getMemberType( builder, this.property );
  2160. }
  2161. generate( builder ) {
  2162. const propertyName = this.node.build( builder );
  2163. return propertyName + '.' + this.property;
  2164. }
  2165. }
  2166. let currentStack = null;
  2167. const NodeElements = new Map();
  2168. function addMethodChaining( name, nodeElement ) {
  2169. if ( NodeElements.has( name ) ) {
  2170. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2171. return;
  2172. }
  2173. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2174. NodeElements.set( name, nodeElement );
  2175. }
  2176. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2177. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2178. const shaderNodeHandler = {
  2179. setup( NodeClosure, params ) {
  2180. const inputs = params.shift();
  2181. return NodeClosure( nodeObjects( inputs ), ...params );
  2182. },
  2183. get( node, prop, nodeObj ) {
  2184. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2185. if ( node.isStackNode !== true && prop === 'assign' ) {
  2186. return ( ...params ) => {
  2187. currentStack.assign( nodeObj, ...params );
  2188. return nodeObj;
  2189. };
  2190. } else if ( NodeElements.has( prop ) ) {
  2191. const nodeElement = NodeElements.get( prop );
  2192. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2193. } else if ( prop === 'toVarIntent' ) {
  2194. return () => nodeObj;
  2195. } else if ( prop === 'self' ) {
  2196. return node;
  2197. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2198. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2199. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2200. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2201. // accessing properties ( swizzle )
  2202. prop = parseSwizzle( prop );
  2203. return nodeObject( new SplitNode( nodeObj, prop ) );
  2204. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2205. // set properties ( swizzle ) and sort to xyzw sequence
  2206. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2207. return ( value ) => nodeObject( new SetNode( node, prop, nodeObject( value ) ) );
  2208. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2209. // set properties ( swizzle ) and sort to xyzw sequence
  2210. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2211. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2212. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2213. // accessing property
  2214. if ( prop === 'width' ) prop = 'x';
  2215. else if ( prop === 'height' ) prop = 'y';
  2216. else if ( prop === 'depth' ) prop = 'z';
  2217. return nodeObject( new SplitNode( node, prop ) );
  2218. } else if ( /^\d+$/.test( prop ) === true ) {
  2219. // accessing array
  2220. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2221. } else if ( /^get$/.test( prop ) === true ) {
  2222. // accessing properties
  2223. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2224. }
  2225. }
  2226. return Reflect.get( node, prop, nodeObj );
  2227. },
  2228. set( node, prop, value, nodeObj ) {
  2229. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2230. // setting properties
  2231. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2232. nodeObj[ prop ].assign( value );
  2233. return true;
  2234. }
  2235. }
  2236. return Reflect.set( node, prop, value, nodeObj );
  2237. }
  2238. };
  2239. const nodeObjectsCacheMap = new WeakMap();
  2240. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2241. const ShaderNodeObject = function ( obj, altType = null ) {
  2242. const type = getValueType( obj );
  2243. if ( type === 'node' ) {
  2244. let nodeObject = nodeObjectsCacheMap.get( obj );
  2245. if ( nodeObject === undefined ) {
  2246. nodeObject = new Proxy( obj, shaderNodeHandler );
  2247. nodeObjectsCacheMap.set( obj, nodeObject );
  2248. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2249. }
  2250. return nodeObject;
  2251. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2252. return nodeObject( getConstNode( obj, altType ) );
  2253. } else if ( type === 'shader' ) {
  2254. return obj.isFn ? obj : Fn( obj );
  2255. }
  2256. return obj;
  2257. };
  2258. const ShaderNodeObjects = function ( objects, altType = null ) {
  2259. for ( const name in objects ) {
  2260. objects[ name ] = nodeObject( objects[ name ], altType );
  2261. }
  2262. return objects;
  2263. };
  2264. const ShaderNodeArray = function ( array, altType = null ) {
  2265. const len = array.length;
  2266. for ( let i = 0; i < len; i ++ ) {
  2267. array[ i ] = nodeObject( array[ i ], altType );
  2268. }
  2269. return array;
  2270. };
  2271. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2272. function assignNode( node ) {
  2273. if ( settings !== null ) {
  2274. node = nodeObject( Object.assign( node, settings ) );
  2275. if ( settings.intent === true ) {
  2276. node = node.toVarIntent();
  2277. }
  2278. } else {
  2279. node = nodeObject( node );
  2280. }
  2281. return node;
  2282. }
  2283. let fn, name = scope, minParams, maxParams;
  2284. function verifyParamsLimit( params ) {
  2285. let tslName;
  2286. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2287. else tslName = NodeClass.type;
  2288. if ( minParams !== undefined && params.length < minParams ) {
  2289. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2290. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2291. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2292. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2293. return params.slice( 0, maxParams );
  2294. }
  2295. return params;
  2296. }
  2297. if ( scope === null ) {
  2298. fn = ( ...params ) => {
  2299. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2300. };
  2301. } else if ( factor !== null ) {
  2302. factor = nodeObject( factor );
  2303. fn = ( ...params ) => {
  2304. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2305. };
  2306. } else {
  2307. fn = ( ...params ) => {
  2308. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2309. };
  2310. }
  2311. fn.setParameterLength = ( ...params ) => {
  2312. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2313. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2314. return fn;
  2315. };
  2316. fn.setName = ( value ) => {
  2317. name = value;
  2318. return fn;
  2319. };
  2320. return fn;
  2321. };
  2322. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2323. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2324. };
  2325. class ShaderCallNodeInternal extends Node {
  2326. constructor( shaderNode, rawInputs ) {
  2327. super();
  2328. this.shaderNode = shaderNode;
  2329. this.rawInputs = rawInputs;
  2330. this.isShaderCallNodeInternal = true;
  2331. }
  2332. getNodeType( builder ) {
  2333. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2334. }
  2335. getMemberType( builder, name ) {
  2336. return this.getOutputNode( builder ).getMemberType( builder, name );
  2337. }
  2338. call( builder ) {
  2339. const { shaderNode, rawInputs } = this;
  2340. const properties = builder.getNodeProperties( shaderNode );
  2341. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2342. const subBuildProperty = subBuild || 'default';
  2343. if ( properties[ subBuildProperty ] ) {
  2344. return properties[ subBuildProperty ];
  2345. }
  2346. //
  2347. const previousSubBuildFn = builder.subBuildFn;
  2348. builder.subBuildFn = subBuild;
  2349. let result = null;
  2350. if ( shaderNode.layout ) {
  2351. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2352. if ( functionNodesCacheMap === undefined ) {
  2353. functionNodesCacheMap = new WeakMap();
  2354. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2355. }
  2356. let functionNode = functionNodesCacheMap.get( shaderNode );
  2357. if ( functionNode === undefined ) {
  2358. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2359. functionNodesCacheMap.set( shaderNode, functionNode );
  2360. }
  2361. builder.addInclude( functionNode );
  2362. //
  2363. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2364. result = nodeObject( functionNode.call( inputs ) );
  2365. } else {
  2366. const secureNodeBuilder = new Proxy( builder, {
  2367. get: ( target, property, receiver ) => {
  2368. let value;
  2369. if ( Symbol.iterator === property ) {
  2370. value = function* () {
  2371. yield undefined;
  2372. };
  2373. } else {
  2374. value = Reflect.get( target, property, receiver );
  2375. }
  2376. return value;
  2377. }
  2378. } );
  2379. //
  2380. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2381. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2382. const jsFunc = shaderNode.jsFunc;
  2383. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2384. result = nodeObject( outputNode );
  2385. }
  2386. builder.subBuildFn = previousSubBuildFn;
  2387. if ( shaderNode.once ) {
  2388. properties[ subBuildProperty ] = result;
  2389. }
  2390. return result;
  2391. }
  2392. setupOutput( builder ) {
  2393. builder.addStack();
  2394. builder.stack.outputNode = this.call( builder );
  2395. return builder.removeStack();
  2396. }
  2397. getOutputNode( builder ) {
  2398. const properties = builder.getNodeProperties( this );
  2399. const subBuildOutput = builder.getSubBuildOutput( this );
  2400. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2401. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2402. return properties[ subBuildOutput ];
  2403. }
  2404. build( builder, output = null ) {
  2405. let result = null;
  2406. const buildStage = builder.getBuildStage();
  2407. const properties = builder.getNodeProperties( this );
  2408. const subBuildOutput = builder.getSubBuildOutput( this );
  2409. const outputNode = this.getOutputNode( builder );
  2410. if ( buildStage === 'setup' ) {
  2411. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2412. if ( properties[ subBuildInitialized ] !== true ) {
  2413. properties[ subBuildInitialized ] = true;
  2414. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2415. properties[ subBuildOutput ].build( builder );
  2416. // If the shaderNode has subBuilds, add them to the chaining nodes
  2417. // so they can be built later in the build process.
  2418. if ( this.shaderNode.subBuilds ) {
  2419. for ( const node of builder.chaining ) {
  2420. const nodeData = builder.getDataFromNode( node, 'any' );
  2421. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2422. for ( const subBuild of this.shaderNode.subBuilds ) {
  2423. nodeData.subBuilds.add( subBuild );
  2424. }
  2425. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2426. }
  2427. }
  2428. }
  2429. result = properties[ subBuildOutput ];
  2430. } else if ( buildStage === 'analyze' ) {
  2431. outputNode.build( builder, output );
  2432. } else if ( buildStage === 'generate' ) {
  2433. result = outputNode.build( builder, output ) || '';
  2434. }
  2435. return result;
  2436. }
  2437. }
  2438. function getLayoutParameters( params ) {
  2439. let output;
  2440. nodeObjects( params );
  2441. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2442. if ( isArrayAsParameter ) {
  2443. output = [ ...params ];
  2444. } else {
  2445. output = params[ 0 ];
  2446. }
  2447. return output;
  2448. }
  2449. function getProxyParameters( params ) {
  2450. let index = 0;
  2451. nodeObjects( params );
  2452. return new Proxy( params, {
  2453. get: ( target, property, receiver ) => {
  2454. let value;
  2455. if ( property === 'length' ) {
  2456. value = params.length;
  2457. return value;
  2458. }
  2459. if ( Symbol.iterator === property ) {
  2460. value = function* () {
  2461. for ( const inputNode of params ) {
  2462. yield nodeObject( inputNode );
  2463. }
  2464. };
  2465. } else {
  2466. if ( params.length > 0 ) {
  2467. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2468. const objectTarget = params[ 0 ];
  2469. if ( objectTarget[ property ] === undefined ) {
  2470. value = objectTarget[ index ++ ];
  2471. } else {
  2472. value = Reflect.get( objectTarget, property, receiver );
  2473. }
  2474. } else if ( params[ 0 ] instanceof Node ) {
  2475. if ( params[ property ] === undefined ) {
  2476. value = params[ index ++ ];
  2477. } else {
  2478. value = Reflect.get( params, property, receiver );
  2479. }
  2480. }
  2481. } else {
  2482. value = Reflect.get( target, property, receiver );
  2483. }
  2484. value = nodeObject( value );
  2485. }
  2486. return value;
  2487. }
  2488. } );
  2489. }
  2490. class ShaderNodeInternal extends Node {
  2491. constructor( jsFunc, nodeType ) {
  2492. super( nodeType );
  2493. this.jsFunc = jsFunc;
  2494. this.layout = null;
  2495. this.global = true;
  2496. this.once = false;
  2497. }
  2498. setLayout( layout ) {
  2499. this.layout = layout;
  2500. return this;
  2501. }
  2502. call( rawInputs = null ) {
  2503. return nodeObject( new ShaderCallNodeInternal( this, rawInputs ) );
  2504. }
  2505. setup() {
  2506. return this.call();
  2507. }
  2508. }
  2509. const bools = [ false, true ];
  2510. const uints = [ 0, 1, 2, 3 ];
  2511. const ints = [ -1, -2 ];
  2512. 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 ];
  2513. const boolsCacheMap = new Map();
  2514. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2515. const uintsCacheMap = new Map();
  2516. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2517. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2518. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2519. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2520. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2521. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2522. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2523. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2524. const getConstNode = ( value, type ) => {
  2525. if ( constNodesCacheMap.has( value ) ) {
  2526. return constNodesCacheMap.get( value );
  2527. } else if ( value.isNode === true ) {
  2528. return value;
  2529. } else {
  2530. return new ConstNode( value, type );
  2531. }
  2532. };
  2533. const ConvertType = function ( type, cacheMap = null ) {
  2534. return ( ...params ) => {
  2535. for ( const param of params ) {
  2536. if ( param === undefined ) {
  2537. console.error( `THREE.TSL: Invalid parameter for the type "${ type }".` );
  2538. return nodeObject( new ConstNode( 0, type ) );
  2539. }
  2540. }
  2541. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2542. const paramType = typeof param;
  2543. return paramType !== 'object' && paramType !== 'function';
  2544. } ) ) ) {
  2545. params = [ getValueFromType( type, ...params ) ];
  2546. }
  2547. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2548. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2549. }
  2550. if ( params.length === 1 ) {
  2551. const node = getConstNode( params[ 0 ], type );
  2552. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2553. return nodeObjectIntent( new ConvertNode( node, type ) );
  2554. }
  2555. const nodes = params.map( param => getConstNode( param ) );
  2556. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2557. };
  2558. };
  2559. // exports
  2560. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2561. // utils
  2562. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2563. // shader node base
  2564. function ShaderNode( jsFunc, nodeType ) {
  2565. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2566. }
  2567. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2568. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2569. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2570. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2571. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2572. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2573. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2574. let fnId = 0;
  2575. class FnNode extends Node {
  2576. constructor( jsFunc, layout = null ) {
  2577. super();
  2578. let nodeType = null;
  2579. if ( layout !== null ) {
  2580. if ( typeof layout === 'object' ) {
  2581. nodeType = layout.return;
  2582. } else {
  2583. if ( typeof layout === 'string' ) {
  2584. nodeType = layout;
  2585. } else {
  2586. console.error( 'THREE.TSL: Invalid layout type.' );
  2587. }
  2588. layout = null;
  2589. }
  2590. }
  2591. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2592. if ( layout !== null ) {
  2593. this.setLayout( layout );
  2594. }
  2595. this.isFn = true;
  2596. }
  2597. setLayout( layout ) {
  2598. const nodeType = this.shaderNode.nodeType;
  2599. if ( typeof layout.inputs !== 'object' ) {
  2600. const fullLayout = {
  2601. name: 'fn' + fnId ++,
  2602. type: nodeType,
  2603. inputs: []
  2604. };
  2605. for ( const name in layout ) {
  2606. if ( name === 'return' ) continue;
  2607. fullLayout.inputs.push( {
  2608. name: name,
  2609. type: layout[ name ]
  2610. } );
  2611. }
  2612. layout = fullLayout;
  2613. }
  2614. this.shaderNode.setLayout( layout );
  2615. return this;
  2616. }
  2617. getNodeType( builder ) {
  2618. return this.shaderNode.getNodeType( builder ) || 'float';
  2619. }
  2620. call( ...params ) {
  2621. const fnCall = this.shaderNode.call( params );
  2622. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2623. return fnCall.toVarIntent();
  2624. }
  2625. once( subBuilds = null ) {
  2626. this.shaderNode.once = true;
  2627. this.shaderNode.subBuilds = subBuilds;
  2628. return this;
  2629. }
  2630. generate( builder ) {
  2631. const type = this.getNodeType( builder );
  2632. console.error( 'THREE.TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2633. return builder.generateConst( type );
  2634. }
  2635. }
  2636. function Fn( jsFunc, layout = null ) {
  2637. const instance = new FnNode( jsFunc, layout );
  2638. return new Proxy( () => {}, {
  2639. apply( target, thisArg, params ) {
  2640. return instance.call( ...params );
  2641. },
  2642. get( target, prop, receiver ) {
  2643. return Reflect.get( instance, prop, receiver );
  2644. },
  2645. set( target, prop, value, receiver ) {
  2646. return Reflect.set( instance, prop, value, receiver );
  2647. }
  2648. } );
  2649. }
  2650. //
  2651. const setCurrentStack = ( stack ) => {
  2652. currentStack = stack;
  2653. };
  2654. const getCurrentStack = () => currentStack;
  2655. /**
  2656. * Represent a conditional node using if/else statements.
  2657. *
  2658. * ```js
  2659. * If( condition, function )
  2660. * .ElseIf( condition, function )
  2661. * .Else( function )
  2662. * ```
  2663. * @tsl
  2664. * @function
  2665. * @param {...any} params - The parameters for the conditional node.
  2666. * @returns {StackNode} The conditional node.
  2667. */
  2668. const If = ( ...params ) => currentStack.If( ...params );
  2669. /**
  2670. * Represent a conditional node using switch/case statements.
  2671. *
  2672. * ```js
  2673. * Switch( value )
  2674. * .Case( 1, function )
  2675. * .Case( 2, 3, 4, function )
  2676. * .Default( function )
  2677. * ```
  2678. * @tsl
  2679. * @function
  2680. * @param {...any} params - The parameters for the conditional node.
  2681. * @returns {StackNode} The conditional node.
  2682. */
  2683. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2684. /**
  2685. * Add the given node to the current stack.
  2686. *
  2687. * @param {Node} node - The node to add.
  2688. * @returns {Node} The node that was added to the stack.
  2689. */
  2690. function Stack( node ) {
  2691. if ( currentStack ) currentStack.add( node );
  2692. return node;
  2693. }
  2694. addMethodChaining( 'toStack', Stack );
  2695. // types
  2696. const color = new ConvertType( 'color' );
  2697. const float = new ConvertType( 'float', cacheMaps.float );
  2698. const int = new ConvertType( 'int', cacheMaps.ints );
  2699. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2700. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2701. const vec2 = new ConvertType( 'vec2' );
  2702. const ivec2 = new ConvertType( 'ivec2' );
  2703. const uvec2 = new ConvertType( 'uvec2' );
  2704. const bvec2 = new ConvertType( 'bvec2' );
  2705. const vec3 = new ConvertType( 'vec3' );
  2706. const ivec3 = new ConvertType( 'ivec3' );
  2707. const uvec3 = new ConvertType( 'uvec3' );
  2708. const bvec3 = new ConvertType( 'bvec3' );
  2709. const vec4 = new ConvertType( 'vec4' );
  2710. const ivec4 = new ConvertType( 'ivec4' );
  2711. const uvec4 = new ConvertType( 'uvec4' );
  2712. const bvec4 = new ConvertType( 'bvec4' );
  2713. const mat2 = new ConvertType( 'mat2' );
  2714. const mat3 = new ConvertType( 'mat3' );
  2715. const mat4 = new ConvertType( 'mat4' );
  2716. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2717. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2718. addMethodChaining( 'toColor', color );
  2719. addMethodChaining( 'toFloat', float );
  2720. addMethodChaining( 'toInt', int );
  2721. addMethodChaining( 'toUint', uint );
  2722. addMethodChaining( 'toBool', bool );
  2723. addMethodChaining( 'toVec2', vec2 );
  2724. addMethodChaining( 'toIVec2', ivec2 );
  2725. addMethodChaining( 'toUVec2', uvec2 );
  2726. addMethodChaining( 'toBVec2', bvec2 );
  2727. addMethodChaining( 'toVec3', vec3 );
  2728. addMethodChaining( 'toIVec3', ivec3 );
  2729. addMethodChaining( 'toUVec3', uvec3 );
  2730. addMethodChaining( 'toBVec3', bvec3 );
  2731. addMethodChaining( 'toVec4', vec4 );
  2732. addMethodChaining( 'toIVec4', ivec4 );
  2733. addMethodChaining( 'toUVec4', uvec4 );
  2734. addMethodChaining( 'toBVec4', bvec4 );
  2735. addMethodChaining( 'toMat2', mat2 );
  2736. addMethodChaining( 'toMat3', mat3 );
  2737. addMethodChaining( 'toMat4', mat4 );
  2738. // basic nodes
  2739. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2740. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2741. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2742. addMethodChaining( 'element', element );
  2743. addMethodChaining( 'convert', convert );
  2744. // deprecated
  2745. /**
  2746. * @tsl
  2747. * @function
  2748. * @deprecated since r176. Use {@link Stack} instead.
  2749. *
  2750. * @param {Node} node - The node to add.
  2751. * @returns {Function}
  2752. */
  2753. const append = ( node ) => { // @deprecated, r176
  2754. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2755. return Stack( node );
  2756. };
  2757. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2758. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2759. return Stack( node );
  2760. } );
  2761. /**
  2762. * This class represents a shader property. It can be used
  2763. * to explicitly define a property and assign a value to it.
  2764. *
  2765. * ```js
  2766. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2767. *```
  2768. * `PropertyNode` is used by the engine to predefined common material properties
  2769. * for TSL code.
  2770. *
  2771. * @augments Node
  2772. */
  2773. class PropertyNode extends Node {
  2774. static get type() {
  2775. return 'PropertyNode';
  2776. }
  2777. /**
  2778. * Constructs a new property node.
  2779. *
  2780. * @param {string} nodeType - The type of the node.
  2781. * @param {?string} [name=null] - The name of the property in the shader.
  2782. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2783. */
  2784. constructor( nodeType, name = null, varying = false ) {
  2785. super( nodeType );
  2786. /**
  2787. * The name of the property in the shader. If no name is defined,
  2788. * the node system auto-generates one.
  2789. *
  2790. * @type {?string}
  2791. * @default null
  2792. */
  2793. this.name = name;
  2794. /**
  2795. * Whether this property is a varying or not.
  2796. *
  2797. * @type {boolean}
  2798. * @default false
  2799. */
  2800. this.varying = varying;
  2801. /**
  2802. * This flag can be used for type testing.
  2803. *
  2804. * @type {boolean}
  2805. * @readonly
  2806. * @default true
  2807. */
  2808. this.isPropertyNode = true;
  2809. /**
  2810. * This flag is used for global cache.
  2811. *
  2812. * @type {boolean}
  2813. * @default true
  2814. */
  2815. this.global = true;
  2816. }
  2817. getHash( builder ) {
  2818. return this.name || super.getHash( builder );
  2819. }
  2820. generate( builder ) {
  2821. let nodeVar;
  2822. if ( this.varying === true ) {
  2823. nodeVar = builder.getVaryingFromNode( this, this.name );
  2824. nodeVar.needsInterpolation = true;
  2825. } else {
  2826. nodeVar = builder.getVarFromNode( this, this.name );
  2827. }
  2828. return builder.getPropertyName( nodeVar );
  2829. }
  2830. }
  2831. /**
  2832. * TSL function for creating a property node.
  2833. *
  2834. * @tsl
  2835. * @function
  2836. * @param {string} type - The type of the node.
  2837. * @param {?string} [name=null] - The name of the property in the shader.
  2838. * @returns {PropertyNode}
  2839. */
  2840. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2841. /**
  2842. * TSL function for creating a varying property node.
  2843. *
  2844. * @tsl
  2845. * @function
  2846. * @param {string} type - The type of the node.
  2847. * @param {?string} [name=null] - The name of the varying in the shader.
  2848. * @returns {PropertyNode}
  2849. */
  2850. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2851. /**
  2852. * TSL object that represents the shader variable `DiffuseColor`.
  2853. *
  2854. * @tsl
  2855. * @type {PropertyNode<vec4>}
  2856. */
  2857. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2858. /**
  2859. * TSL object that represents the shader variable `EmissiveColor`.
  2860. *
  2861. * @tsl
  2862. * @type {PropertyNode<vec3>}
  2863. */
  2864. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2865. /**
  2866. * TSL object that represents the shader variable `Roughness`.
  2867. *
  2868. * @tsl
  2869. * @type {PropertyNode<float>}
  2870. */
  2871. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2872. /**
  2873. * TSL object that represents the shader variable `Metalness`.
  2874. *
  2875. * @tsl
  2876. * @type {PropertyNode<float>}
  2877. */
  2878. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2879. /**
  2880. * TSL object that represents the shader variable `Clearcoat`.
  2881. *
  2882. * @tsl
  2883. * @type {PropertyNode<float>}
  2884. */
  2885. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2886. /**
  2887. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2888. *
  2889. * @tsl
  2890. * @type {PropertyNode<float>}
  2891. */
  2892. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2893. /**
  2894. * TSL object that represents the shader variable `Sheen`.
  2895. *
  2896. * @tsl
  2897. * @type {PropertyNode<vec3>}
  2898. */
  2899. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2900. /**
  2901. * TSL object that represents the shader variable `SheenRoughness`.
  2902. *
  2903. * @tsl
  2904. * @type {PropertyNode<float>}
  2905. */
  2906. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2907. /**
  2908. * TSL object that represents the shader variable `Iridescence`.
  2909. *
  2910. * @tsl
  2911. * @type {PropertyNode<float>}
  2912. */
  2913. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2914. /**
  2915. * TSL object that represents the shader variable `IridescenceIOR`.
  2916. *
  2917. * @tsl
  2918. * @type {PropertyNode<float>}
  2919. */
  2920. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2921. /**
  2922. * TSL object that represents the shader variable `IridescenceThickness`.
  2923. *
  2924. * @tsl
  2925. * @type {PropertyNode<float>}
  2926. */
  2927. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2928. /**
  2929. * TSL object that represents the shader variable `AlphaT`.
  2930. *
  2931. * @tsl
  2932. * @type {PropertyNode<float>}
  2933. */
  2934. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2935. /**
  2936. * TSL object that represents the shader variable `Anisotropy`.
  2937. *
  2938. * @tsl
  2939. * @type {PropertyNode<float>}
  2940. */
  2941. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2942. /**
  2943. * TSL object that represents the shader variable `AnisotropyT`.
  2944. *
  2945. * @tsl
  2946. * @type {PropertyNode<vec3>}
  2947. */
  2948. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2949. /**
  2950. * TSL object that represents the shader variable `AnisotropyB`.
  2951. *
  2952. * @tsl
  2953. * @type {PropertyNode<vec3>}
  2954. */
  2955. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2956. /**
  2957. * TSL object that represents the shader variable `SpecularColor`.
  2958. *
  2959. * @tsl
  2960. * @type {PropertyNode<color>}
  2961. */
  2962. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2963. /**
  2964. * TSL object that represents the shader variable `SpecularF90`.
  2965. *
  2966. * @tsl
  2967. * @type {PropertyNode<float>}
  2968. */
  2969. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2970. /**
  2971. * TSL object that represents the shader variable `Shininess`.
  2972. *
  2973. * @tsl
  2974. * @type {PropertyNode<float>}
  2975. */
  2976. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2977. /**
  2978. * TSL object that represents the shader variable `Output`.
  2979. *
  2980. * @tsl
  2981. * @type {PropertyNode<vec4>}
  2982. */
  2983. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2984. /**
  2985. * TSL object that represents the shader variable `dashSize`.
  2986. *
  2987. * @tsl
  2988. * @type {PropertyNode<float>}
  2989. */
  2990. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2991. /**
  2992. * TSL object that represents the shader variable `gapSize`.
  2993. *
  2994. * @tsl
  2995. * @type {PropertyNode<float>}
  2996. */
  2997. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2998. /**
  2999. * TSL object that represents the shader variable `pointWidth`.
  3000. *
  3001. * @tsl
  3002. * @type {PropertyNode<float>}
  3003. */
  3004. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3005. /**
  3006. * TSL object that represents the shader variable `IOR`.
  3007. *
  3008. * @tsl
  3009. * @type {PropertyNode<float>}
  3010. */
  3011. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3012. /**
  3013. * TSL object that represents the shader variable `Transmission`.
  3014. *
  3015. * @tsl
  3016. * @type {PropertyNode<float>}
  3017. */
  3018. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3019. /**
  3020. * TSL object that represents the shader variable `Thickness`.
  3021. *
  3022. * @tsl
  3023. * @type {PropertyNode<float>}
  3024. */
  3025. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3026. /**
  3027. * TSL object that represents the shader variable `AttenuationDistance`.
  3028. *
  3029. * @tsl
  3030. * @type {PropertyNode<float>}
  3031. */
  3032. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3033. /**
  3034. * TSL object that represents the shader variable `AttenuationColor`.
  3035. *
  3036. * @tsl
  3037. * @type {PropertyNode<color>}
  3038. */
  3039. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3040. /**
  3041. * TSL object that represents the shader variable `Dispersion`.
  3042. *
  3043. * @tsl
  3044. * @type {PropertyNode<float>}
  3045. */
  3046. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3047. /**
  3048. * This node can be used to group single instances of {@link UniformNode}
  3049. * and manage them as a uniform buffer.
  3050. *
  3051. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3052. * will be used when defining the {@link UniformNode#groupNode} property.
  3053. *
  3054. * - `objectGroup`: Uniform buffer per object.
  3055. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3056. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3057. *
  3058. * @augments Node
  3059. */
  3060. class UniformGroupNode extends Node {
  3061. static get type() {
  3062. return 'UniformGroupNode';
  3063. }
  3064. /**
  3065. * Constructs a new uniform group node.
  3066. *
  3067. * @param {string} name - The name of the uniform group node.
  3068. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3069. * @param {number} [order=1] - Influences the internal sorting.
  3070. */
  3071. constructor( name, shared = false, order = 1 ) {
  3072. super( 'string' );
  3073. /**
  3074. * The name of the uniform group node.
  3075. *
  3076. * @type {string}
  3077. */
  3078. this.name = name;
  3079. /**
  3080. * Whether this uniform group node is shared or not.
  3081. *
  3082. * @type {boolean}
  3083. * @default false
  3084. */
  3085. this.shared = shared;
  3086. /**
  3087. * Influences the internal sorting.
  3088. * TODO: Add details when this property should be changed.
  3089. *
  3090. * @type {number}
  3091. * @default 1
  3092. */
  3093. this.order = order;
  3094. /**
  3095. * This flag can be used for type testing.
  3096. *
  3097. * @type {boolean}
  3098. * @readonly
  3099. * @default true
  3100. */
  3101. this.isUniformGroup = true;
  3102. }
  3103. serialize( data ) {
  3104. super.serialize( data );
  3105. data.name = this.name;
  3106. data.version = this.version;
  3107. data.shared = this.shared;
  3108. }
  3109. deserialize( data ) {
  3110. super.deserialize( data );
  3111. this.name = data.name;
  3112. this.version = data.version;
  3113. this.shared = data.shared;
  3114. }
  3115. }
  3116. /**
  3117. * TSL function for creating a uniform group node with the given name.
  3118. *
  3119. * @tsl
  3120. * @function
  3121. * @param {string} name - The name of the uniform group node.
  3122. * @returns {UniformGroupNode}
  3123. */
  3124. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3125. /**
  3126. * TSL function for creating a shared uniform group node with the given name and order.
  3127. *
  3128. * @tsl
  3129. * @function
  3130. * @param {string} name - The name of the uniform group node.
  3131. * @param {number} [order=0] - Influences the internal sorting.
  3132. * @returns {UniformGroupNode}
  3133. */
  3134. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3135. /**
  3136. * TSL object that represents a shared uniform group node which is updated once per frame.
  3137. *
  3138. * @tsl
  3139. * @type {UniformGroupNode}
  3140. */
  3141. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3142. /**
  3143. * TSL object that represents a shared uniform group node which is updated once per render.
  3144. *
  3145. * @tsl
  3146. * @type {UniformGroupNode}
  3147. */
  3148. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3149. /**
  3150. * TSL object that represents a uniform group node which is updated once per object.
  3151. *
  3152. * @tsl
  3153. * @type {UniformGroupNode}
  3154. */
  3155. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3156. /**
  3157. * Class for representing a uniform.
  3158. *
  3159. * @augments InputNode
  3160. */
  3161. class UniformNode extends InputNode {
  3162. static get type() {
  3163. return 'UniformNode';
  3164. }
  3165. /**
  3166. * Constructs a new uniform node.
  3167. *
  3168. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3169. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3170. */
  3171. constructor( value, nodeType = null ) {
  3172. super( value, nodeType );
  3173. /**
  3174. * This flag can be used for type testing.
  3175. *
  3176. * @type {boolean}
  3177. * @readonly
  3178. * @default true
  3179. */
  3180. this.isUniformNode = true;
  3181. /**
  3182. * The name or label of the uniform.
  3183. *
  3184. * @type {string}
  3185. * @default ''
  3186. */
  3187. this.name = '';
  3188. /**
  3189. * The uniform group of this uniform. By default, uniforms are
  3190. * managed per object but they might belong to a shared group
  3191. * which is updated per frame or render call.
  3192. *
  3193. * @type {UniformGroupNode}
  3194. */
  3195. this.groupNode = objectGroup;
  3196. }
  3197. /**
  3198. * Sets the {@link UniformNode#name} property.
  3199. *
  3200. * @param {string} name - The name of the uniform.
  3201. * @return {UniformNode} A reference to this node.
  3202. */
  3203. setName( name ) {
  3204. this.name = name;
  3205. return this;
  3206. }
  3207. /**
  3208. * Sets the {@link UniformNode#name} property.
  3209. *
  3210. * @deprecated
  3211. * @param {string} name - The name of the uniform.
  3212. * @return {UniformNode} A reference to this node.
  3213. */
  3214. label( name ) {
  3215. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3216. return this.setName( name );
  3217. }
  3218. /**
  3219. * Sets the {@link UniformNode#groupNode} property.
  3220. *
  3221. * @param {UniformGroupNode} group - The uniform group.
  3222. * @return {UniformNode} A reference to this node.
  3223. */
  3224. setGroup( group ) {
  3225. this.groupNode = group;
  3226. return this;
  3227. }
  3228. /**
  3229. * Returns the {@link UniformNode#groupNode}.
  3230. *
  3231. * @return {UniformGroupNode} The uniform group.
  3232. */
  3233. getGroup() {
  3234. return this.groupNode;
  3235. }
  3236. /**
  3237. * By default, this method returns the result of {@link Node#getHash} but derived
  3238. * classes might overwrite this method with a different implementation.
  3239. *
  3240. * @param {NodeBuilder} builder - The current node builder.
  3241. * @return {string} The uniform hash.
  3242. */
  3243. getUniformHash( builder ) {
  3244. return this.getHash( builder );
  3245. }
  3246. onUpdate( callback, updateType ) {
  3247. const self = this.getSelf();
  3248. callback = callback.bind( self );
  3249. return super.onUpdate( ( frame ) => {
  3250. const value = callback( frame, self );
  3251. if ( value !== undefined ) {
  3252. this.value = value;
  3253. }
  3254. }, updateType );
  3255. }
  3256. getInputType( builder ) {
  3257. let type = super.getInputType( builder );
  3258. if ( type === 'bool' ) {
  3259. type = 'uint';
  3260. }
  3261. return type;
  3262. }
  3263. generate( builder, output ) {
  3264. const type = this.getNodeType( builder );
  3265. const hash = this.getUniformHash( builder );
  3266. let sharedNode = builder.getNodeFromHash( hash );
  3267. if ( sharedNode === undefined ) {
  3268. builder.setHashNode( this, hash );
  3269. sharedNode = this;
  3270. }
  3271. const sharedNodeType = sharedNode.getInputType( builder );
  3272. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3273. const uniformName = builder.getPropertyName( nodeUniform );
  3274. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3275. //
  3276. let snippet = uniformName;
  3277. if ( type === 'bool' ) {
  3278. // cache to variable
  3279. const nodeData = builder.getDataFromNode( this );
  3280. let propertyName = nodeData.propertyName;
  3281. if ( propertyName === undefined ) {
  3282. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3283. propertyName = builder.getPropertyName( nodeVar );
  3284. nodeData.propertyName = propertyName;
  3285. snippet = builder.format( uniformName, sharedNodeType, type );
  3286. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3287. }
  3288. snippet = propertyName;
  3289. }
  3290. return builder.format( snippet, type, output );
  3291. }
  3292. }
  3293. /**
  3294. * TSL function for creating a uniform node.
  3295. *
  3296. * @tsl
  3297. * @function
  3298. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3299. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3300. * @returns {UniformNode}
  3301. */
  3302. const uniform = ( value, type ) => {
  3303. const nodeType = getConstNodeType( type || value );
  3304. if ( nodeType === value ) {
  3305. // if the value is a type but no having a value
  3306. value = getValueFromType( nodeType );
  3307. }
  3308. // @TODO: get ConstNode from .traverse() in the future
  3309. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3310. return nodeObject( new UniformNode( value, nodeType ) );
  3311. };
  3312. /**
  3313. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3314. * ```js
  3315. * const colors = array( [
  3316. * vec3( 1, 0, 0 ),
  3317. * vec3( 0, 1, 0 ),
  3318. * vec3( 0, 0, 1 )
  3319. * ] );
  3320. *
  3321. * const redColor = tintColors.element( 0 );
  3322. *
  3323. * @augments TempNode
  3324. */
  3325. class ArrayNode extends TempNode {
  3326. static get type() {
  3327. return 'ArrayNode';
  3328. }
  3329. /**
  3330. * Constructs a new array node.
  3331. *
  3332. * @param {?string} nodeType - The data type of the elements.
  3333. * @param {number} count - Size of the array.
  3334. * @param {?Array<Node>} [values=null] - Array default values.
  3335. */
  3336. constructor( nodeType, count, values = null ) {
  3337. super( nodeType );
  3338. /**
  3339. * Array size.
  3340. *
  3341. * @type {number}
  3342. */
  3343. this.count = count;
  3344. /**
  3345. * Array default values.
  3346. *
  3347. * @type {?Array<Node>}
  3348. */
  3349. this.values = values;
  3350. /**
  3351. * This flag can be used for type testing.
  3352. *
  3353. * @type {boolean}
  3354. * @readonly
  3355. * @default true
  3356. */
  3357. this.isArrayNode = true;
  3358. }
  3359. /**
  3360. * Returns the number of elements in the node array.
  3361. *
  3362. * @param {NodeBuilder} builder - The current node builder.
  3363. * @return {number} The number of elements in the node array.
  3364. */
  3365. getArrayCount( /*builder*/ ) {
  3366. return this.count;
  3367. }
  3368. /**
  3369. * Returns the node's type.
  3370. *
  3371. * @param {NodeBuilder} builder - The current node builder.
  3372. * @return {string} The type of the node.
  3373. */
  3374. getNodeType( builder ) {
  3375. if ( this.nodeType === null ) {
  3376. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3377. }
  3378. return this.nodeType;
  3379. }
  3380. /**
  3381. * Returns the node's type.
  3382. *
  3383. * @param {NodeBuilder} builder - The current node builder.
  3384. * @return {string} The type of the node.
  3385. */
  3386. getElementType( builder ) {
  3387. return this.getNodeType( builder );
  3388. }
  3389. /**
  3390. * This method builds the output node and returns the resulting array as a shader string.
  3391. *
  3392. * @param {NodeBuilder} builder - The current node builder.
  3393. * @return {string} The generated shader string.
  3394. */
  3395. generate( builder ) {
  3396. const type = this.getNodeType( builder );
  3397. return builder.generateArray( type, this.count, this.values );
  3398. }
  3399. }
  3400. /**
  3401. * TSL function for creating an array node.
  3402. *
  3403. * @tsl
  3404. * @function
  3405. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3406. * or an array containing the default values (e.g., [ vec3() ]).
  3407. * @param {?number} [count] - Size of the array.
  3408. * @returns {ArrayNode}
  3409. */
  3410. const array = ( ...params ) => {
  3411. let node;
  3412. if ( params.length === 1 ) {
  3413. const values = params[ 0 ];
  3414. node = new ArrayNode( null, values.length, values );
  3415. } else {
  3416. const nodeType = params[ 0 ];
  3417. const count = params[ 1 ];
  3418. node = new ArrayNode( nodeType, count );
  3419. }
  3420. return nodeObject( node );
  3421. };
  3422. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3423. /**
  3424. * These node represents an assign operation. Meaning a node is assigned
  3425. * to another node.
  3426. *
  3427. * @augments TempNode
  3428. */
  3429. class AssignNode extends TempNode {
  3430. static get type() {
  3431. return 'AssignNode';
  3432. }
  3433. /**
  3434. * Constructs a new assign node.
  3435. *
  3436. * @param {Node} targetNode - The target node.
  3437. * @param {Node} sourceNode - The source type.
  3438. */
  3439. constructor( targetNode, sourceNode ) {
  3440. super();
  3441. /**
  3442. * The target node.
  3443. *
  3444. * @type {Node}
  3445. */
  3446. this.targetNode = targetNode;
  3447. /**
  3448. * The source node.
  3449. *
  3450. * @type {Node}
  3451. */
  3452. this.sourceNode = sourceNode;
  3453. /**
  3454. * This flag can be used for type testing.
  3455. *
  3456. * @type {boolean}
  3457. * @readonly
  3458. * @default true
  3459. */
  3460. this.isAssignNode = true;
  3461. }
  3462. /**
  3463. * Whether this node is used more than once in context of other nodes. This method
  3464. * is overwritten since it always returns `false` (assigns are unique).
  3465. *
  3466. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3467. */
  3468. hasDependencies() {
  3469. return false;
  3470. }
  3471. getNodeType( builder, output ) {
  3472. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3473. }
  3474. /**
  3475. * Whether a split is required when assigning source to target. This can happen when the component length of
  3476. * target and source data type does not match.
  3477. *
  3478. * @param {NodeBuilder} builder - The current node builder.
  3479. * @return {boolean} Whether a split is required when assigning source to target.
  3480. */
  3481. needsSplitAssign( builder ) {
  3482. const { targetNode } = this;
  3483. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3484. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3485. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3486. return assignDifferentVector;
  3487. }
  3488. return false;
  3489. }
  3490. setup( builder ) {
  3491. const { targetNode, sourceNode } = this;
  3492. const scope = targetNode.getScope();
  3493. const targetProperties = builder.getNodeProperties( scope );
  3494. targetProperties.assign = true;
  3495. const properties = builder.getNodeProperties( this );
  3496. properties.sourceNode = sourceNode;
  3497. properties.targetNode = targetNode.context( { assign: true } );
  3498. }
  3499. generate( builder, output ) {
  3500. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3501. const needsSplitAssign = this.needsSplitAssign( builder );
  3502. const target = targetNode.build( builder );
  3503. const targetType = targetNode.getNodeType( builder );
  3504. const source = sourceNode.build( builder, targetType );
  3505. const sourceType = sourceNode.getNodeType( builder );
  3506. const nodeData = builder.getDataFromNode( this );
  3507. //
  3508. let snippet;
  3509. if ( nodeData.initialized === true ) {
  3510. if ( output !== 'void' ) {
  3511. snippet = target;
  3512. }
  3513. } else if ( needsSplitAssign ) {
  3514. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3515. const sourceProperty = builder.getPropertyName( sourceVar );
  3516. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3517. const splitNode = targetNode.node;
  3518. const splitTargetNode = splitNode.node.context( { assign: true } );
  3519. const targetRoot = splitTargetNode.build( builder );
  3520. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3521. const component = splitNode.components[ i ];
  3522. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3523. }
  3524. if ( output !== 'void' ) {
  3525. snippet = target;
  3526. }
  3527. } else {
  3528. snippet = `${ target } = ${ source }`;
  3529. if ( output === 'void' || sourceType === 'void' ) {
  3530. builder.addLineFlowCode( snippet, this );
  3531. if ( output !== 'void' ) {
  3532. snippet = target;
  3533. }
  3534. }
  3535. }
  3536. nodeData.initialized = true;
  3537. return builder.format( snippet, targetType, output );
  3538. }
  3539. }
  3540. /**
  3541. * TSL function for creating an assign node.
  3542. *
  3543. * @tsl
  3544. * @function
  3545. * @param {Node} targetNode - The target node.
  3546. * @param {Node} sourceNode - The source type.
  3547. * @returns {AssignNode}
  3548. */
  3549. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3550. addMethodChaining( 'assign', assign );
  3551. /**
  3552. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3553. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3554. * this logic.
  3555. *
  3556. * @augments TempNode
  3557. */
  3558. class FunctionCallNode extends TempNode {
  3559. static get type() {
  3560. return 'FunctionCallNode';
  3561. }
  3562. /**
  3563. * Constructs a new function call node.
  3564. *
  3565. * @param {?FunctionNode} functionNode - The function node.
  3566. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3567. */
  3568. constructor( functionNode = null, parameters = {} ) {
  3569. super();
  3570. /**
  3571. * The function node.
  3572. *
  3573. * @type {?FunctionNode}
  3574. * @default null
  3575. */
  3576. this.functionNode = functionNode;
  3577. /**
  3578. * The parameters of the function call.
  3579. *
  3580. * @type {Object<string, Node>}
  3581. * @default {}
  3582. */
  3583. this.parameters = parameters;
  3584. }
  3585. /**
  3586. * Sets the parameters of the function call node.
  3587. *
  3588. * @param {Object<string, Node>} parameters - The parameters to set.
  3589. * @return {FunctionCallNode} A reference to this node.
  3590. */
  3591. setParameters( parameters ) {
  3592. this.parameters = parameters;
  3593. return this;
  3594. }
  3595. /**
  3596. * Returns the parameters of the function call node.
  3597. *
  3598. * @return {Object<string, Node>} The parameters of this node.
  3599. */
  3600. getParameters() {
  3601. return this.parameters;
  3602. }
  3603. /**
  3604. * Returns the type of this function call node.
  3605. *
  3606. * @param {NodeBuilder} builder - The current node builder.
  3607. * @returns {string} The type of this node.
  3608. */
  3609. getNodeType( builder ) {
  3610. return this.functionNode.getNodeType( builder );
  3611. }
  3612. /**
  3613. * Returns the function node of this function call node.
  3614. *
  3615. * @param {NodeBuilder} builder - The current node builder.
  3616. * @param {string} [name] - The name of the member.
  3617. * @returns {string} The type of the member.
  3618. */
  3619. getMemberType( builder, name ) {
  3620. return this.functionNode.getMemberType( builder, name );
  3621. }
  3622. generate( builder ) {
  3623. const params = [];
  3624. const functionNode = this.functionNode;
  3625. const inputs = functionNode.getInputs( builder );
  3626. const parameters = this.parameters;
  3627. const generateInput = ( node, inputNode ) => {
  3628. const type = inputNode.type;
  3629. const pointer = type === 'pointer';
  3630. let output;
  3631. if ( pointer ) output = '&' + node.build( builder );
  3632. else output = node.build( builder, type );
  3633. return output;
  3634. };
  3635. if ( Array.isArray( parameters ) ) {
  3636. if ( parameters.length > inputs.length ) {
  3637. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3638. parameters.length = inputs.length;
  3639. } else if ( parameters.length < inputs.length ) {
  3640. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3641. while ( parameters.length < inputs.length ) {
  3642. parameters.push( float( 0 ) );
  3643. }
  3644. }
  3645. for ( let i = 0; i < parameters.length; i ++ ) {
  3646. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3647. }
  3648. } else {
  3649. for ( const inputNode of inputs ) {
  3650. const node = parameters[ inputNode.name ];
  3651. if ( node !== undefined ) {
  3652. params.push( generateInput( node, inputNode ) );
  3653. } else {
  3654. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3655. params.push( generateInput( float( 0 ), inputNode ) );
  3656. }
  3657. }
  3658. }
  3659. const functionName = functionNode.build( builder, 'property' );
  3660. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3661. }
  3662. }
  3663. const call = ( func, ...params ) => {
  3664. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3665. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3666. };
  3667. addMethodChaining( 'call', call );
  3668. const _vectorOperators = {
  3669. '==': 'equal',
  3670. '!=': 'notEqual',
  3671. '<': 'lessThan',
  3672. '>': 'greaterThan',
  3673. '<=': 'lessThanEqual',
  3674. '>=': 'greaterThanEqual',
  3675. '%': 'mod'
  3676. };
  3677. /**
  3678. * This node represents basic mathematical and logical operations like addition,
  3679. * subtraction or comparisons (e.g. `equal()`).
  3680. *
  3681. * @augments TempNode
  3682. */
  3683. class OperatorNode extends TempNode {
  3684. static get type() {
  3685. return 'OperatorNode';
  3686. }
  3687. /**
  3688. * Constructs a new operator node.
  3689. *
  3690. * @param {string} op - The operator.
  3691. * @param {Node} aNode - The first input.
  3692. * @param {Node} bNode - The second input.
  3693. * @param {...Node} params - Additional input parameters.
  3694. */
  3695. constructor( op, aNode, bNode, ...params ) {
  3696. super();
  3697. if ( params.length > 0 ) {
  3698. let finalOp = new OperatorNode( op, aNode, bNode );
  3699. for ( let i = 0; i < params.length - 1; i ++ ) {
  3700. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3701. }
  3702. aNode = finalOp;
  3703. bNode = params[ params.length - 1 ];
  3704. }
  3705. /**
  3706. * The operator.
  3707. *
  3708. * @type {string}
  3709. */
  3710. this.op = op;
  3711. /**
  3712. * The first input.
  3713. *
  3714. * @type {Node}
  3715. */
  3716. this.aNode = aNode;
  3717. /**
  3718. * The second input.
  3719. *
  3720. * @type {Node}
  3721. */
  3722. this.bNode = bNode;
  3723. /**
  3724. * This flag can be used for type testing.
  3725. *
  3726. * @type {boolean}
  3727. * @readonly
  3728. * @default true
  3729. */
  3730. this.isOperatorNode = true;
  3731. }
  3732. /**
  3733. * Returns the operator method name.
  3734. *
  3735. * @param {NodeBuilder} builder - The current node builder.
  3736. * @param {string} output - The output type.
  3737. * @returns {string} The operator method name.
  3738. */
  3739. getOperatorMethod( builder, output ) {
  3740. return builder.getMethod( _vectorOperators[ this.op ], output );
  3741. }
  3742. /**
  3743. * This method is overwritten since the node type is inferred from the operator
  3744. * and the input node types.
  3745. *
  3746. * @param {NodeBuilder} builder - The current node builder.
  3747. * @param {?string} [output=null] - The output type.
  3748. * @return {string} The node type.
  3749. */
  3750. getNodeType( builder, output = null ) {
  3751. const op = this.op;
  3752. const aNode = this.aNode;
  3753. const bNode = this.bNode;
  3754. const typeA = aNode.getNodeType( builder );
  3755. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3756. if ( typeA === 'void' || typeB === 'void' ) {
  3757. return output || 'void';
  3758. } else if ( op === '%' ) {
  3759. return typeA;
  3760. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3761. return builder.getIntegerType( typeA );
  3762. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3763. return 'bool';
  3764. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3765. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3766. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3767. } else {
  3768. // Handle matrix operations
  3769. if ( builder.isMatrix( typeA ) ) {
  3770. if ( typeB === 'float' ) {
  3771. return typeA; // matrix * scalar = matrix
  3772. } else if ( builder.isVector( typeB ) ) {
  3773. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3774. } else if ( builder.isMatrix( typeB ) ) {
  3775. return typeA; // matrix * matrix
  3776. }
  3777. } else if ( builder.isMatrix( typeB ) ) {
  3778. if ( typeA === 'float' ) {
  3779. return typeB; // scalar * matrix = matrix
  3780. } else if ( builder.isVector( typeA ) ) {
  3781. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3782. }
  3783. }
  3784. // Handle non-matrix cases
  3785. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3786. // anytype x anytype: use the greater length vector
  3787. return typeB;
  3788. }
  3789. return typeA;
  3790. }
  3791. }
  3792. generate( builder, output ) {
  3793. const op = this.op;
  3794. const { aNode, bNode } = this;
  3795. const type = this.getNodeType( builder, output );
  3796. let typeA = null;
  3797. let typeB = null;
  3798. if ( type !== 'void' ) {
  3799. typeA = aNode.getNodeType( builder );
  3800. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3801. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3802. if ( builder.isVector( typeA ) ) {
  3803. typeB = typeA;
  3804. } else if ( builder.isVector( typeB ) ) {
  3805. typeA = typeB;
  3806. } else if ( typeA !== typeB ) {
  3807. typeA = typeB = 'float';
  3808. }
  3809. } else if ( op === '>>' || op === '<<' ) {
  3810. typeA = type;
  3811. typeB = builder.changeComponentType( typeB, 'uint' );
  3812. } else if ( op === '%' ) {
  3813. typeA = type;
  3814. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3815. } else if ( builder.isMatrix( typeA ) ) {
  3816. if ( typeB === 'float' ) {
  3817. // Keep matrix type for typeA, but ensure typeB stays float
  3818. typeB = 'float';
  3819. } else if ( builder.isVector( typeB ) ) {
  3820. // matrix x vector
  3821. typeB = builder.getVectorFromMatrix( typeA );
  3822. } else if ( builder.isMatrix( typeB ) ) ; else {
  3823. typeA = typeB = type;
  3824. }
  3825. } else if ( builder.isMatrix( typeB ) ) {
  3826. if ( typeA === 'float' ) {
  3827. // Keep matrix type for typeB, but ensure typeA stays float
  3828. typeA = 'float';
  3829. } else if ( builder.isVector( typeA ) ) {
  3830. // vector x matrix
  3831. typeA = builder.getVectorFromMatrix( typeB );
  3832. } else {
  3833. typeA = typeB = type;
  3834. }
  3835. } else {
  3836. // anytype x anytype
  3837. typeA = typeB = type;
  3838. }
  3839. } else {
  3840. typeA = typeB = type;
  3841. }
  3842. const a = aNode.build( builder, typeA );
  3843. const b = bNode ? bNode.build( builder, typeB ) : null;
  3844. const fnOpSnippet = builder.getFunctionOperator( op );
  3845. if ( output !== 'void' ) {
  3846. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3847. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3848. if ( isGLSL ) {
  3849. if ( builder.isVector( typeA ) ) {
  3850. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3851. } else {
  3852. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3853. }
  3854. } else {
  3855. // WGSL
  3856. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3857. }
  3858. } else if ( op === '%' ) {
  3859. if ( builder.isInteger( typeB ) ) {
  3860. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3861. } else {
  3862. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3863. }
  3864. } else if ( op === '!' || op === '~' ) {
  3865. return builder.format( `(${op}${a})`, typeA, output );
  3866. } else if ( fnOpSnippet ) {
  3867. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3868. } else {
  3869. // Handle matrix operations
  3870. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3871. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3872. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3873. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3874. } else {
  3875. let snippet = `( ${ a } ${ op } ${ b } )`;
  3876. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3877. snippet = `all${ snippet }`;
  3878. }
  3879. return builder.format( snippet, type, output );
  3880. }
  3881. }
  3882. } else if ( typeA !== 'void' ) {
  3883. if ( fnOpSnippet ) {
  3884. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3885. } else {
  3886. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3887. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3888. } else {
  3889. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3890. }
  3891. }
  3892. }
  3893. }
  3894. serialize( data ) {
  3895. super.serialize( data );
  3896. data.op = this.op;
  3897. }
  3898. deserialize( data ) {
  3899. super.deserialize( data );
  3900. this.op = data.op;
  3901. }
  3902. }
  3903. /**
  3904. * Returns the addition of two or more value.
  3905. *
  3906. * @tsl
  3907. * @function
  3908. * @param {Node} a - The first input.
  3909. * @param {Node} b - The second input.
  3910. * @param {...Node} params - Additional input parameters.
  3911. * @returns {OperatorNode}
  3912. */
  3913. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3914. /**
  3915. * Returns the subtraction of two or more value.
  3916. *
  3917. * @tsl
  3918. * @function
  3919. * @param {Node} a - The first input.
  3920. * @param {Node} b - The second input.
  3921. * @param {...Node} params - Additional input parameters.
  3922. * @returns {OperatorNode}
  3923. */
  3924. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3925. /**
  3926. * Returns the multiplication of two or more value.
  3927. *
  3928. * @tsl
  3929. * @function
  3930. * @param {Node} a - The first input.
  3931. * @param {Node} b - The second input.
  3932. * @param {...Node} params - Additional input parameters.
  3933. * @returns {OperatorNode}
  3934. */
  3935. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3936. /**
  3937. * Returns the division of two or more value.
  3938. *
  3939. * @tsl
  3940. * @function
  3941. * @param {Node} a - The first input.
  3942. * @param {Node} b - The second input.
  3943. * @param {...Node} params - Additional input parameters.
  3944. * @returns {OperatorNode}
  3945. */
  3946. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3947. /**
  3948. * Computes the remainder of dividing the first node by the second one.
  3949. *
  3950. * @tsl
  3951. * @function
  3952. * @param {Node} a - The first input.
  3953. * @param {Node} b - The second input.
  3954. * @returns {OperatorNode}
  3955. */
  3956. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3957. /**
  3958. * Checks if two nodes are equal.
  3959. *
  3960. * @tsl
  3961. * @function
  3962. * @param {Node} a - The first input.
  3963. * @param {Node} b - The second input.
  3964. * @returns {OperatorNode}
  3965. */
  3966. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3967. /**
  3968. * Checks if two nodes are not equal.
  3969. *
  3970. * @tsl
  3971. * @function
  3972. * @param {Node} a - The first input.
  3973. * @param {Node} b - The second input.
  3974. * @returns {OperatorNode}
  3975. */
  3976. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3977. /**
  3978. * Checks if the first node is less than the second.
  3979. *
  3980. * @tsl
  3981. * @function
  3982. * @param {Node} a - The first input.
  3983. * @param {Node} b - The second input.
  3984. * @returns {OperatorNode}
  3985. */
  3986. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3987. /**
  3988. * Checks if the first node is greater than the second.
  3989. *
  3990. * @tsl
  3991. * @function
  3992. * @param {Node} a - The first input.
  3993. * @param {Node} b - The second input.
  3994. * @returns {OperatorNode}
  3995. */
  3996. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3997. /**
  3998. * Checks if the first node is less than or equal to the second.
  3999. *
  4000. * @tsl
  4001. * @function
  4002. * @param {Node} a - The first input.
  4003. * @param {Node} b - The second input.
  4004. * @returns {OperatorNode}
  4005. */
  4006. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4007. /**
  4008. * Checks if the first node is greater than or equal to the second.
  4009. *
  4010. * @tsl
  4011. * @function
  4012. * @param {Node} a - The first input.
  4013. * @param {Node} b - The second input.
  4014. * @returns {OperatorNode}
  4015. */
  4016. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4017. /**
  4018. * Performs a logical AND operation on multiple nodes.
  4019. *
  4020. * @tsl
  4021. * @function
  4022. * @param {...Node} nodes - The input nodes to be combined using AND.
  4023. * @returns {OperatorNode}
  4024. */
  4025. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4026. /**
  4027. * Performs a logical OR operation on multiple nodes.
  4028. *
  4029. * @tsl
  4030. * @function
  4031. * @param {...Node} nodes - The input nodes to be combined using OR.
  4032. * @returns {OperatorNode}
  4033. */
  4034. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4035. /**
  4036. * Performs logical NOT on a node.
  4037. *
  4038. * @tsl
  4039. * @function
  4040. * @param {Node} value - The value.
  4041. * @returns {OperatorNode}
  4042. */
  4043. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4044. /**
  4045. * Performs logical XOR on two nodes.
  4046. *
  4047. * @tsl
  4048. * @function
  4049. * @param {Node} a - The first input.
  4050. * @param {Node} b - The second input.
  4051. * @returns {OperatorNode}
  4052. */
  4053. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4054. /**
  4055. * Performs bitwise AND on two nodes.
  4056. *
  4057. * @tsl
  4058. * @function
  4059. * @param {Node} a - The first input.
  4060. * @param {Node} b - The second input.
  4061. * @returns {OperatorNode}
  4062. */
  4063. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4064. /**
  4065. * Performs bitwise NOT on a node.
  4066. *
  4067. * @tsl
  4068. * @function
  4069. * @param {Node} a - The first input.
  4070. * @param {Node} b - The second input.
  4071. * @returns {OperatorNode}
  4072. */
  4073. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  4074. /**
  4075. * Performs bitwise OR on two nodes.
  4076. *
  4077. * @tsl
  4078. * @function
  4079. * @param {Node} a - The first input.
  4080. * @param {Node} b - The second input.
  4081. * @returns {OperatorNode}
  4082. */
  4083. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4084. /**
  4085. * Performs bitwise XOR on two nodes.
  4086. *
  4087. * @tsl
  4088. * @function
  4089. * @param {Node} a - The first input.
  4090. * @param {Node} b - The second input.
  4091. * @returns {OperatorNode}
  4092. */
  4093. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4094. /**
  4095. * Shifts a node to the left.
  4096. *
  4097. * @tsl
  4098. * @function
  4099. * @param {Node} a - The node to shift.
  4100. * @param {Node} b - The value to shift.
  4101. * @returns {OperatorNode}
  4102. */
  4103. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4104. /**
  4105. * Shifts a node to the right.
  4106. *
  4107. * @tsl
  4108. * @function
  4109. * @param {Node} a - The node to shift.
  4110. * @param {Node} b - The value to shift.
  4111. * @returns {OperatorNode}
  4112. */
  4113. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4114. /**
  4115. * Increments a node by 1.
  4116. *
  4117. * @tsl
  4118. * @function
  4119. * @param {Node} a - The node to increment.
  4120. * @returns {OperatorNode}
  4121. */
  4122. const incrementBefore = Fn( ( [ a ] ) => {
  4123. a.addAssign( 1 );
  4124. return a;
  4125. } );
  4126. /**
  4127. * Decrements a node by 1.
  4128. *
  4129. * @tsl
  4130. * @function
  4131. * @param {Node} a - The node to decrement.
  4132. * @returns {OperatorNode}
  4133. */
  4134. const decrementBefore = Fn( ( [ a ] ) => {
  4135. a.subAssign( 1 );
  4136. return a;
  4137. } );
  4138. /**
  4139. * Increments a node by 1 and returns the previous value.
  4140. *
  4141. * @tsl
  4142. * @function
  4143. * @param {Node} a - The node to increment.
  4144. * @returns {OperatorNode}
  4145. */
  4146. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4147. const temp = int( a ).toConst();
  4148. a.addAssign( 1 );
  4149. return temp;
  4150. } );
  4151. /**
  4152. * Decrements a node by 1 and returns the previous value.
  4153. *
  4154. * @tsl
  4155. * @function
  4156. * @param {Node} a - The node to decrement.
  4157. * @returns {OperatorNode}
  4158. */
  4159. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4160. const temp = int( a ).toConst();
  4161. a.subAssign( 1 );
  4162. return temp;
  4163. } );
  4164. addMethodChaining( 'add', add );
  4165. addMethodChaining( 'sub', sub );
  4166. addMethodChaining( 'mul', mul );
  4167. addMethodChaining( 'div', div );
  4168. addMethodChaining( 'mod', mod );
  4169. addMethodChaining( 'equal', equal );
  4170. addMethodChaining( 'notEqual', notEqual );
  4171. addMethodChaining( 'lessThan', lessThan );
  4172. addMethodChaining( 'greaterThan', greaterThan );
  4173. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4174. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4175. addMethodChaining( 'and', and );
  4176. addMethodChaining( 'or', or );
  4177. addMethodChaining( 'not', not );
  4178. addMethodChaining( 'xor', xor );
  4179. addMethodChaining( 'bitAnd', bitAnd );
  4180. addMethodChaining( 'bitNot', bitNot );
  4181. addMethodChaining( 'bitOr', bitOr );
  4182. addMethodChaining( 'bitXor', bitXor );
  4183. addMethodChaining( 'shiftLeft', shiftLeft );
  4184. addMethodChaining( 'shiftRight', shiftRight );
  4185. addMethodChaining( 'incrementBefore', incrementBefore );
  4186. addMethodChaining( 'decrementBefore', decrementBefore );
  4187. addMethodChaining( 'increment', increment );
  4188. addMethodChaining( 'decrement', decrement );
  4189. /**
  4190. * @tsl
  4191. * @function
  4192. * @deprecated since r175. Use {@link mod} instead.
  4193. *
  4194. * @param {Node} a - The first input.
  4195. * @param {Node} b - The second input.
  4196. * @returns {OperatorNode}
  4197. */
  4198. const modInt = ( a, b ) => { // @deprecated, r175
  4199. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4200. return mod( int( a ), int( b ) );
  4201. };
  4202. addMethodChaining( 'modInt', modInt );
  4203. /**
  4204. * This node represents a variety of mathematical methods available in shaders.
  4205. * They are divided into three categories:
  4206. *
  4207. * - Methods with one input like `sin`, `cos` or `normalize`.
  4208. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4209. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4210. *
  4211. * @augments TempNode
  4212. */
  4213. class MathNode extends TempNode {
  4214. static get type() {
  4215. return 'MathNode';
  4216. }
  4217. /**
  4218. * Constructs a new math node.
  4219. *
  4220. * @param {string} method - The method name.
  4221. * @param {Node} aNode - The first input.
  4222. * @param {?Node} [bNode=null] - The second input.
  4223. * @param {?Node} [cNode=null] - The third input.
  4224. */
  4225. constructor( method, aNode, bNode = null, cNode = null ) {
  4226. super();
  4227. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4228. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4229. let finalOp = new MathNode( method, aNode, bNode );
  4230. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4231. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4232. }
  4233. aNode = finalOp;
  4234. bNode = arguments[ arguments.length - 1 ];
  4235. cNode = null;
  4236. }
  4237. /**
  4238. * The method name.
  4239. *
  4240. * @type {string}
  4241. */
  4242. this.method = method;
  4243. /**
  4244. * The first input.
  4245. *
  4246. * @type {Node}
  4247. */
  4248. this.aNode = aNode;
  4249. /**
  4250. * The second input.
  4251. *
  4252. * @type {?Node}
  4253. * @default null
  4254. */
  4255. this.bNode = bNode;
  4256. /**
  4257. * The third input.
  4258. *
  4259. * @type {?Node}
  4260. * @default null
  4261. */
  4262. this.cNode = cNode;
  4263. /**
  4264. * This flag can be used for type testing.
  4265. *
  4266. * @type {boolean}
  4267. * @readonly
  4268. * @default true
  4269. */
  4270. this.isMathNode = true;
  4271. }
  4272. /**
  4273. * The input type is inferred from the node types of the input nodes.
  4274. *
  4275. * @param {NodeBuilder} builder - The current node builder.
  4276. * @return {string} The input type.
  4277. */
  4278. getInputType( builder ) {
  4279. const aType = this.aNode.getNodeType( builder );
  4280. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4281. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4282. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4283. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4284. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4285. if ( aLen > bLen && aLen > cLen ) {
  4286. return aType;
  4287. } else if ( bLen > cLen ) {
  4288. return bType;
  4289. } else if ( cLen > aLen ) {
  4290. return cType;
  4291. }
  4292. return aType;
  4293. }
  4294. /**
  4295. * The selected method as well as the input type determine the node type of this node.
  4296. *
  4297. * @param {NodeBuilder} builder - The current node builder.
  4298. * @return {string} The node type.
  4299. */
  4300. getNodeType( builder ) {
  4301. const method = this.method;
  4302. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4303. return 'float';
  4304. } else if ( method === MathNode.CROSS ) {
  4305. return 'vec3';
  4306. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4307. return 'bool';
  4308. } else if ( method === MathNode.EQUALS ) {
  4309. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4310. } else {
  4311. return this.getInputType( builder );
  4312. }
  4313. }
  4314. setup( builder ) {
  4315. const { aNode, bNode, method } = this;
  4316. let outputNode = null;
  4317. if ( method === MathNode.ONE_MINUS ) {
  4318. outputNode = sub( 1.0, aNode );
  4319. } else if ( method === MathNode.RECIPROCAL ) {
  4320. outputNode = div( 1.0, aNode );
  4321. } else if ( method === MathNode.DIFFERENCE ) {
  4322. outputNode = abs( sub( aNode, bNode ) );
  4323. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4324. // dir can be either a direction vector or a normal vector
  4325. // upper-left 3x3 of matrix is assumed to be orthogonal
  4326. let tA = aNode;
  4327. let tB = bNode;
  4328. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4329. tB = vec4( vec3( tB ), 0.0 );
  4330. } else {
  4331. tA = vec4( vec3( tA ), 0.0 );
  4332. }
  4333. const mulNode = mul( tA, tB ).xyz;
  4334. outputNode = normalize( mulNode );
  4335. }
  4336. if ( outputNode !== null ) {
  4337. return outputNode;
  4338. } else {
  4339. return super.setup( builder );
  4340. }
  4341. }
  4342. generate( builder, output ) {
  4343. const properties = builder.getNodeProperties( this );
  4344. if ( properties.outputNode ) {
  4345. return super.generate( builder, output );
  4346. }
  4347. let method = this.method;
  4348. const type = this.getNodeType( builder );
  4349. const inputType = this.getInputType( builder );
  4350. const a = this.aNode;
  4351. const b = this.bNode;
  4352. const c = this.cNode;
  4353. const coordinateSystem = builder.renderer.coordinateSystem;
  4354. if ( method === MathNode.NEGATE ) {
  4355. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4356. } else {
  4357. const params = [];
  4358. if ( method === MathNode.CROSS ) {
  4359. params.push(
  4360. a.build( builder, type ),
  4361. b.build( builder, type )
  4362. );
  4363. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4364. params.push(
  4365. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4366. b.build( builder, inputType )
  4367. );
  4368. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4369. params.push(
  4370. a.build( builder, inputType ),
  4371. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4372. );
  4373. } else if ( method === MathNode.REFRACT ) {
  4374. params.push(
  4375. a.build( builder, inputType ),
  4376. b.build( builder, inputType ),
  4377. c.build( builder, 'float' )
  4378. );
  4379. } else if ( method === MathNode.MIX ) {
  4380. params.push(
  4381. a.build( builder, inputType ),
  4382. b.build( builder, inputType ),
  4383. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4384. );
  4385. } else {
  4386. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4387. method = 'atan2';
  4388. }
  4389. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4390. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4391. method = '/*' + method + '*/';
  4392. }
  4393. params.push( a.build( builder, inputType ) );
  4394. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4395. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4396. }
  4397. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4398. }
  4399. }
  4400. serialize( data ) {
  4401. super.serialize( data );
  4402. data.method = this.method;
  4403. }
  4404. deserialize( data ) {
  4405. super.deserialize( data );
  4406. this.method = data.method;
  4407. }
  4408. }
  4409. // 1 input
  4410. MathNode.ALL = 'all';
  4411. MathNode.ANY = 'any';
  4412. MathNode.RADIANS = 'radians';
  4413. MathNode.DEGREES = 'degrees';
  4414. MathNode.EXP = 'exp';
  4415. MathNode.EXP2 = 'exp2';
  4416. MathNode.LOG = 'log';
  4417. MathNode.LOG2 = 'log2';
  4418. MathNode.SQRT = 'sqrt';
  4419. MathNode.INVERSE_SQRT = 'inversesqrt';
  4420. MathNode.FLOOR = 'floor';
  4421. MathNode.CEIL = 'ceil';
  4422. MathNode.NORMALIZE = 'normalize';
  4423. MathNode.FRACT = 'fract';
  4424. MathNode.SIN = 'sin';
  4425. MathNode.COS = 'cos';
  4426. MathNode.TAN = 'tan';
  4427. MathNode.ASIN = 'asin';
  4428. MathNode.ACOS = 'acos';
  4429. MathNode.ATAN = 'atan';
  4430. MathNode.ABS = 'abs';
  4431. MathNode.SIGN = 'sign';
  4432. MathNode.LENGTH = 'length';
  4433. MathNode.NEGATE = 'negate';
  4434. MathNode.ONE_MINUS = 'oneMinus';
  4435. MathNode.DFDX = 'dFdx';
  4436. MathNode.DFDY = 'dFdy';
  4437. MathNode.ROUND = 'round';
  4438. MathNode.RECIPROCAL = 'reciprocal';
  4439. MathNode.TRUNC = 'trunc';
  4440. MathNode.FWIDTH = 'fwidth';
  4441. MathNode.TRANSPOSE = 'transpose';
  4442. MathNode.DETERMINANT = 'determinant';
  4443. MathNode.INVERSE = 'inverse';
  4444. // 2 inputs
  4445. MathNode.BITCAST = 'bitcast';
  4446. MathNode.EQUALS = 'equals';
  4447. MathNode.MIN = 'min';
  4448. MathNode.MAX = 'max';
  4449. MathNode.STEP = 'step';
  4450. MathNode.REFLECT = 'reflect';
  4451. MathNode.DISTANCE = 'distance';
  4452. MathNode.DIFFERENCE = 'difference';
  4453. MathNode.DOT = 'dot';
  4454. MathNode.CROSS = 'cross';
  4455. MathNode.POW = 'pow';
  4456. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4457. // 3 inputs
  4458. MathNode.MIX = 'mix';
  4459. MathNode.CLAMP = 'clamp';
  4460. MathNode.REFRACT = 'refract';
  4461. MathNode.SMOOTHSTEP = 'smoothstep';
  4462. MathNode.FACEFORWARD = 'faceforward';
  4463. // 1 inputs
  4464. /**
  4465. * A small value used to handle floating-point precision errors.
  4466. *
  4467. * @tsl
  4468. * @type {Node<float>}
  4469. */
  4470. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4471. /**
  4472. * Represents infinity.
  4473. *
  4474. * @tsl
  4475. * @type {Node<float>}
  4476. */
  4477. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4478. /**
  4479. * Represents PI.
  4480. *
  4481. * @tsl
  4482. * @type {Node<float>}
  4483. */
  4484. const PI = /*@__PURE__*/ float( Math.PI );
  4485. /**
  4486. * Represents PI * 2.
  4487. *
  4488. * @tsl
  4489. * @type {Node<float>}
  4490. */
  4491. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4492. /**
  4493. * Returns `true` if all components of `x` are `true`.
  4494. *
  4495. * @tsl
  4496. * @function
  4497. * @param {Node | number} x - The parameter.
  4498. * @returns {Node<bool>}
  4499. */
  4500. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4501. /**
  4502. * Returns `true` if any components of `x` are `true`.
  4503. *
  4504. * @tsl
  4505. * @function
  4506. * @param {Node | number} x - The parameter.
  4507. * @returns {Node<bool>}
  4508. */
  4509. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4510. /**
  4511. * Converts a quantity in degrees to radians.
  4512. *
  4513. * @tsl
  4514. * @function
  4515. * @param {Node | number} x - The input in degrees.
  4516. * @returns {Node}
  4517. */
  4518. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4519. /**
  4520. * Convert a quantity in radians to degrees.
  4521. *
  4522. * @tsl
  4523. * @function
  4524. * @param {Node | number} x - The input in radians.
  4525. * @returns {Node}
  4526. */
  4527. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4528. /**
  4529. * Returns the natural exponentiation of the parameter.
  4530. *
  4531. * @tsl
  4532. * @function
  4533. * @param {Node | number} x - The parameter.
  4534. * @returns {Node}
  4535. */
  4536. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4537. /**
  4538. * Returns 2 raised to the power of the parameter.
  4539. *
  4540. * @tsl
  4541. * @function
  4542. * @param {Node | number} x - The parameter.
  4543. * @returns {Node}
  4544. */
  4545. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4546. /**
  4547. * Returns the natural logarithm of the parameter.
  4548. *
  4549. * @tsl
  4550. * @function
  4551. * @param {Node | number} x - The parameter.
  4552. * @returns {Node}
  4553. */
  4554. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4555. /**
  4556. * Returns the base 2 logarithm of the parameter.
  4557. *
  4558. * @tsl
  4559. * @function
  4560. * @param {Node | number} x - The parameter.
  4561. * @returns {Node}
  4562. */
  4563. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4564. /**
  4565. * Returns the square root of the parameter.
  4566. *
  4567. * @tsl
  4568. * @function
  4569. * @param {Node | number} x - The parameter.
  4570. * @returns {Node}
  4571. */
  4572. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4573. /**
  4574. * Returns the inverse of the square root of the parameter.
  4575. *
  4576. * @tsl
  4577. * @function
  4578. * @param {Node | number} x - The parameter.
  4579. * @returns {Node}
  4580. */
  4581. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4582. /**
  4583. * Finds the nearest integer less than or equal to the parameter.
  4584. *
  4585. * @tsl
  4586. * @function
  4587. * @param {Node | number} x - The parameter.
  4588. * @returns {Node}
  4589. */
  4590. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4591. /**
  4592. * Finds the nearest integer that is greater than or equal to the parameter.
  4593. *
  4594. * @tsl
  4595. * @function
  4596. * @param {Node | number} x - The parameter.
  4597. * @returns {Node}
  4598. */
  4599. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4600. /**
  4601. * Calculates the unit vector in the same direction as the original vector.
  4602. *
  4603. * @tsl
  4604. * @function
  4605. * @param {Node} x - The input vector.
  4606. * @returns {Node}
  4607. */
  4608. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4609. /**
  4610. * Computes the fractional part of the parameter.
  4611. *
  4612. * @tsl
  4613. * @function
  4614. * @param {Node | number} x - The parameter.
  4615. * @returns {Node}
  4616. */
  4617. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4618. /**
  4619. * Returns the sine of the parameter.
  4620. *
  4621. * @tsl
  4622. * @function
  4623. * @param {Node | number} x - The parameter.
  4624. * @returns {Node}
  4625. */
  4626. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4627. /**
  4628. * Returns the cosine of the parameter.
  4629. *
  4630. * @tsl
  4631. * @function
  4632. * @param {Node | number} x - The parameter.
  4633. * @returns {Node}
  4634. */
  4635. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4636. /**
  4637. * Returns the tangent of the parameter.
  4638. *
  4639. * @tsl
  4640. * @function
  4641. * @param {Node | number} x - The parameter.
  4642. * @returns {Node}
  4643. */
  4644. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4645. /**
  4646. * Returns the arcsine of the parameter.
  4647. *
  4648. * @tsl
  4649. * @function
  4650. * @param {Node | number} x - The parameter.
  4651. * @returns {Node}
  4652. */
  4653. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4654. /**
  4655. * Returns the arccosine of the parameter.
  4656. *
  4657. * @tsl
  4658. * @function
  4659. * @param {Node | number} x - The parameter.
  4660. * @returns {Node}
  4661. */
  4662. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4663. /**
  4664. * Returns the arc-tangent of the parameter.
  4665. * If two parameters are provided, the result is `atan2(y/x)`.
  4666. *
  4667. * @tsl
  4668. * @function
  4669. * @param {Node | number} y - The y parameter.
  4670. * @param {?(Node | number)} x - The x parameter.
  4671. * @returns {Node}
  4672. */
  4673. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4674. /**
  4675. * Returns the absolute value of the parameter.
  4676. *
  4677. * @tsl
  4678. * @function
  4679. * @param {Node | number} x - The parameter.
  4680. * @returns {Node}
  4681. */
  4682. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4683. /**
  4684. * Extracts the sign of the parameter.
  4685. *
  4686. * @tsl
  4687. * @function
  4688. * @param {Node | number} x - The parameter.
  4689. * @returns {Node}
  4690. */
  4691. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4692. /**
  4693. * Calculates the length of a vector.
  4694. *
  4695. * @tsl
  4696. * @function
  4697. * @param {Node} x - The parameter.
  4698. * @returns {Node<float>}
  4699. */
  4700. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4701. /**
  4702. * Negates the value of the parameter (-x).
  4703. *
  4704. * @tsl
  4705. * @function
  4706. * @param {Node | number} x - The parameter.
  4707. * @returns {Node}
  4708. */
  4709. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4710. /**
  4711. * Return `1` minus the parameter.
  4712. *
  4713. * @tsl
  4714. * @function
  4715. * @param {Node | number} x - The parameter.
  4716. * @returns {Node}
  4717. */
  4718. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4719. /**
  4720. * Returns the partial derivative of the parameter with respect to x.
  4721. *
  4722. * @tsl
  4723. * @function
  4724. * @param {Node | number} x - The parameter.
  4725. * @returns {Node}
  4726. */
  4727. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4728. /**
  4729. * Returns the partial derivative of the parameter with respect to y.
  4730. *
  4731. * @tsl
  4732. * @function
  4733. * @param {Node | number} x - The parameter.
  4734. * @returns {Node}
  4735. */
  4736. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4737. /**
  4738. * Rounds the parameter to the nearest integer.
  4739. *
  4740. * @tsl
  4741. * @function
  4742. * @param {Node | number} x - The parameter.
  4743. * @returns {Node}
  4744. */
  4745. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4746. /**
  4747. * Returns the reciprocal of the parameter `(1/x)`.
  4748. *
  4749. * @tsl
  4750. * @function
  4751. * @param {Node | number} x - The parameter.
  4752. * @returns {Node}
  4753. */
  4754. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4755. /**
  4756. * Truncates the parameter, removing the fractional part.
  4757. *
  4758. * @tsl
  4759. * @function
  4760. * @param {Node | number} x - The parameter.
  4761. * @returns {Node}
  4762. */
  4763. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4764. /**
  4765. * Returns the sum of the absolute derivatives in x and y.
  4766. *
  4767. * @tsl
  4768. * @function
  4769. * @param {Node | number} x - The parameter.
  4770. * @returns {Node}
  4771. */
  4772. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4773. /**
  4774. * Returns the transpose of a matrix.
  4775. *
  4776. * @tsl
  4777. * @function
  4778. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4779. * @returns {Node}
  4780. */
  4781. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4782. /**
  4783. * Returns the determinant of a matrix.
  4784. *
  4785. * @tsl
  4786. * @function
  4787. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4788. * @returns {Node<float>}
  4789. */
  4790. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4791. /**
  4792. * Returns the inverse of a matrix.
  4793. *
  4794. * @tsl
  4795. * @function
  4796. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4797. * @returns {Node<mat2|mat3|mat4>}
  4798. */
  4799. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4800. // 2 inputs
  4801. /**
  4802. * Reinterpret the bit representation of a value in one type as a value in another type.
  4803. *
  4804. * @tsl
  4805. * @function
  4806. * @param {Node | number} x - The parameter.
  4807. * @param {string} y - The new type.
  4808. * @returns {Node}
  4809. */
  4810. const bitcast = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4811. /**
  4812. * Returns `true` if `x` equals `y`.
  4813. *
  4814. * @tsl
  4815. * @function
  4816. * @param {Node | number} x - The first parameter.
  4817. * @param {Node | number} y - The second parameter.
  4818. * @deprecated since r175. Use {@link equal} instead.
  4819. * @returns {Node<bool>}
  4820. */
  4821. const equals = ( x, y ) => { // @deprecated, r172
  4822. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4823. return equal( x, y );
  4824. };
  4825. /**
  4826. * Returns the least of the given values.
  4827. *
  4828. * @tsl
  4829. * @function
  4830. * @param {...(Node | number)} values - The values to compare.
  4831. * @returns {Node}
  4832. */
  4833. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4834. /**
  4835. * Returns the greatest of the given values.
  4836. *
  4837. * @tsl
  4838. * @function
  4839. * @param {...(Node | number)} values - The values to compare.
  4840. * @returns {Node}
  4841. */
  4842. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4843. /**
  4844. * Generate a step function by comparing two values.
  4845. *
  4846. * @tsl
  4847. * @function
  4848. * @param {Node | number} x - The y parameter.
  4849. * @param {Node | number} y - The x parameter.
  4850. * @returns {Node}
  4851. */
  4852. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4853. /**
  4854. * Calculates the reflection direction for an incident vector.
  4855. *
  4856. * @tsl
  4857. * @function
  4858. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4859. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4860. * @returns {Node<vec2|vec3|vec4>}
  4861. */
  4862. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4863. /**
  4864. * Calculates the distance between two points.
  4865. *
  4866. * @tsl
  4867. * @function
  4868. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4869. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4870. * @returns {Node<float>}
  4871. */
  4872. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4873. /**
  4874. * Calculates the absolute difference between two values.
  4875. *
  4876. * @tsl
  4877. * @function
  4878. * @param {Node | number} x - The first parameter.
  4879. * @param {Node | number} y - The second parameter.
  4880. * @returns {Node}
  4881. */
  4882. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4883. /**
  4884. * Calculates the dot product of two vectors.
  4885. *
  4886. * @tsl
  4887. * @function
  4888. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4889. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4890. * @returns {Node<float>}
  4891. */
  4892. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4893. /**
  4894. * Calculates the cross product of two vectors.
  4895. *
  4896. * @tsl
  4897. * @function
  4898. * @param {Node<vec2|vec3>} x - The first vector.
  4899. * @param {Node<vec2|vec3>} y - The second vector.
  4900. * @returns {Node<float|vec3>}
  4901. */
  4902. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4903. /**
  4904. * Return the value of the first parameter raised to the power of the second one.
  4905. *
  4906. * @tsl
  4907. * @function
  4908. * @param {Node | number} x - The first parameter.
  4909. * @param {Node | number} y - The second parameter.
  4910. * @returns {Node}
  4911. */
  4912. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  4913. /**
  4914. * Returns the square of the parameter.
  4915. *
  4916. * @tsl
  4917. * @function
  4918. * @param {Node | number} x - The first parameter.
  4919. * @returns {Node}
  4920. */
  4921. const pow2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4922. /**
  4923. * Returns the cube of the parameter.
  4924. *
  4925. * @tsl
  4926. * @function
  4927. * @param {Node | number} x - The first parameter.
  4928. * @returns {Node}
  4929. */
  4930. const pow3 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4931. /**
  4932. * Returns the fourth power of the parameter.
  4933. *
  4934. * @tsl
  4935. * @function
  4936. * @param {Node | number} x - The first parameter.
  4937. * @returns {Node}
  4938. */
  4939. const pow4 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4940. /**
  4941. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4942. *
  4943. * @tsl
  4944. * @function
  4945. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4946. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4947. * @returns {Node}
  4948. */
  4949. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4950. /**
  4951. * Returns the cube root of a number.
  4952. *
  4953. * @tsl
  4954. * @function
  4955. * @param {Node | number} a - The first parameter.
  4956. * @returns {Node}
  4957. */
  4958. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4959. /**
  4960. * Calculate the squared length of a vector.
  4961. *
  4962. * @tsl
  4963. * @function
  4964. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4965. * @returns {Node<float>}
  4966. */
  4967. const lengthSq = ( a ) => dot( a, a );
  4968. /**
  4969. * Linearly interpolates between two values.
  4970. *
  4971. * @tsl
  4972. * @function
  4973. * @param {Node | number} a - The first parameter.
  4974. * @param {Node | number} b - The second parameter.
  4975. * @param {Node | number} t - The interpolation value.
  4976. * @returns {Node}
  4977. */
  4978. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4979. /**
  4980. * Constrains a value to lie between two further values.
  4981. *
  4982. * @tsl
  4983. * @function
  4984. * @param {Node | number} value - The value to constrain.
  4985. * @param {Node | number} [low=0] - The lower bound.
  4986. * @param {Node | number} [high=1] - The upper bound.
  4987. * @returns {Node}
  4988. */
  4989. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4990. /**
  4991. * Constrains a value between `0` and `1`.
  4992. *
  4993. * @tsl
  4994. * @function
  4995. * @param {Node | number} value - The value to constrain.
  4996. * @returns {Node}
  4997. */
  4998. const saturate = ( value ) => clamp( value );
  4999. /**
  5000. * Calculates the refraction direction for an incident vector.
  5001. *
  5002. * @tsl
  5003. * @function
  5004. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5005. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5006. * @param {Node<float>} eta - The ratio of indices of refraction.
  5007. * @returns {Node<vec2|vec3|vec4>}
  5008. */
  5009. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5010. /**
  5011. * Performs a Hermite interpolation between two values.
  5012. *
  5013. * @tsl
  5014. * @function
  5015. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5016. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5017. * @param {Node | number} x - The source value for interpolation.
  5018. * @returns {Node}
  5019. */
  5020. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5021. /**
  5022. * Returns a vector pointing in the same direction as another.
  5023. *
  5024. * @tsl
  5025. * @function
  5026. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5027. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5028. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5029. * @returns {Node<vec2|vec3|vec4>}
  5030. */
  5031. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5032. /**
  5033. * Returns a random value for the given uv.
  5034. *
  5035. * @tsl
  5036. * @function
  5037. * @param {Node<vec2>} uv - The uv node.
  5038. * @returns {Node<float>}
  5039. */
  5040. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5041. const a = 12.9898, b = 78.233, c = 43758.5453;
  5042. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5043. return fract( sin( sn ).mul( c ) );
  5044. } );
  5045. /**
  5046. * Alias for `mix()` with a different parameter order.
  5047. *
  5048. * @tsl
  5049. * @function
  5050. * @param {Node | number} t - The interpolation value.
  5051. * @param {Node | number} e1 - The first parameter.
  5052. * @param {Node | number} e2 - The second parameter.
  5053. * @returns {Node}
  5054. */
  5055. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5056. /**
  5057. * Alias for `smoothstep()` with a different parameter order.
  5058. *
  5059. * @tsl
  5060. * @function
  5061. * @param {Node | number} x - The source value for interpolation.
  5062. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5063. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5064. * @returns {Node}
  5065. */
  5066. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5067. /**
  5068. * Alias for `step()` with a different parameter order.
  5069. *
  5070. * @tsl
  5071. * @function
  5072. * @param {Node | number} x - The source value for interpolation.
  5073. * @param {Node | number} edge - The edge value.
  5074. * @returns {Node}
  5075. */
  5076. const stepElement = ( x, edge ) => step( edge, x );
  5077. /**
  5078. * Returns the arc-tangent of the quotient of its parameters.
  5079. *
  5080. * @tsl
  5081. * @function
  5082. * @deprecated since r172. Use {@link atan} instead.
  5083. *
  5084. * @param {Node | number} y - The y parameter.
  5085. * @param {Node | number} x - The x parameter.
  5086. * @returns {Node}
  5087. */
  5088. const atan2 = ( y, x ) => { // @deprecated, r172
  5089. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  5090. return atan( y, x );
  5091. };
  5092. // GLSL alias function
  5093. const faceforward = faceForward;
  5094. const inversesqrt = inverseSqrt;
  5095. // Method chaining
  5096. addMethodChaining( 'all', all );
  5097. addMethodChaining( 'any', any );
  5098. addMethodChaining( 'equals', equals );
  5099. addMethodChaining( 'radians', radians );
  5100. addMethodChaining( 'degrees', degrees );
  5101. addMethodChaining( 'exp', exp );
  5102. addMethodChaining( 'exp2', exp2 );
  5103. addMethodChaining( 'log', log );
  5104. addMethodChaining( 'log2', log2 );
  5105. addMethodChaining( 'sqrt', sqrt );
  5106. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5107. addMethodChaining( 'floor', floor );
  5108. addMethodChaining( 'ceil', ceil );
  5109. addMethodChaining( 'normalize', normalize );
  5110. addMethodChaining( 'fract', fract );
  5111. addMethodChaining( 'sin', sin );
  5112. addMethodChaining( 'cos', cos );
  5113. addMethodChaining( 'tan', tan );
  5114. addMethodChaining( 'asin', asin );
  5115. addMethodChaining( 'acos', acos );
  5116. addMethodChaining( 'atan', atan );
  5117. addMethodChaining( 'abs', abs );
  5118. addMethodChaining( 'sign', sign );
  5119. addMethodChaining( 'length', length );
  5120. addMethodChaining( 'lengthSq', lengthSq );
  5121. addMethodChaining( 'negate', negate );
  5122. addMethodChaining( 'oneMinus', oneMinus );
  5123. addMethodChaining( 'dFdx', dFdx );
  5124. addMethodChaining( 'dFdy', dFdy );
  5125. addMethodChaining( 'round', round );
  5126. addMethodChaining( 'reciprocal', reciprocal );
  5127. addMethodChaining( 'trunc', trunc );
  5128. addMethodChaining( 'fwidth', fwidth );
  5129. addMethodChaining( 'atan2', atan2 );
  5130. addMethodChaining( 'min', min$1 );
  5131. addMethodChaining( 'max', max$1 );
  5132. addMethodChaining( 'step', stepElement );
  5133. addMethodChaining( 'reflect', reflect );
  5134. addMethodChaining( 'distance', distance );
  5135. addMethodChaining( 'dot', dot );
  5136. addMethodChaining( 'cross', cross );
  5137. addMethodChaining( 'pow', pow );
  5138. addMethodChaining( 'pow2', pow2 );
  5139. addMethodChaining( 'pow3', pow3 );
  5140. addMethodChaining( 'pow4', pow4 );
  5141. addMethodChaining( 'transformDirection', transformDirection );
  5142. addMethodChaining( 'mix', mixElement );
  5143. addMethodChaining( 'clamp', clamp );
  5144. addMethodChaining( 'refract', refract );
  5145. addMethodChaining( 'smoothstep', smoothstepElement );
  5146. addMethodChaining( 'faceForward', faceForward );
  5147. addMethodChaining( 'difference', difference );
  5148. addMethodChaining( 'saturate', saturate );
  5149. addMethodChaining( 'cbrt', cbrt );
  5150. addMethodChaining( 'transpose', transpose );
  5151. addMethodChaining( 'determinant', determinant );
  5152. addMethodChaining( 'inverse', inverse );
  5153. addMethodChaining( 'rand', rand );
  5154. /**
  5155. * Represents a logical `if/else` statement. Can be used as an alternative
  5156. * to the `If()`/`Else()` syntax.
  5157. *
  5158. * The corresponding TSL `select()` looks like so:
  5159. * ```js
  5160. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5161. * ```
  5162. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5163. * determine the outcome of the entire statement.
  5164. *
  5165. * @augments Node
  5166. */
  5167. class ConditionalNode extends Node {
  5168. static get type() {
  5169. return 'ConditionalNode';
  5170. }
  5171. /**
  5172. * Constructs a new conditional node.
  5173. *
  5174. * @param {Node} condNode - The node that defines the condition.
  5175. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5176. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5177. */
  5178. constructor( condNode, ifNode, elseNode = null ) {
  5179. super();
  5180. /**
  5181. * The node that defines the condition.
  5182. *
  5183. * @type {Node}
  5184. */
  5185. this.condNode = condNode;
  5186. /**
  5187. * The node that is evaluate when the condition ends up `true`.
  5188. *
  5189. * @type {Node}
  5190. */
  5191. this.ifNode = ifNode;
  5192. /**
  5193. * The node that is evaluate when the condition ends up `false`.
  5194. *
  5195. * @type {?Node}
  5196. * @default null
  5197. */
  5198. this.elseNode = elseNode;
  5199. }
  5200. /**
  5201. * This method is overwritten since the node type is inferred from the if/else
  5202. * nodes.
  5203. *
  5204. * @param {NodeBuilder} builder - The current node builder.
  5205. * @return {string} The node type.
  5206. */
  5207. getNodeType( builder ) {
  5208. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5209. if ( ifNode === undefined ) {
  5210. // fallback setup
  5211. builder.flowBuildStage( this, 'setup' );
  5212. return this.getNodeType( builder );
  5213. }
  5214. const ifType = ifNode.getNodeType( builder );
  5215. if ( elseNode !== null ) {
  5216. const elseType = elseNode.getNodeType( builder );
  5217. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5218. return elseType;
  5219. }
  5220. }
  5221. return ifType;
  5222. }
  5223. setup( builder ) {
  5224. const condNode = this.condNode.cache();
  5225. const ifNode = this.ifNode.cache();
  5226. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  5227. //
  5228. const currentNodeBlock = builder.context.nodeBlock;
  5229. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5230. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5231. //
  5232. const isUniformFlow = builder.context.uniformFlow;
  5233. const properties = builder.getNodeProperties( this );
  5234. properties.condNode = condNode;
  5235. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5236. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5237. }
  5238. generate( builder, output ) {
  5239. const type = this.getNodeType( builder );
  5240. const nodeData = builder.getDataFromNode( this );
  5241. if ( nodeData.nodeProperty !== undefined ) {
  5242. return nodeData.nodeProperty;
  5243. }
  5244. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5245. const functionNode = builder.currentFunctionNode;
  5246. const needsOutput = output !== 'void';
  5247. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5248. nodeData.nodeProperty = nodeProperty;
  5249. const nodeSnippet = condNode.build( builder, 'bool' );
  5250. const isUniformFlow = builder.context.uniformFlow;
  5251. if ( isUniformFlow && elseNode !== null ) {
  5252. const ifSnippet = ifNode.build( builder, type );
  5253. const elseSnippet = elseNode.build( builder, type );
  5254. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5255. // TODO: If node property already exists return something else
  5256. return builder.format( mathSnippet, type, output );
  5257. }
  5258. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5259. let ifSnippet = ifNode.build( builder, type );
  5260. if ( ifSnippet ) {
  5261. if ( needsOutput ) {
  5262. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5263. } else {
  5264. ifSnippet = 'return ' + ifSnippet + ';';
  5265. if ( functionNode === null ) {
  5266. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5267. ifSnippet = '// ' + ifSnippet;
  5268. }
  5269. }
  5270. }
  5271. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5272. if ( elseNode !== null ) {
  5273. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5274. let elseSnippet = elseNode.build( builder, type );
  5275. if ( elseSnippet ) {
  5276. if ( needsOutput ) {
  5277. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5278. } else {
  5279. elseSnippet = 'return ' + elseSnippet + ';';
  5280. if ( functionNode === null ) {
  5281. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5282. elseSnippet = '// ' + elseSnippet;
  5283. }
  5284. }
  5285. }
  5286. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5287. } else {
  5288. builder.addFlowCode( '\n\n' );
  5289. }
  5290. return builder.format( nodeProperty, type, output );
  5291. }
  5292. }
  5293. /**
  5294. * TSL function for creating a conditional node.
  5295. *
  5296. * @tsl
  5297. * @function
  5298. * @param {Node} condNode - The node that defines the condition.
  5299. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5300. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5301. * @returns {ConditionalNode}
  5302. */
  5303. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5304. addMethodChaining( 'select', select );
  5305. /**
  5306. * This node can be used as a context management component for another node.
  5307. * {@link NodeBuilder} performs its node building process in a specific context and
  5308. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5309. *
  5310. * ```js
  5311. *node.context( { getUV: () => customCoord } );
  5312. *```
  5313. * @augments Node
  5314. */
  5315. class ContextNode extends Node {
  5316. static get type() {
  5317. return 'ContextNode';
  5318. }
  5319. /**
  5320. * Constructs a new context node.
  5321. *
  5322. * @param {Node} node - The node whose context should be modified.
  5323. * @param {Object} [value={}] - The modified context data.
  5324. */
  5325. constructor( node, value = {} ) {
  5326. super();
  5327. /**
  5328. * This flag can be used for type testing.
  5329. *
  5330. * @type {boolean}
  5331. * @readonly
  5332. * @default true
  5333. */
  5334. this.isContextNode = true;
  5335. /**
  5336. * The node whose context should be modified.
  5337. *
  5338. * @type {Node}
  5339. */
  5340. this.node = node;
  5341. /**
  5342. * The modified context data.
  5343. *
  5344. * @type {Object}
  5345. * @default {}
  5346. */
  5347. this.value = value;
  5348. }
  5349. /**
  5350. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5351. *
  5352. * @return {Node} A reference to {@link ContextNode#node}.
  5353. */
  5354. getScope() {
  5355. return this.node.getScope();
  5356. }
  5357. /**
  5358. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5359. *
  5360. * @param {NodeBuilder} builder - The current node builder.
  5361. * @return {string} The node type.
  5362. */
  5363. getNodeType( builder ) {
  5364. return this.node.getNodeType( builder );
  5365. }
  5366. /**
  5367. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5368. *
  5369. * @param {NodeBuilder} builder - The current node builder.
  5370. * @param {string} name - The member name.
  5371. * @returns {string} The member type.
  5372. */
  5373. getMemberType( builder, name ) {
  5374. return this.node.getMemberType( builder, name );
  5375. }
  5376. analyze( builder ) {
  5377. const previousContext = builder.getContext();
  5378. builder.setContext( { ...builder.context, ...this.value } );
  5379. this.node.build( builder );
  5380. builder.setContext( previousContext );
  5381. }
  5382. setup( builder ) {
  5383. const previousContext = builder.getContext();
  5384. builder.setContext( { ...builder.context, ...this.value } );
  5385. this.node.build( builder );
  5386. builder.setContext( previousContext );
  5387. }
  5388. generate( builder, output ) {
  5389. const previousContext = builder.getContext();
  5390. builder.setContext( { ...builder.context, ...this.value } );
  5391. const snippet = this.node.build( builder, output );
  5392. builder.setContext( previousContext );
  5393. return snippet;
  5394. }
  5395. }
  5396. /**
  5397. * TSL function for creating a context node.
  5398. *
  5399. * @tsl
  5400. * @function
  5401. * @param {Node} node - The node whose context should be modified.
  5402. * @param {Object} [value={}] - The modified context data.
  5403. * @returns {ContextNode}
  5404. */
  5405. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5406. /**
  5407. * TSL function for defining a uniformFlow context value for a given node.
  5408. *
  5409. * @tsl
  5410. * @function
  5411. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5412. * @returns {ContextNode}
  5413. */
  5414. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5415. /**
  5416. * TSL function for defining a name for the context value for a given node.
  5417. *
  5418. * @tsl
  5419. * @function
  5420. * @param {Node} node - The node whose context should be modified.
  5421. * @param {string} name - The name to set.
  5422. * @returns {ContextNode}
  5423. */
  5424. const setName = ( node, name ) => context( node, { nodeName: name } );
  5425. /**
  5426. * TSL function for defining a label context value for a given node.
  5427. *
  5428. * @tsl
  5429. * @function
  5430. * @deprecated
  5431. * @param {Node} node - The node whose context should be modified.
  5432. * @param {string} name - The name/label to set.
  5433. * @returns {ContextNode}
  5434. */
  5435. function label( node, name ) {
  5436. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5437. return setName( node, name );
  5438. }
  5439. addMethodChaining( 'context', context );
  5440. addMethodChaining( 'label', label );
  5441. addMethodChaining( 'uniformFlow', uniformFlow );
  5442. addMethodChaining( 'setName', setName );
  5443. /**
  5444. * Class for representing shader variables as nodes. Variables are created from
  5445. * existing nodes like the following:
  5446. *
  5447. * ```js
  5448. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5449. * ```
  5450. *
  5451. * @augments Node
  5452. */
  5453. class VarNode extends Node {
  5454. static get type() {
  5455. return 'VarNode';
  5456. }
  5457. /**
  5458. * Constructs a new variable node.
  5459. *
  5460. * @param {Node} node - The node for which a variable should be created.
  5461. * @param {?string} [name=null] - The name of the variable in the shader.
  5462. * @param {boolean} [readOnly=false] - The read-only flag.
  5463. */
  5464. constructor( node, name = null, readOnly = false ) {
  5465. super();
  5466. /**
  5467. * The node for which a variable should be created.
  5468. *
  5469. * @type {Node}
  5470. */
  5471. this.node = node;
  5472. /**
  5473. * The name of the variable in the shader. If no name is defined,
  5474. * the node system auto-generates one.
  5475. *
  5476. * @type {?string}
  5477. * @default null
  5478. */
  5479. this.name = name;
  5480. /**
  5481. * `VarNode` sets this property to `true` by default.
  5482. *
  5483. * @type {boolean}
  5484. * @default true
  5485. */
  5486. this.global = true;
  5487. /**
  5488. * This flag can be used for type testing.
  5489. *
  5490. * @type {boolean}
  5491. * @readonly
  5492. * @default true
  5493. */
  5494. this.isVarNode = true;
  5495. /**
  5496. *
  5497. * The read-only flag.
  5498. *
  5499. * @type {boolean}
  5500. * @default false
  5501. */
  5502. this.readOnly = readOnly;
  5503. /**
  5504. *
  5505. * Add this flag to the node system to indicate that this node require parents.
  5506. *
  5507. * @type {boolean}
  5508. * @default true
  5509. */
  5510. this.parents = true;
  5511. /**
  5512. * This flag is used to indicate that this node is used for intent.
  5513. *
  5514. * @type {boolean}
  5515. * @default false
  5516. */
  5517. this.intent = false;
  5518. }
  5519. /**
  5520. * Sets the intent flag for this node.
  5521. *
  5522. * This flag is used to indicate that this node is used for intent
  5523. * and should not be built directly. Instead, it is used to indicate that
  5524. * the node should be treated as a variable intent.
  5525. *
  5526. * It's useful for assigning variables without needing creating a new variable node.
  5527. *
  5528. * @param {boolean} value - The value to set for the intent flag.
  5529. * @returns {VarNode} This node.
  5530. */
  5531. setIntent( value ) {
  5532. this.intent = value;
  5533. return this;
  5534. }
  5535. /**
  5536. * Returns the intent flag of this node.
  5537. *
  5538. * @return {boolean} The intent flag.
  5539. */
  5540. getIntent() {
  5541. return this.intent;
  5542. }
  5543. getMemberType( builder, name ) {
  5544. return this.node.getMemberType( builder, name );
  5545. }
  5546. getElementType( builder ) {
  5547. return this.node.getElementType( builder );
  5548. }
  5549. getNodeType( builder ) {
  5550. return this.node.getNodeType( builder );
  5551. }
  5552. getArrayCount( builder ) {
  5553. return this.node.getArrayCount( builder );
  5554. }
  5555. build( ...params ) {
  5556. if ( this.intent === true ) {
  5557. const builder = params[ 0 ];
  5558. const properties = builder.getNodeProperties( this );
  5559. if ( properties.assign !== true ) {
  5560. return this.node.build( ...params );
  5561. }
  5562. }
  5563. return super.build( ...params );
  5564. }
  5565. generate( builder ) {
  5566. const { node, name, readOnly } = this;
  5567. const { renderer } = builder;
  5568. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5569. let isDeterministic = false;
  5570. let shouldTreatAsReadOnly = false;
  5571. if ( readOnly ) {
  5572. isDeterministic = builder.isDeterministic( node );
  5573. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5574. }
  5575. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5576. const snippet = node.build( builder, vectorType );
  5577. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5578. const propertyName = builder.getPropertyName( nodeVar );
  5579. let declarationPrefix = propertyName;
  5580. if ( shouldTreatAsReadOnly ) {
  5581. if ( isWebGPUBackend ) {
  5582. declarationPrefix = isDeterministic
  5583. ? `const ${ propertyName }`
  5584. : `let ${ propertyName }`;
  5585. } else {
  5586. const count = node.getArrayCount( builder );
  5587. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5588. }
  5589. }
  5590. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5591. return propertyName;
  5592. }
  5593. }
  5594. /**
  5595. * TSL function for creating a var node.
  5596. *
  5597. * @tsl
  5598. * @function
  5599. * @param {Node} node - The node for which a variable should be created.
  5600. * @param {?string} name - The name of the variable in the shader.
  5601. * @returns {VarNode}
  5602. */
  5603. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5604. /**
  5605. * TSL function for creating a var node.
  5606. *
  5607. * @tsl
  5608. * @function
  5609. * @param {Node} node - The node for which a variable should be created.
  5610. * @param {?string} name - The name of the variable in the shader.
  5611. * @returns {VarNode}
  5612. */
  5613. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5614. /**
  5615. * TSL function for creating a const node.
  5616. *
  5617. * @tsl
  5618. * @function
  5619. * @param {Node} node - The node for which a constant should be created.
  5620. * @param {?string} name - The name of the constant in the shader.
  5621. * @returns {VarNode}
  5622. */
  5623. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5624. //
  5625. //
  5626. /**
  5627. * TSL function for creating a var intent node.
  5628. *
  5629. * @tsl
  5630. * @function
  5631. * @param {Node} node - The node for which a variable should be created.
  5632. * @param {?string} name - The name of the variable in the shader.
  5633. * @returns {VarNode}
  5634. */
  5635. const VarIntent = ( node ) => {
  5636. if ( getCurrentStack() === null ) {
  5637. return node;
  5638. }
  5639. return createVar( node ).setIntent( true ).toStack();
  5640. };
  5641. // Method chaining
  5642. addMethodChaining( 'toVar', Var );
  5643. addMethodChaining( 'toConst', Const );
  5644. addMethodChaining( 'toVarIntent', VarIntent );
  5645. /**
  5646. * This node is used to build a sub-build in the node system.
  5647. *
  5648. * @augments Node
  5649. * @param {Node} node - The node to be built in the sub-build.
  5650. * @param {string} name - The name of the sub-build.
  5651. * @param {string|null} [nodeType=null] - The type of the node, if known.
  5652. */
  5653. class SubBuildNode extends Node {
  5654. static get type() {
  5655. return 'SubBuild';
  5656. }
  5657. constructor( node, name, nodeType = null ) {
  5658. super( nodeType );
  5659. /**
  5660. * The node to be built in the sub-build.
  5661. *
  5662. * @type {Node}
  5663. */
  5664. this.node = node;
  5665. /**
  5666. * The name of the sub-build.
  5667. *
  5668. * @type {string}
  5669. */
  5670. this.name = name;
  5671. /**
  5672. * This flag can be used for type testing.
  5673. *
  5674. * @type {boolean}
  5675. * @readonly
  5676. * @default true
  5677. */
  5678. this.isSubBuildNode = true;
  5679. }
  5680. getNodeType( builder ) {
  5681. if ( this.nodeType !== null ) return this.nodeType;
  5682. builder.addSubBuild( this.name );
  5683. const nodeType = this.node.getNodeType( builder );
  5684. builder.removeSubBuild();
  5685. return nodeType;
  5686. }
  5687. build( builder, ...params ) {
  5688. builder.addSubBuild( this.name );
  5689. const data = this.node.build( builder, ...params );
  5690. builder.removeSubBuild();
  5691. return data;
  5692. }
  5693. }
  5694. /**
  5695. * Creates a new sub-build node.
  5696. *
  5697. * @tsl
  5698. * @function
  5699. * @param {Node} node - The node to be built in the sub-build.
  5700. * @param {string} name - The name of the sub-build.
  5701. * @param {string|null} [type=null] - The type of the node, if known.
  5702. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5703. */
  5704. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5705. /**
  5706. * Class for representing shader varyings as nodes. Varyings are create from
  5707. * existing nodes like the following:
  5708. *
  5709. * ```js
  5710. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5711. * ```
  5712. *
  5713. * @augments Node
  5714. */
  5715. class VaryingNode extends Node {
  5716. static get type() {
  5717. return 'VaryingNode';
  5718. }
  5719. /**
  5720. * Constructs a new varying node.
  5721. *
  5722. * @param {Node} node - The node for which a varying should be created.
  5723. * @param {?string} name - The name of the varying in the shader.
  5724. */
  5725. constructor( node, name = null ) {
  5726. super();
  5727. /**
  5728. * The node for which a varying should be created.
  5729. *
  5730. * @type {Node}
  5731. */
  5732. this.node = node;
  5733. /**
  5734. * The name of the varying in the shader. If no name is defined,
  5735. * the node system auto-generates one.
  5736. *
  5737. * @type {?string}
  5738. * @default null
  5739. */
  5740. this.name = name;
  5741. /**
  5742. * This flag can be used for type testing.
  5743. *
  5744. * @type {boolean}
  5745. * @readonly
  5746. * @default true
  5747. */
  5748. this.isVaryingNode = true;
  5749. /**
  5750. * The interpolation type of the varying data.
  5751. *
  5752. * @type {?string}
  5753. * @default null
  5754. */
  5755. this.interpolationType = null;
  5756. /**
  5757. * The interpolation sampling type of varying data.
  5758. *
  5759. * @type {?string}
  5760. * @default null
  5761. */
  5762. this.interpolationSampling = null;
  5763. /**
  5764. * This flag is used for global cache.
  5765. *
  5766. * @type {boolean}
  5767. * @default true
  5768. */
  5769. this.global = true;
  5770. }
  5771. /**
  5772. * Defines the interpolation type of the varying.
  5773. *
  5774. * @param {string} type - The interpolation type.
  5775. * @param {?string} sampling - The interpolation sampling type
  5776. * @return {VaryingNode} A reference to this node.
  5777. */
  5778. setInterpolation( type, sampling = null ) {
  5779. this.interpolationType = type;
  5780. this.interpolationSampling = sampling;
  5781. return this;
  5782. }
  5783. getHash( builder ) {
  5784. return this.name || super.getHash( builder );
  5785. }
  5786. getNodeType( builder ) {
  5787. // VaryingNode is auto type
  5788. return this.node.getNodeType( builder );
  5789. }
  5790. /**
  5791. * This method performs the setup of a varying node with the current node builder.
  5792. *
  5793. * @param {NodeBuilder} builder - The current node builder.
  5794. * @return {NodeVarying} The node varying from the node builder.
  5795. */
  5796. setupVarying( builder ) {
  5797. const properties = builder.getNodeProperties( this );
  5798. let varying = properties.varying;
  5799. if ( varying === undefined ) {
  5800. const name = this.name;
  5801. const type = this.getNodeType( builder );
  5802. const interpolationType = this.interpolationType;
  5803. const interpolationSampling = this.interpolationSampling;
  5804. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5805. properties.node = subBuild( this.node, 'VERTEX' );
  5806. }
  5807. // this property can be used to check if the varying can be optimized for a variable
  5808. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5809. return varying;
  5810. }
  5811. setup( builder ) {
  5812. this.setupVarying( builder );
  5813. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5814. }
  5815. analyze( builder ) {
  5816. this.setupVarying( builder );
  5817. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5818. }
  5819. generate( builder ) {
  5820. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5821. const properties = builder.getNodeProperties( this );
  5822. const varying = this.setupVarying( builder );
  5823. if ( properties[ propertyKey ] === undefined ) {
  5824. const type = this.getNodeType( builder );
  5825. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5826. // force node run in vertex stage
  5827. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5828. properties[ propertyKey ] = propertyName;
  5829. }
  5830. return builder.getPropertyName( varying );
  5831. }
  5832. }
  5833. /**
  5834. * TSL function for creating a varying node.
  5835. *
  5836. * @tsl
  5837. * @function
  5838. * @param {Node} node - The node for which a varying should be created.
  5839. * @param {?string} name - The name of the varying in the shader.
  5840. * @returns {VaryingNode}
  5841. */
  5842. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5843. /**
  5844. * Computes a node in the vertex stage.
  5845. *
  5846. * @tsl
  5847. * @function
  5848. * @param {Node} node - The node which should be executed in the vertex stage.
  5849. * @returns {VaryingNode}
  5850. */
  5851. const vertexStage = ( node ) => varying( node );
  5852. addMethodChaining( 'toVarying', varying );
  5853. addMethodChaining( 'toVertexStage', vertexStage );
  5854. // Deprecated
  5855. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5856. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5857. return varying( ...params );
  5858. } );
  5859. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5860. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5861. return varying( ...params );
  5862. } );
  5863. /**
  5864. * Converts the given color value from sRGB to linear-sRGB color space.
  5865. *
  5866. * @tsl
  5867. * @function
  5868. * @param {Node<vec3>} color - The sRGB color.
  5869. * @return {Node<vec3>} The linear-sRGB color.
  5870. */
  5871. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5872. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5873. const b = color.mul( 0.0773993808 );
  5874. const factor = color.lessThanEqual( 0.04045 );
  5875. const rgbResult = mix( a, b, factor );
  5876. return rgbResult;
  5877. } ).setLayout( {
  5878. name: 'sRGBTransferEOTF',
  5879. type: 'vec3',
  5880. inputs: [
  5881. { name: 'color', type: 'vec3' }
  5882. ]
  5883. } );
  5884. /**
  5885. * Converts the given color value from linear-sRGB to sRGB color space.
  5886. *
  5887. * @tsl
  5888. * @function
  5889. * @param {Node<vec3>} color - The linear-sRGB color.
  5890. * @return {Node<vec3>} The sRGB color.
  5891. */
  5892. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5893. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5894. const b = color.mul( 12.92 );
  5895. const factor = color.lessThanEqual( 0.0031308 );
  5896. const rgbResult = mix( a, b, factor );
  5897. return rgbResult;
  5898. } ).setLayout( {
  5899. name: 'sRGBTransferOETF',
  5900. type: 'vec3',
  5901. inputs: [
  5902. { name: 'color', type: 'vec3' }
  5903. ]
  5904. } );
  5905. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5906. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5907. /**
  5908. * This node represents a color space conversion. Meaning it converts
  5909. * a color value from a source to a target color space.
  5910. *
  5911. * @augments TempNode
  5912. */
  5913. class ColorSpaceNode extends TempNode {
  5914. static get type() {
  5915. return 'ColorSpaceNode';
  5916. }
  5917. /**
  5918. * Constructs a new color space node.
  5919. *
  5920. * @param {Node} colorNode - Represents the color to convert.
  5921. * @param {string} source - The source color space.
  5922. * @param {string} target - The target color space.
  5923. */
  5924. constructor( colorNode, source, target ) {
  5925. super( 'vec4' );
  5926. /**
  5927. * Represents the color to convert.
  5928. *
  5929. * @type {Node}
  5930. */
  5931. this.colorNode = colorNode;
  5932. /**
  5933. * The source color space.
  5934. *
  5935. * @type {string}
  5936. */
  5937. this.source = source;
  5938. /**
  5939. * The target color space.
  5940. *
  5941. * @type {string}
  5942. */
  5943. this.target = target;
  5944. }
  5945. /**
  5946. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5947. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5948. * color management and renderer.
  5949. *
  5950. * @param {NodeBuilder} builder - The current node builder.
  5951. * @param {string} colorSpace - The color space to resolve.
  5952. * @return {string} The resolved color space.
  5953. */
  5954. resolveColorSpace( builder, colorSpace ) {
  5955. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5956. return ColorManagement.workingColorSpace;
  5957. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5958. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5959. }
  5960. return colorSpace;
  5961. }
  5962. setup( builder ) {
  5963. const { colorNode } = this;
  5964. const source = this.resolveColorSpace( builder, this.source );
  5965. const target = this.resolveColorSpace( builder, this.target );
  5966. let outputNode = colorNode;
  5967. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5968. return outputNode;
  5969. }
  5970. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5971. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5972. }
  5973. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5974. outputNode = vec4(
  5975. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5976. outputNode.a
  5977. );
  5978. }
  5979. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5980. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5981. }
  5982. return outputNode;
  5983. }
  5984. }
  5985. /**
  5986. * TSL function for converting a given color node from the current working color space to the given color space.
  5987. *
  5988. * @tsl
  5989. * @function
  5990. * @param {Node} node - Represents the node to convert.
  5991. * @param {string} targetColorSpace - The target color space.
  5992. * @returns {ColorSpaceNode}
  5993. */
  5994. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  5995. /**
  5996. * TSL function for converting a given color node from the given color space to the current working color space.
  5997. *
  5998. * @tsl
  5999. * @function
  6000. * @param {Node} node - Represents the node to convert.
  6001. * @param {string} sourceColorSpace - The source color space.
  6002. * @returns {ColorSpaceNode}
  6003. */
  6004. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6005. /**
  6006. * TSL function for converting a given color node from one color space to another one.
  6007. *
  6008. * @tsl
  6009. * @function
  6010. * @param {Node} node - Represents the node to convert.
  6011. * @param {string} sourceColorSpace - The source color space.
  6012. * @param {string} targetColorSpace - The target color space.
  6013. * @returns {ColorSpaceNode}
  6014. */
  6015. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6016. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6017. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6018. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6019. /**
  6020. * This class is only relevant if the referenced property is array-like.
  6021. * In this case, `ReferenceElementNode` allows to refer to a specific
  6022. * element inside the data structure via an index.
  6023. *
  6024. * @augments ArrayElementNode
  6025. */
  6026. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6027. static get type() {
  6028. return 'ReferenceElementNode';
  6029. }
  6030. /**
  6031. * Constructs a new reference element node.
  6032. *
  6033. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6034. * @param {Node} indexNode - The index node that defines the element access.
  6035. */
  6036. constructor( referenceNode, indexNode ) {
  6037. super( referenceNode, indexNode );
  6038. /**
  6039. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6040. * property references to the current node.
  6041. *
  6042. * @type {?ReferenceBaseNode}
  6043. * @default null
  6044. */
  6045. this.referenceNode = referenceNode;
  6046. /**
  6047. * This flag can be used for type testing.
  6048. *
  6049. * @type {boolean}
  6050. * @readonly
  6051. * @default true
  6052. */
  6053. this.isReferenceElementNode = true;
  6054. }
  6055. /**
  6056. * This method is overwritten since the node type is inferred from
  6057. * the uniform type of the reference node.
  6058. *
  6059. * @return {string} The node type.
  6060. */
  6061. getNodeType() {
  6062. return this.referenceNode.uniformType;
  6063. }
  6064. generate( builder ) {
  6065. const snippet = super.generate( builder );
  6066. const arrayType = this.referenceNode.getNodeType();
  6067. const elementType = this.getNodeType();
  6068. return builder.format( snippet, arrayType, elementType );
  6069. }
  6070. };
  6071. /**
  6072. * Base class for nodes which establishes a reference to a property of another object.
  6073. * In this way, the value of the node is automatically linked to the value of
  6074. * referenced object. Reference nodes internally represent the linked value
  6075. * as a uniform.
  6076. *
  6077. * @augments Node
  6078. */
  6079. class ReferenceBaseNode extends Node {
  6080. static get type() {
  6081. return 'ReferenceBaseNode';
  6082. }
  6083. /**
  6084. * Constructs a new reference base node.
  6085. *
  6086. * @param {string} property - The name of the property the node refers to.
  6087. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6088. * @param {?Object} [object=null] - The object the property belongs to.
  6089. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6090. */
  6091. constructor( property, uniformType, object = null, count = null ) {
  6092. super();
  6093. /**
  6094. * The name of the property the node refers to.
  6095. *
  6096. * @type {string}
  6097. */
  6098. this.property = property;
  6099. /**
  6100. * The uniform type that should be used to represent the property value.
  6101. *
  6102. * @type {string}
  6103. */
  6104. this.uniformType = uniformType;
  6105. /**
  6106. * The object the property belongs to.
  6107. *
  6108. * @type {?Object}
  6109. * @default null
  6110. */
  6111. this.object = object;
  6112. /**
  6113. * When the linked property is an array, this parameter defines its length.
  6114. *
  6115. * @type {?number}
  6116. * @default null
  6117. */
  6118. this.count = count;
  6119. /**
  6120. * The property name might have dots so nested properties can be referred.
  6121. * The hierarchy of the names is stored inside this array.
  6122. *
  6123. * @type {Array<string>}
  6124. */
  6125. this.properties = property.split( '.' );
  6126. /**
  6127. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6128. * since the final reference might be updated from calling code.
  6129. *
  6130. * @type {?Object}
  6131. * @default null
  6132. */
  6133. this.reference = object;
  6134. /**
  6135. * The uniform node that holds the value of the reference node.
  6136. *
  6137. * @type {UniformNode}
  6138. * @default null
  6139. */
  6140. this.node = null;
  6141. /**
  6142. * The uniform group of the internal uniform.
  6143. *
  6144. * @type {UniformGroupNode}
  6145. * @default null
  6146. */
  6147. this.group = null;
  6148. /**
  6149. * Overwritten since reference nodes are updated per object.
  6150. *
  6151. * @type {string}
  6152. * @default 'object'
  6153. */
  6154. this.updateType = NodeUpdateType.OBJECT;
  6155. }
  6156. /**
  6157. * Sets the uniform group for this reference node.
  6158. *
  6159. * @param {UniformGroupNode} group - The uniform group to set.
  6160. * @return {ReferenceBaseNode} A reference to this node.
  6161. */
  6162. setGroup( group ) {
  6163. this.group = group;
  6164. return this;
  6165. }
  6166. /**
  6167. * When the referred property is array-like, this method can be used
  6168. * to access elements via an index node.
  6169. *
  6170. * @param {IndexNode} indexNode - indexNode.
  6171. * @return {ReferenceElementNode} A reference to an element.
  6172. */
  6173. element( indexNode ) {
  6174. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6175. }
  6176. /**
  6177. * Sets the node type which automatically defines the internal
  6178. * uniform type.
  6179. *
  6180. * @param {string} uniformType - The type to set.
  6181. */
  6182. setNodeType( uniformType ) {
  6183. const node = uniform( null, uniformType ).getSelf();
  6184. if ( this.group !== null ) {
  6185. node.setGroup( this.group );
  6186. }
  6187. this.node = node;
  6188. }
  6189. /**
  6190. * This method is overwritten since the node type is inferred from
  6191. * the type of the reference node.
  6192. *
  6193. * @param {NodeBuilder} builder - The current node builder.
  6194. * @return {string} The node type.
  6195. */
  6196. getNodeType( builder ) {
  6197. if ( this.node === null ) {
  6198. this.updateReference( builder );
  6199. this.updateValue();
  6200. }
  6201. return this.node.getNodeType( builder );
  6202. }
  6203. /**
  6204. * Returns the property value from the given referred object.
  6205. *
  6206. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6207. * @return {any} The value.
  6208. */
  6209. getValueFromReference( object = this.reference ) {
  6210. const { properties } = this;
  6211. let value = object[ properties[ 0 ] ];
  6212. for ( let i = 1; i < properties.length; i ++ ) {
  6213. value = value[ properties[ i ] ];
  6214. }
  6215. return value;
  6216. }
  6217. /**
  6218. * Allows to update the reference based on the given state. The state is only
  6219. * evaluated {@link ReferenceBaseNode#object} is not set.
  6220. *
  6221. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6222. * @return {Object} The updated reference.
  6223. */
  6224. updateReference( state ) {
  6225. this.reference = this.object !== null ? this.object : state.object;
  6226. return this.reference;
  6227. }
  6228. /**
  6229. * The output of the reference node is the internal uniform node.
  6230. *
  6231. * @return {UniformNode} The output node.
  6232. */
  6233. setup() {
  6234. this.updateValue();
  6235. return this.node;
  6236. }
  6237. /**
  6238. * Overwritten to update the internal uniform value.
  6239. *
  6240. * @param {NodeFrame} frame - A reference to the current node frame.
  6241. */
  6242. update( /*frame*/ ) {
  6243. this.updateValue();
  6244. }
  6245. /**
  6246. * Retrieves the value from the referred object property and uses it
  6247. * to updated the internal uniform.
  6248. */
  6249. updateValue() {
  6250. if ( this.node === null ) this.setNodeType( this.uniformType );
  6251. const value = this.getValueFromReference();
  6252. if ( Array.isArray( value ) ) {
  6253. this.node.array = value;
  6254. } else {
  6255. this.node.value = value;
  6256. }
  6257. }
  6258. }
  6259. /**
  6260. * TSL function for creating a reference base node.
  6261. *
  6262. * @tsl
  6263. * @function
  6264. * @param {string} name - The name of the property the node refers to.
  6265. * @param {string} type - The uniform type that should be used to represent the property value.
  6266. * @param {Object} object - The object the property belongs to.
  6267. * @returns {ReferenceBaseNode}
  6268. */
  6269. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6270. /**
  6271. * This node is a special type of reference node which is intended
  6272. * for linking renderer properties with node values.
  6273. * ```js
  6274. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6275. * ```
  6276. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6277. * automatically be updated.
  6278. *
  6279. * @augments ReferenceBaseNode
  6280. */
  6281. class RendererReferenceNode extends ReferenceBaseNode {
  6282. static get type() {
  6283. return 'RendererReferenceNode';
  6284. }
  6285. /**
  6286. * Constructs a new renderer reference node.
  6287. *
  6288. * @param {string} property - The name of the property the node refers to.
  6289. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6290. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6291. * the node refers to the renderer of the current state.
  6292. */
  6293. constructor( property, inputType, renderer = null ) {
  6294. super( property, inputType, renderer );
  6295. /**
  6296. * The renderer the property belongs to. When no renderer is set,
  6297. * the node refers to the renderer of the current state.
  6298. *
  6299. * @type {?Renderer}
  6300. * @default null
  6301. */
  6302. this.renderer = renderer;
  6303. this.setGroup( renderGroup );
  6304. }
  6305. /**
  6306. * Updates the reference based on the given state. The state is only evaluated
  6307. * {@link RendererReferenceNode#renderer} is not set.
  6308. *
  6309. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6310. * @return {Object} The updated reference.
  6311. */
  6312. updateReference( state ) {
  6313. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6314. return this.reference;
  6315. }
  6316. }
  6317. /**
  6318. * TSL function for creating a renderer reference node.
  6319. *
  6320. * @tsl
  6321. * @function
  6322. * @param {string} name - The name of the property the node refers to.
  6323. * @param {string} type - The uniform type that should be used to represent the property value.
  6324. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6325. * the node refers to the renderer of the current state.
  6326. * @returns {RendererReferenceNode}
  6327. */
  6328. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6329. /**
  6330. * This node represents a tone mapping operation.
  6331. *
  6332. * @augments TempNode
  6333. */
  6334. class ToneMappingNode extends TempNode {
  6335. static get type() {
  6336. return 'ToneMappingNode';
  6337. }
  6338. /**
  6339. * Constructs a new tone mapping node.
  6340. *
  6341. * @param {number} toneMapping - The tone mapping type.
  6342. * @param {Node} exposureNode - The tone mapping exposure.
  6343. * @param {Node} [colorNode=null] - The color node to process.
  6344. */
  6345. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6346. super( 'vec3' );
  6347. /**
  6348. * The tone mapping type.
  6349. *
  6350. * @type {number}
  6351. */
  6352. this.toneMapping = toneMapping;
  6353. /**
  6354. * The tone mapping exposure.
  6355. *
  6356. * @type {Node}
  6357. * @default null
  6358. */
  6359. this.exposureNode = exposureNode;
  6360. /**
  6361. * Represents the color to process.
  6362. *
  6363. * @type {?Node}
  6364. * @default null
  6365. */
  6366. this.colorNode = colorNode;
  6367. }
  6368. /**
  6369. * Overwrites the default `customCacheKey()` implementation by including the tone
  6370. * mapping type into the cache key.
  6371. *
  6372. * @return {number} The hash.
  6373. */
  6374. customCacheKey() {
  6375. return hash$1( this.toneMapping );
  6376. }
  6377. setup( builder ) {
  6378. const colorNode = this.colorNode || builder.context.color;
  6379. const toneMapping = this.toneMapping;
  6380. if ( toneMapping === NoToneMapping ) return colorNode;
  6381. let outputNode = null;
  6382. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6383. if ( toneMappingFn !== null ) {
  6384. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6385. } else {
  6386. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6387. outputNode = colorNode;
  6388. }
  6389. return outputNode;
  6390. }
  6391. }
  6392. /**
  6393. * TSL function for creating a tone mapping node.
  6394. *
  6395. * @tsl
  6396. * @function
  6397. * @param {number} mapping - The tone mapping type.
  6398. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6399. * @param {Node<vec3> | Color} color - The color node to process.
  6400. * @returns {ToneMappingNode<vec3>}
  6401. */
  6402. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6403. /**
  6404. * TSL object that represents the global tone mapping exposure of the renderer.
  6405. *
  6406. * @tsl
  6407. * @type {RendererReferenceNode<vec3>}
  6408. */
  6409. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6410. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6411. /**
  6412. * In earlier `three.js` versions it was only possible to define attribute data
  6413. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6414. * on the node level.
  6415. * ```js
  6416. * const geometry = new THREE.PlaneGeometry();
  6417. * const positionAttribute = geometry.getAttribute( 'position' );
  6418. *
  6419. * const colors = [];
  6420. * for ( let i = 0; i < position.count; i ++ ) {
  6421. * colors.push( 1, 0, 0 );
  6422. * }
  6423. *
  6424. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6425. * ```
  6426. * This new approach is especially interesting when geometry data are generated via
  6427. * compute shaders. The below line converts a storage buffer into an attribute node.
  6428. * ```js
  6429. * material.positionNode = positionBuffer.toAttribute();
  6430. * ```
  6431. * @augments InputNode
  6432. */
  6433. class BufferAttributeNode extends InputNode {
  6434. static get type() {
  6435. return 'BufferAttributeNode';
  6436. }
  6437. /**
  6438. * Constructs a new buffer attribute node.
  6439. *
  6440. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6441. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6442. * @param {number} [bufferStride=0] - The buffer stride.
  6443. * @param {number} [bufferOffset=0] - The buffer offset.
  6444. */
  6445. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6446. super( value, bufferType );
  6447. /**
  6448. * This flag can be used for type testing.
  6449. *
  6450. * @type {boolean}
  6451. * @readonly
  6452. * @default true
  6453. */
  6454. this.isBufferNode = true;
  6455. /**
  6456. * The buffer type (e.g. `'vec3'`).
  6457. *
  6458. * @type {?string}
  6459. * @default null
  6460. */
  6461. this.bufferType = bufferType;
  6462. /**
  6463. * The buffer stride.
  6464. *
  6465. * @type {number}
  6466. * @default 0
  6467. */
  6468. this.bufferStride = bufferStride;
  6469. /**
  6470. * The buffer offset.
  6471. *
  6472. * @type {number}
  6473. * @default 0
  6474. */
  6475. this.bufferOffset = bufferOffset;
  6476. /**
  6477. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6478. * if you are planning to update the attribute data per frame.
  6479. *
  6480. * @type {number}
  6481. * @default StaticDrawUsage
  6482. */
  6483. this.usage = StaticDrawUsage;
  6484. /**
  6485. * Whether the attribute is instanced or not.
  6486. *
  6487. * @type {boolean}
  6488. * @default false
  6489. */
  6490. this.instanced = false;
  6491. /**
  6492. * A reference to the buffer attribute.
  6493. *
  6494. * @type {?BufferAttribute}
  6495. * @default null
  6496. */
  6497. this.attribute = null;
  6498. /**
  6499. * `BufferAttributeNode` sets this property to `true` by default.
  6500. *
  6501. * @type {boolean}
  6502. * @default true
  6503. */
  6504. this.global = true;
  6505. if ( value && value.isBufferAttribute === true ) {
  6506. this.attribute = value;
  6507. this.usage = value.usage;
  6508. this.instanced = value.isInstancedBufferAttribute;
  6509. }
  6510. }
  6511. /**
  6512. * This method is overwritten since the attribute data might be shared
  6513. * and thus the hash should be shared as well.
  6514. *
  6515. * @param {NodeBuilder} builder - The current node builder.
  6516. * @return {string} The hash.
  6517. */
  6518. getHash( builder ) {
  6519. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6520. let bufferData = builder.globalCache.getData( this.value );
  6521. if ( bufferData === undefined ) {
  6522. bufferData = {
  6523. node: this
  6524. };
  6525. builder.globalCache.setData( this.value, bufferData );
  6526. }
  6527. return bufferData.node.uuid;
  6528. }
  6529. return this.uuid;
  6530. }
  6531. /**
  6532. * This method is overwritten since the node type is inferred from
  6533. * the buffer attribute.
  6534. *
  6535. * @param {NodeBuilder} builder - The current node builder.
  6536. * @return {string} The node type.
  6537. */
  6538. getNodeType( builder ) {
  6539. if ( this.bufferType === null ) {
  6540. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6541. }
  6542. return this.bufferType;
  6543. }
  6544. /**
  6545. * Depending on which value was passed to the node, `setup()` behaves
  6546. * differently. If no instance of `BufferAttribute` was passed, the method
  6547. * creates an internal attribute and configures it respectively.
  6548. *
  6549. * @param {NodeBuilder} builder - The current node builder.
  6550. */
  6551. setup( builder ) {
  6552. if ( this.attribute !== null ) return;
  6553. const type = this.getNodeType( builder );
  6554. const array = this.value;
  6555. const itemSize = builder.getTypeLength( type );
  6556. const stride = this.bufferStride || itemSize;
  6557. const offset = this.bufferOffset;
  6558. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6559. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6560. buffer.setUsage( this.usage );
  6561. this.attribute = bufferAttribute;
  6562. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6563. }
  6564. /**
  6565. * Generates the code snippet of the buffer attribute node.
  6566. *
  6567. * @param {NodeBuilder} builder - The current node builder.
  6568. * @return {string} The generated code snippet.
  6569. */
  6570. generate( builder ) {
  6571. const nodeType = this.getNodeType( builder );
  6572. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6573. const propertyName = builder.getPropertyName( nodeAttribute );
  6574. let output = null;
  6575. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6576. this.name = propertyName;
  6577. output = propertyName;
  6578. } else {
  6579. const nodeVarying = varying( this );
  6580. output = nodeVarying.build( builder, nodeType );
  6581. }
  6582. return output;
  6583. }
  6584. /**
  6585. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6586. *
  6587. * @param {NodeBuilder} builder - The current node builder.
  6588. * @return {string} The input type.
  6589. */
  6590. getInputType( /*builder*/ ) {
  6591. return 'bufferAttribute';
  6592. }
  6593. /**
  6594. * Sets the `usage` property to the given value.
  6595. *
  6596. * @param {number} value - The usage to set.
  6597. * @return {BufferAttributeNode} A reference to this node.
  6598. */
  6599. setUsage( value ) {
  6600. this.usage = value;
  6601. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6602. this.attribute.usage = value;
  6603. }
  6604. return this;
  6605. }
  6606. /**
  6607. * Sets the `instanced` property to the given value.
  6608. *
  6609. * @param {boolean} value - The value to set.
  6610. * @return {BufferAttributeNode} A reference to this node.
  6611. */
  6612. setInstanced( value ) {
  6613. this.instanced = value;
  6614. return this;
  6615. }
  6616. }
  6617. /**
  6618. * TSL function for creating a buffer attribute node.
  6619. *
  6620. * @tsl
  6621. * @function
  6622. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6623. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6624. * @param {number} [stride=0] - The buffer stride.
  6625. * @param {number} [offset=0] - The buffer offset.
  6626. * @returns {BufferAttributeNode}
  6627. */
  6628. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6629. /**
  6630. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6631. * Use this function if attribute data are updated per frame.
  6632. *
  6633. * @tsl
  6634. * @function
  6635. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6636. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6637. * @param {number} [stride=0] - The buffer stride.
  6638. * @param {number} [offset=0] - The buffer offset.
  6639. * @returns {BufferAttributeNode}
  6640. */
  6641. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6642. /**
  6643. * TSL function for creating a buffer attribute node but with enabled instancing
  6644. *
  6645. * @tsl
  6646. * @function
  6647. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6648. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6649. * @param {number} [stride=0] - The buffer stride.
  6650. * @param {number} [offset=0] - The buffer offset.
  6651. * @returns {BufferAttributeNode}
  6652. */
  6653. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6654. /**
  6655. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6656. *
  6657. * @tsl
  6658. * @function
  6659. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6660. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6661. * @param {number} [stride=0] - The buffer stride.
  6662. * @param {number} [offset=0] - The buffer offset.
  6663. * @returns {BufferAttributeNode}
  6664. */
  6665. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6666. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6667. /**
  6668. * TODO
  6669. *
  6670. * @augments Node
  6671. */
  6672. class ComputeNode extends Node {
  6673. static get type() {
  6674. return 'ComputeNode';
  6675. }
  6676. /**
  6677. * Constructs a new compute node.
  6678. *
  6679. * @param {Node} computeNode - TODO
  6680. * @param {Array<number>} workgroupSize - TODO.
  6681. */
  6682. constructor( computeNode, workgroupSize ) {
  6683. super( 'void' );
  6684. /**
  6685. * This flag can be used for type testing.
  6686. *
  6687. * @type {boolean}
  6688. * @readonly
  6689. * @default true
  6690. */
  6691. this.isComputeNode = true;
  6692. /**
  6693. * TODO
  6694. *
  6695. * @type {Node}
  6696. */
  6697. this.computeNode = computeNode;
  6698. /**
  6699. * TODO
  6700. *
  6701. * @type {Array<number>}
  6702. * @default [ 64 ]
  6703. */
  6704. this.workgroupSize = workgroupSize;
  6705. /**
  6706. * TODO
  6707. *
  6708. * @type {number}
  6709. */
  6710. this.count = null;
  6711. /**
  6712. * TODO
  6713. *
  6714. * @type {number}
  6715. */
  6716. this.version = 1;
  6717. /**
  6718. * The name or label of the uniform.
  6719. *
  6720. * @type {string}
  6721. * @default ''
  6722. */
  6723. this.name = '';
  6724. /**
  6725. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6726. * is executed once per object by default.
  6727. *
  6728. * @type {string}
  6729. * @default 'object'
  6730. */
  6731. this.updateBeforeType = NodeUpdateType.OBJECT;
  6732. /**
  6733. * TODO
  6734. *
  6735. * @type {?Function}
  6736. */
  6737. this.onInitFunction = null;
  6738. }
  6739. setCount( count ) {
  6740. this.count = count;
  6741. return this;
  6742. }
  6743. getCount() {
  6744. return this.count;
  6745. }
  6746. /**
  6747. * Executes the `dispose` event for this node.
  6748. */
  6749. dispose() {
  6750. this.dispatchEvent( { type: 'dispose' } );
  6751. }
  6752. /**
  6753. * Sets the {@link ComputeNode#name} property.
  6754. *
  6755. * @param {string} name - The name of the uniform.
  6756. * @return {ComputeNode} A reference to this node.
  6757. */
  6758. setName( name ) {
  6759. this.name = name;
  6760. return this;
  6761. }
  6762. /**
  6763. * Sets the {@link ComputeNode#name} property.
  6764. *
  6765. * @deprecated
  6766. * @param {string} name - The name of the uniform.
  6767. * @return {ComputeNode} A reference to this node.
  6768. */
  6769. label( name ) {
  6770. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6771. return this.setName( name );
  6772. }
  6773. /**
  6774. * TODO
  6775. *
  6776. * @param {Function} callback - TODO.
  6777. * @return {ComputeNode} A reference to this node.
  6778. */
  6779. onInit( callback ) {
  6780. this.onInitFunction = callback;
  6781. return this;
  6782. }
  6783. /**
  6784. * The method execute the compute for this node.
  6785. *
  6786. * @param {NodeFrame} frame - A reference to the current node frame.
  6787. */
  6788. updateBefore( { renderer } ) {
  6789. renderer.compute( this );
  6790. }
  6791. setup( builder ) {
  6792. const result = this.computeNode.build( builder );
  6793. if ( result ) {
  6794. const properties = builder.getNodeProperties( this );
  6795. properties.outputComputeNode = result.outputNode;
  6796. result.outputNode = null;
  6797. }
  6798. return result;
  6799. }
  6800. generate( builder, output ) {
  6801. const { shaderStage } = builder;
  6802. if ( shaderStage === 'compute' ) {
  6803. const snippet = this.computeNode.build( builder, 'void' );
  6804. if ( snippet !== '' ) {
  6805. builder.addLineFlowCode( snippet, this );
  6806. }
  6807. } else {
  6808. const properties = builder.getNodeProperties( this );
  6809. const outputComputeNode = properties.outputComputeNode;
  6810. if ( outputComputeNode ) {
  6811. return outputComputeNode.build( builder, output );
  6812. }
  6813. }
  6814. }
  6815. }
  6816. /**
  6817. * TSL function for creating a compute kernel node.
  6818. *
  6819. * @tsl
  6820. * @function
  6821. * @param {Node} node - TODO
  6822. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6823. * @returns {AtomicFunctionNode}
  6824. */
  6825. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6826. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6827. console.error( 'THREE.TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6828. }
  6829. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6830. const val = workgroupSize[ i ];
  6831. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6832. console.error( `THREE.TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6833. }
  6834. }
  6835. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6836. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6837. //
  6838. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6839. };
  6840. /**
  6841. * TSL function for creating a compute node.
  6842. *
  6843. * @tsl
  6844. * @function
  6845. * @param {Node} node - TODO
  6846. * @param {number} count - TODO.
  6847. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6848. * @returns {AtomicFunctionNode}
  6849. */
  6850. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  6851. addMethodChaining( 'compute', compute );
  6852. addMethodChaining( 'computeKernel', computeKernel );
  6853. /**
  6854. * This node can be used as a cache management component for another node.
  6855. * Caching is in general used by default in {@link NodeBuilder} but this node
  6856. * allows the usage of a shared parent cache during the build process.
  6857. *
  6858. * @augments Node
  6859. */
  6860. class CacheNode extends Node {
  6861. static get type() {
  6862. return 'CacheNode';
  6863. }
  6864. /**
  6865. * Constructs a new cache node.
  6866. *
  6867. * @param {Node} node - The node that should be cached.
  6868. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6869. */
  6870. constructor( node, parent = true ) {
  6871. super();
  6872. /**
  6873. * The node that should be cached.
  6874. *
  6875. * @type {Node}
  6876. */
  6877. this.node = node;
  6878. /**
  6879. * Whether this node refers to a shared parent cache or not.
  6880. *
  6881. * @type {boolean}
  6882. * @default true
  6883. */
  6884. this.parent = parent;
  6885. /**
  6886. * This flag can be used for type testing.
  6887. *
  6888. * @type {boolean}
  6889. * @readonly
  6890. * @default true
  6891. */
  6892. this.isCacheNode = true;
  6893. }
  6894. getNodeType( builder ) {
  6895. const previousCache = builder.getCache();
  6896. const cache = builder.getCacheFromNode( this, this.parent );
  6897. builder.setCache( cache );
  6898. const nodeType = this.node.getNodeType( builder );
  6899. builder.setCache( previousCache );
  6900. return nodeType;
  6901. }
  6902. build( builder, ...params ) {
  6903. const previousCache = builder.getCache();
  6904. const cache = builder.getCacheFromNode( this, this.parent );
  6905. builder.setCache( cache );
  6906. const data = this.node.build( builder, ...params );
  6907. builder.setCache( previousCache );
  6908. return data;
  6909. }
  6910. }
  6911. /**
  6912. * TSL function for creating a cache node.
  6913. *
  6914. * @tsl
  6915. * @function
  6916. * @param {Node} node - The node that should be cached.
  6917. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6918. * @returns {CacheNode}
  6919. */
  6920. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6921. addMethodChaining( 'cache', cache );
  6922. /**
  6923. * The class generates the code of a given node but returns another node in the output.
  6924. * This can be used to call a method or node that does not return a value, i.e.
  6925. * type `void` on an input where returning a value is required. Example:
  6926. *
  6927. * ```js
  6928. * material.colorNode = myColor.bypass( runVoidFn() )
  6929. *```
  6930. *
  6931. * @augments Node
  6932. */
  6933. class BypassNode extends Node {
  6934. static get type() {
  6935. return 'BypassNode';
  6936. }
  6937. /**
  6938. * Constructs a new bypass node.
  6939. *
  6940. * @param {Node} outputNode - The output node.
  6941. * @param {Node} callNode - The call node.
  6942. */
  6943. constructor( outputNode, callNode ) {
  6944. super();
  6945. /**
  6946. * This flag can be used for type testing.
  6947. *
  6948. * @type {boolean}
  6949. * @readonly
  6950. * @default true
  6951. */
  6952. this.isBypassNode = true;
  6953. /**
  6954. * The output node.
  6955. *
  6956. * @type {Node}
  6957. */
  6958. this.outputNode = outputNode;
  6959. /**
  6960. * The call node.
  6961. *
  6962. * @type {Node}
  6963. */
  6964. this.callNode = callNode;
  6965. }
  6966. getNodeType( builder ) {
  6967. return this.outputNode.getNodeType( builder );
  6968. }
  6969. generate( builder ) {
  6970. const snippet = this.callNode.build( builder, 'void' );
  6971. if ( snippet !== '' ) {
  6972. builder.addLineFlowCode( snippet, this );
  6973. }
  6974. return this.outputNode.build( builder );
  6975. }
  6976. }
  6977. /**
  6978. * TSL function for creating a bypass node.
  6979. *
  6980. * @tsl
  6981. * @function
  6982. * @param {Node} outputNode - The output node.
  6983. * @param {Node} callNode - The call node.
  6984. * @returns {BypassNode}
  6985. */
  6986. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6987. addMethodChaining( 'bypass', bypass );
  6988. /**
  6989. * This node allows to remap a node value from one range into another. E.g a value of
  6990. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6991. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6992. *
  6993. * @augments Node
  6994. */
  6995. class RemapNode extends Node {
  6996. static get type() {
  6997. return 'RemapNode';
  6998. }
  6999. /**
  7000. * Constructs a new remap node.
  7001. *
  7002. * @param {Node} node - The node that should be remapped.
  7003. * @param {Node} inLowNode - The source or current lower bound of the range.
  7004. * @param {Node} inHighNode - The source or current upper bound of the range.
  7005. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7006. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7007. */
  7008. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7009. super();
  7010. /**
  7011. * The node that should be remapped.
  7012. *
  7013. * @type {Node}
  7014. */
  7015. this.node = node;
  7016. /**
  7017. * The source or current lower bound of the range.
  7018. *
  7019. * @type {Node}
  7020. */
  7021. this.inLowNode = inLowNode;
  7022. /**
  7023. * The source or current upper bound of the range.
  7024. *
  7025. * @type {Node}
  7026. */
  7027. this.inHighNode = inHighNode;
  7028. /**
  7029. * The target lower bound of the range.
  7030. *
  7031. * @type {Node}
  7032. * @default float(0)
  7033. */
  7034. this.outLowNode = outLowNode;
  7035. /**
  7036. * The target upper bound of the range.
  7037. *
  7038. * @type {Node}
  7039. * @default float(1)
  7040. */
  7041. this.outHighNode = outHighNode;
  7042. /**
  7043. * Whether the node value should be clamped before
  7044. * remapping it to the target range.
  7045. *
  7046. * @type {boolean}
  7047. * @default true
  7048. */
  7049. this.doClamp = true;
  7050. }
  7051. setup() {
  7052. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7053. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7054. if ( doClamp === true ) t = t.clamp();
  7055. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7056. }
  7057. }
  7058. /**
  7059. * TSL function for creating a remap node.
  7060. *
  7061. * @tsl
  7062. * @function
  7063. * @param {Node} node - The node that should be remapped.
  7064. * @param {Node} inLowNode - The source or current lower bound of the range.
  7065. * @param {Node} inHighNode - The source or current upper bound of the range.
  7066. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7067. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7068. * @returns {RemapNode}
  7069. */
  7070. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7071. /**
  7072. * TSL function for creating a remap node, but with enabled clamping.
  7073. *
  7074. * @tsl
  7075. * @function
  7076. * @param {Node} node - The node that should be remapped.
  7077. * @param {Node} inLowNode - The source or current lower bound of the range.
  7078. * @param {Node} inHighNode - The source or current upper bound of the range.
  7079. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7080. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7081. * @returns {RemapNode}
  7082. */
  7083. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7084. addMethodChaining( 'remap', remap );
  7085. addMethodChaining( 'remapClamp', remapClamp );
  7086. /**
  7087. * This class can be used to implement basic expressions in shader code.
  7088. * Basic examples for that are `return`, `continue` or `discard` statements.
  7089. *
  7090. * @augments Node
  7091. */
  7092. class ExpressionNode extends Node {
  7093. static get type() {
  7094. return 'ExpressionNode';
  7095. }
  7096. /**
  7097. * Constructs a new expression node.
  7098. *
  7099. * @param {string} [snippet=''] - The native code snippet.
  7100. * @param {string} [nodeType='void'] - The node type.
  7101. */
  7102. constructor( snippet = '', nodeType = 'void' ) {
  7103. super( nodeType );
  7104. /**
  7105. * The native code snippet.
  7106. *
  7107. * @type {string}
  7108. * @default ''
  7109. */
  7110. this.snippet = snippet;
  7111. }
  7112. generate( builder, output ) {
  7113. const type = this.getNodeType( builder );
  7114. const snippet = this.snippet;
  7115. if ( type === 'void' ) {
  7116. builder.addLineFlowCode( snippet, this );
  7117. } else {
  7118. return builder.format( snippet, type, output );
  7119. }
  7120. }
  7121. }
  7122. /**
  7123. * TSL function for creating an expression node.
  7124. *
  7125. * @tsl
  7126. * @function
  7127. * @param {string} [snippet] - The native code snippet.
  7128. * @param {?string} [nodeType='void'] - The node type.
  7129. * @returns {ExpressionNode}
  7130. */
  7131. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7132. /**
  7133. * Represents a `discard` shader operation in TSL.
  7134. *
  7135. * @tsl
  7136. * @function
  7137. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7138. * @return {Node} The `discard` expression.
  7139. */
  7140. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7141. /**
  7142. * Represents a `return` shader operation in TSL.
  7143. *
  7144. * @tsl
  7145. * @function
  7146. * @return {ExpressionNode} The `return` expression.
  7147. */
  7148. const Return = () => expression( 'return' ).toStack();
  7149. addMethodChaining( 'discard', Discard );
  7150. /**
  7151. * Normally, tone mapping and color conversion happens automatically
  7152. * before outputting pixel too the default (screen) framebuffer. In certain
  7153. * post processing setups this happens to late because certain effects
  7154. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7155. * to apply tone mapping and color space conversion at an arbitrary point
  7156. * in the effect chain.
  7157. *
  7158. * When applying tone mapping and color space conversion manually with this node,
  7159. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7160. *
  7161. * ```js
  7162. * const postProcessing = new PostProcessing( renderer );
  7163. * postProcessing.outputColorTransform = false;
  7164. *
  7165. * const scenePass = pass( scene, camera );
  7166. * const outputPass = renderOutput( scenePass );
  7167. *
  7168. * postProcessing.outputNode = outputPass;
  7169. * ```
  7170. *
  7171. * @augments TempNode
  7172. */
  7173. class RenderOutputNode extends TempNode {
  7174. static get type() {
  7175. return 'RenderOutputNode';
  7176. }
  7177. /**
  7178. * Constructs a new render output node.
  7179. *
  7180. * @param {Node} colorNode - The color node to process.
  7181. * @param {?number} toneMapping - The tone mapping type.
  7182. * @param {?string} outputColorSpace - The output color space.
  7183. */
  7184. constructor( colorNode, toneMapping, outputColorSpace ) {
  7185. super( 'vec4' );
  7186. /**
  7187. * The color node to process.
  7188. *
  7189. * @type {Node}
  7190. */
  7191. this.colorNode = colorNode;
  7192. /**
  7193. * The tone mapping type.
  7194. *
  7195. * @type {?number}
  7196. */
  7197. this.toneMapping = toneMapping;
  7198. /**
  7199. * The output color space.
  7200. *
  7201. * @type {?string}
  7202. */
  7203. this.outputColorSpace = outputColorSpace;
  7204. /**
  7205. * This flag can be used for type testing.
  7206. *
  7207. * @type {boolean}
  7208. * @readonly
  7209. * @default true
  7210. */
  7211. this.isRenderOutputNode = true;
  7212. }
  7213. setup( { context } ) {
  7214. let outputNode = this.colorNode || context.color;
  7215. // tone mapping
  7216. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  7217. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7218. if ( toneMapping !== NoToneMapping ) {
  7219. outputNode = outputNode.toneMapping( toneMapping );
  7220. }
  7221. // working to output color space
  7222. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7223. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7224. }
  7225. return outputNode;
  7226. }
  7227. }
  7228. /**
  7229. * TSL function for creating a posterize node.
  7230. *
  7231. * @tsl
  7232. * @function
  7233. * @param {Node} color - The color node to process.
  7234. * @param {?number} [toneMapping=null] - The tone mapping type.
  7235. * @param {?string} [outputColorSpace=null] - The output color space.
  7236. * @returns {RenderOutputNode}
  7237. */
  7238. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7239. addMethodChaining( 'renderOutput', renderOutput );
  7240. class DebugNode extends TempNode {
  7241. static get type() {
  7242. return 'DebugNode';
  7243. }
  7244. constructor( node, callback = null ) {
  7245. super();
  7246. this.node = node;
  7247. this.callback = callback;
  7248. }
  7249. getNodeType( builder ) {
  7250. return this.node.getNodeType( builder );
  7251. }
  7252. setup( builder ) {
  7253. return this.node.build( builder );
  7254. }
  7255. analyze( builder ) {
  7256. return this.node.build( builder );
  7257. }
  7258. generate( builder ) {
  7259. const callback = this.callback;
  7260. const snippet = this.node.build( builder );
  7261. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7262. const border = '-'.repeat( title.length );
  7263. let code = '';
  7264. code += '// #' + title + '#\n';
  7265. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7266. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7267. code += '// #' + border + '#\n';
  7268. if ( callback !== null ) {
  7269. callback( builder, code );
  7270. } else {
  7271. console.log( code );
  7272. }
  7273. return snippet;
  7274. }
  7275. }
  7276. /**
  7277. * TSL function for creating a debug node.
  7278. *
  7279. * @tsl
  7280. * @function
  7281. * @param {Node} node - The node to debug.
  7282. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7283. * @returns {DebugNode}
  7284. */
  7285. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7286. addMethodChaining( 'debug', debug );
  7287. // Non-PURE exports list, side-effects are required here.
  7288. // TSL Base Syntax
  7289. function addNodeElement( name/*, nodeElement*/ ) {
  7290. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7291. }
  7292. /**
  7293. * Base class for representing shader attributes as nodes.
  7294. *
  7295. * @augments Node
  7296. */
  7297. class AttributeNode extends Node {
  7298. static get type() {
  7299. return 'AttributeNode';
  7300. }
  7301. /**
  7302. * Constructs a new attribute node.
  7303. *
  7304. * @param {string} attributeName - The name of the attribute.
  7305. * @param {?string} nodeType - The node type.
  7306. */
  7307. constructor( attributeName, nodeType = null ) {
  7308. super( nodeType );
  7309. /**
  7310. * `AttributeNode` sets this property to `true` by default.
  7311. *
  7312. * @type {boolean}
  7313. * @default true
  7314. */
  7315. this.global = true;
  7316. this._attributeName = attributeName;
  7317. }
  7318. getHash( builder ) {
  7319. return this.getAttributeName( builder );
  7320. }
  7321. getNodeType( builder ) {
  7322. let nodeType = this.nodeType;
  7323. if ( nodeType === null ) {
  7324. const attributeName = this.getAttributeName( builder );
  7325. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7326. const attribute = builder.geometry.getAttribute( attributeName );
  7327. nodeType = builder.getTypeFromAttribute( attribute );
  7328. } else {
  7329. nodeType = 'float';
  7330. }
  7331. }
  7332. return nodeType;
  7333. }
  7334. /**
  7335. * Sets the attribute name to the given value. The method can be
  7336. * overwritten in derived classes if the final name must be computed
  7337. * analytically.
  7338. *
  7339. * @param {string} attributeName - The name of the attribute.
  7340. * @return {AttributeNode} A reference to this node.
  7341. */
  7342. setAttributeName( attributeName ) {
  7343. this._attributeName = attributeName;
  7344. return this;
  7345. }
  7346. /**
  7347. * Returns the attribute name of this node. The method can be
  7348. * overwritten in derived classes if the final name must be computed
  7349. * analytically.
  7350. *
  7351. * @param {NodeBuilder} builder - The current node builder.
  7352. * @return {string} The attribute name.
  7353. */
  7354. getAttributeName( /*builder*/ ) {
  7355. return this._attributeName;
  7356. }
  7357. generate( builder ) {
  7358. const attributeName = this.getAttributeName( builder );
  7359. const nodeType = this.getNodeType( builder );
  7360. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7361. if ( geometryAttribute === true ) {
  7362. const attribute = builder.geometry.getAttribute( attributeName );
  7363. const attributeType = builder.getTypeFromAttribute( attribute );
  7364. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7365. if ( builder.shaderStage === 'vertex' ) {
  7366. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7367. } else {
  7368. const nodeVarying = varying( this );
  7369. return nodeVarying.build( builder, nodeType );
  7370. }
  7371. } else {
  7372. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7373. return builder.generateConst( nodeType );
  7374. }
  7375. }
  7376. serialize( data ) {
  7377. super.serialize( data );
  7378. data.global = this.global;
  7379. data._attributeName = this._attributeName;
  7380. }
  7381. deserialize( data ) {
  7382. super.deserialize( data );
  7383. this.global = data.global;
  7384. this._attributeName = data._attributeName;
  7385. }
  7386. }
  7387. /**
  7388. * TSL function for creating an attribute node.
  7389. *
  7390. * @tsl
  7391. * @function
  7392. * @param {string} name - The name of the attribute.
  7393. * @param {?string} [nodeType=null] - The node type.
  7394. * @returns {AttributeNode}
  7395. */
  7396. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7397. /**
  7398. * TSL function for creating an uv attribute node with the given index.
  7399. *
  7400. * @tsl
  7401. * @function
  7402. * @param {number} [index=0] - The uv index.
  7403. * @return {AttributeNode<vec2>} The uv attribute node.
  7404. */
  7405. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7406. /**
  7407. * A node that represents the dimensions of a texture. The texture size is
  7408. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7409. * or `textureSize()`.
  7410. *
  7411. * @augments Node
  7412. */
  7413. class TextureSizeNode extends Node {
  7414. static get type() {
  7415. return 'TextureSizeNode';
  7416. }
  7417. /**
  7418. * Constructs a new texture size node.
  7419. *
  7420. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7421. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7422. */
  7423. constructor( textureNode, levelNode = null ) {
  7424. super( 'uvec2' );
  7425. /**
  7426. * This flag can be used for type testing.
  7427. *
  7428. * @type {boolean}
  7429. * @readonly
  7430. * @default true
  7431. */
  7432. this.isTextureSizeNode = true;
  7433. /**
  7434. * A texture node which size should be retrieved.
  7435. *
  7436. * @type {TextureNode}
  7437. */
  7438. this.textureNode = textureNode;
  7439. /**
  7440. * A level node which defines the requested mip.
  7441. *
  7442. * @type {Node<int>}
  7443. * @default null
  7444. */
  7445. this.levelNode = levelNode;
  7446. }
  7447. generate( builder, output ) {
  7448. const textureProperty = this.textureNode.build( builder, 'property' );
  7449. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7450. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7451. }
  7452. }
  7453. /**
  7454. * TSL function for creating a texture size node.
  7455. *
  7456. * @tsl
  7457. * @function
  7458. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7459. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7460. * @returns {TextureSizeNode}
  7461. */
  7462. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7463. /**
  7464. * A special type of uniform node that computes the
  7465. * maximum mipmap level for a given texture node.
  7466. *
  7467. * ```js
  7468. * const level = maxMipLevel( textureNode );
  7469. * ```
  7470. *
  7471. * @augments UniformNode
  7472. */
  7473. class MaxMipLevelNode extends UniformNode {
  7474. static get type() {
  7475. return 'MaxMipLevelNode';
  7476. }
  7477. /**
  7478. * Constructs a new max mip level node.
  7479. *
  7480. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7481. */
  7482. constructor( textureNode ) {
  7483. super( 0 );
  7484. /**
  7485. * The texture node to compute the max mip level for.
  7486. *
  7487. * @private
  7488. * @type {TextureNode}
  7489. */
  7490. this._textureNode = textureNode;
  7491. /**
  7492. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7493. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7494. *
  7495. * @type {string}
  7496. * @default 'frame'
  7497. */
  7498. this.updateType = NodeUpdateType.FRAME;
  7499. }
  7500. /**
  7501. * The texture node to compute the max mip level for.
  7502. *
  7503. * @readonly
  7504. * @type {TextureNode}
  7505. */
  7506. get textureNode() {
  7507. return this._textureNode;
  7508. }
  7509. /**
  7510. * The texture.
  7511. *
  7512. * @readonly
  7513. * @type {Texture}
  7514. */
  7515. get texture() {
  7516. return this._textureNode.value;
  7517. }
  7518. update() {
  7519. const texture = this.texture;
  7520. const images = texture.images;
  7521. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7522. if ( image && image.width !== undefined ) {
  7523. const { width, height } = image;
  7524. this.value = Math.log2( Math.max( width, height ) );
  7525. }
  7526. }
  7527. }
  7528. /**
  7529. * TSL function for creating a max mip level node.
  7530. *
  7531. * @tsl
  7532. * @function
  7533. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7534. * @returns {MaxMipLevelNode}
  7535. */
  7536. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7537. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7538. /**
  7539. * This type of uniform node represents a 2D texture.
  7540. *
  7541. * @augments UniformNode
  7542. */
  7543. class TextureNode extends UniformNode {
  7544. static get type() {
  7545. return 'TextureNode';
  7546. }
  7547. /**
  7548. * Constructs a new texture node.
  7549. *
  7550. * @param {Texture} [value=EmptyTexture] - The texture.
  7551. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7552. * @param {?Node<int>} [levelNode=null] - The level node.
  7553. * @param {?Node<float>} [biasNode=null] - The bias node.
  7554. */
  7555. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7556. super( value );
  7557. /**
  7558. * This flag can be used for type testing.
  7559. *
  7560. * @type {boolean}
  7561. * @readonly
  7562. * @default true
  7563. */
  7564. this.isTextureNode = true;
  7565. /**
  7566. * Represents the texture coordinates.
  7567. *
  7568. * @type {?Node<vec2|vec3>}
  7569. * @default null
  7570. */
  7571. this.uvNode = uvNode;
  7572. /**
  7573. * Represents the mip level that should be selected.
  7574. *
  7575. * @type {?Node<int>}
  7576. * @default null
  7577. */
  7578. this.levelNode = levelNode;
  7579. /**
  7580. * Represents the bias to be applied during level-of-detail computation.
  7581. *
  7582. * @type {?Node<float>}
  7583. * @default null
  7584. */
  7585. this.biasNode = biasNode;
  7586. /**
  7587. * Represents a reference value a texture sample is compared to.
  7588. *
  7589. * @type {?Node<float>}
  7590. * @default null
  7591. */
  7592. this.compareNode = null;
  7593. /**
  7594. * When using texture arrays, the depth node defines the layer to select.
  7595. *
  7596. * @type {?Node<int>}
  7597. * @default null
  7598. */
  7599. this.depthNode = null;
  7600. /**
  7601. * When defined, a texture is sampled using explicit gradients.
  7602. *
  7603. * @type {?Array<Node<vec2>>}
  7604. * @default null
  7605. */
  7606. this.gradNode = null;
  7607. /**
  7608. * Whether texture values should be sampled or fetched.
  7609. *
  7610. * @type {boolean}
  7611. * @default true
  7612. */
  7613. this.sampler = true;
  7614. /**
  7615. * Whether the uv transformation matrix should be
  7616. * automatically updated or not. Use `setUpdateMatrix()`
  7617. * if you want to change the value of the property.
  7618. *
  7619. * @type {boolean}
  7620. * @default false
  7621. */
  7622. this.updateMatrix = false;
  7623. /**
  7624. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7625. * sets the value to `frame` when the uv transformation matrix should
  7626. * automatically be updated.
  7627. *
  7628. * @type {string}
  7629. * @default 'none'
  7630. */
  7631. this.updateType = NodeUpdateType.NONE;
  7632. /**
  7633. * The reference node.
  7634. *
  7635. * @type {?Node}
  7636. * @default null
  7637. */
  7638. this.referenceNode = null;
  7639. /**
  7640. * The texture value is stored in a private property.
  7641. *
  7642. * @private
  7643. * @type {Texture}
  7644. */
  7645. this._value = value;
  7646. /**
  7647. * The uniform node that represents the uv transformation matrix.
  7648. *
  7649. * @private
  7650. * @type {?UniformNode<mat3>}
  7651. */
  7652. this._matrixUniform = null;
  7653. this.setUpdateMatrix( uvNode === null );
  7654. }
  7655. set value( value ) {
  7656. if ( this.referenceNode ) {
  7657. this.referenceNode.value = value;
  7658. } else {
  7659. this._value = value;
  7660. }
  7661. }
  7662. /**
  7663. * The texture value.
  7664. *
  7665. * @type {Texture}
  7666. */
  7667. get value() {
  7668. return this.referenceNode ? this.referenceNode.value : this._value;
  7669. }
  7670. /**
  7671. * Overwritten since the uniform hash is defined by the texture's UUID.
  7672. *
  7673. * @param {NodeBuilder} builder - The current node builder.
  7674. * @return {string} The uniform hash.
  7675. */
  7676. getUniformHash( /*builder*/ ) {
  7677. return this.value.uuid;
  7678. }
  7679. /**
  7680. * Overwritten since the node type is inferred from the texture type.
  7681. *
  7682. * @param {NodeBuilder} builder - The current node builder.
  7683. * @return {string} The node type.
  7684. */
  7685. getNodeType( /*builder*/ ) {
  7686. if ( this.value.isDepthTexture === true ) return 'float';
  7687. if ( this.value.type === UnsignedIntType ) {
  7688. return 'uvec4';
  7689. } else if ( this.value.type === IntType ) {
  7690. return 'ivec4';
  7691. }
  7692. return 'vec4';
  7693. }
  7694. /**
  7695. * Overwrites the default implementation to return a fixed value `'texture'`.
  7696. *
  7697. * @param {NodeBuilder} builder - The current node builder.
  7698. * @return {string} The input type.
  7699. */
  7700. getInputType( /*builder*/ ) {
  7701. return 'texture';
  7702. }
  7703. /**
  7704. * Returns a default uvs based on the current texture's channel.
  7705. *
  7706. * @return {AttributeNode<vec2>} The default uvs.
  7707. */
  7708. getDefaultUV() {
  7709. return uv$1( this.value.channel );
  7710. }
  7711. /**
  7712. * Overwritten to always return the texture reference of the node.
  7713. *
  7714. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7715. * @return {Texture} The texture reference.
  7716. */
  7717. updateReference( /*state*/ ) {
  7718. return this.value;
  7719. }
  7720. /**
  7721. * Transforms the given uv node with the texture transformation matrix.
  7722. *
  7723. * @param {Node} uvNode - The uv node to transform.
  7724. * @return {Node} The transformed uv node.
  7725. */
  7726. getTransformedUV( uvNode ) {
  7727. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7728. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7729. }
  7730. /**
  7731. * Defines whether the uv transformation matrix should automatically be updated or not.
  7732. *
  7733. * @param {boolean} value - The update toggle.
  7734. * @return {TextureNode} A reference to this node.
  7735. */
  7736. setUpdateMatrix( value ) {
  7737. this.updateMatrix = value;
  7738. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7739. return this;
  7740. }
  7741. /**
  7742. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7743. * to modify the uv node for correct sampling.
  7744. *
  7745. * @param {NodeBuilder} builder - The current node builder.
  7746. * @param {Node} uvNode - The uv node to setup.
  7747. * @return {Node} The updated uv node.
  7748. */
  7749. setupUV( builder, uvNode ) {
  7750. const texture = this.value;
  7751. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7752. if ( this.sampler ) {
  7753. uvNode = uvNode.flipY();
  7754. } else {
  7755. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7756. }
  7757. }
  7758. return uvNode;
  7759. }
  7760. /**
  7761. * Setups texture node by preparing the internal nodes for code generation.
  7762. *
  7763. * @param {NodeBuilder} builder - The current node builder.
  7764. */
  7765. setup( builder ) {
  7766. const properties = builder.getNodeProperties( this );
  7767. properties.referenceNode = this.referenceNode;
  7768. //
  7769. const texture = this.value;
  7770. if ( ! texture || texture.isTexture !== true ) {
  7771. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7772. }
  7773. //
  7774. let uvNode = this.uvNode;
  7775. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7776. uvNode = builder.context.getUV( this, builder );
  7777. }
  7778. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7779. if ( this.updateMatrix === true ) {
  7780. uvNode = this.getTransformedUV( uvNode );
  7781. }
  7782. uvNode = this.setupUV( builder, uvNode );
  7783. //
  7784. let levelNode = this.levelNode;
  7785. if ( levelNode === null && builder.context.getTextureLevel ) {
  7786. levelNode = builder.context.getTextureLevel( this );
  7787. }
  7788. //
  7789. properties.uvNode = uvNode;
  7790. properties.levelNode = levelNode;
  7791. properties.biasNode = this.biasNode;
  7792. properties.compareNode = this.compareNode;
  7793. properties.gradNode = this.gradNode;
  7794. properties.depthNode = this.depthNode;
  7795. }
  7796. /**
  7797. * Generates the uv code snippet.
  7798. *
  7799. * @param {NodeBuilder} builder - The current node builder.
  7800. * @param {Node} uvNode - The uv node to generate code for.
  7801. * @return {string} The generated code snippet.
  7802. */
  7803. generateUV( builder, uvNode ) {
  7804. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7805. }
  7806. /**
  7807. * Generates the snippet for the texture sampling.
  7808. *
  7809. * @param {NodeBuilder} builder - The current node builder.
  7810. * @param {string} textureProperty - The texture property.
  7811. * @param {string} uvSnippet - The uv snippet.
  7812. * @param {?string} levelSnippet - The level snippet.
  7813. * @param {?string} biasSnippet - The bias snippet.
  7814. * @param {?string} depthSnippet - The depth snippet.
  7815. * @param {?string} compareSnippet - The compare snippet.
  7816. * @param {?Array<string>} gradSnippet - The grad snippet.
  7817. * @return {string} The generated code snippet.
  7818. */
  7819. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7820. const texture = this.value;
  7821. let snippet;
  7822. if ( levelSnippet ) {
  7823. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7824. } else if ( biasSnippet ) {
  7825. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7826. } else if ( gradSnippet ) {
  7827. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7828. } else if ( compareSnippet ) {
  7829. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7830. } else if ( this.sampler === false ) {
  7831. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7832. } else {
  7833. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7834. }
  7835. return snippet;
  7836. }
  7837. /**
  7838. * Generates the code snippet of the texture node.
  7839. *
  7840. * @param {NodeBuilder} builder - The current node builder.
  7841. * @param {string} output - The current output.
  7842. * @return {string} The generated code snippet.
  7843. */
  7844. generate( builder, output ) {
  7845. const texture = this.value;
  7846. const properties = builder.getNodeProperties( this );
  7847. const textureProperty = super.generate( builder, 'property' );
  7848. if ( /^sampler/.test( output ) ) {
  7849. return textureProperty + '_sampler';
  7850. } else if ( builder.isReference( output ) ) {
  7851. return textureProperty;
  7852. } else {
  7853. const nodeData = builder.getDataFromNode( this );
  7854. let propertyName = nodeData.propertyName;
  7855. if ( propertyName === undefined ) {
  7856. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7857. const uvSnippet = this.generateUV( builder, uvNode );
  7858. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7859. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7860. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7861. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7862. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7863. const nodeVar = builder.getVarFromNode( this );
  7864. propertyName = builder.getPropertyName( nodeVar );
  7865. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7866. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7867. nodeData.snippet = snippet;
  7868. nodeData.propertyName = propertyName;
  7869. }
  7870. let snippet = propertyName;
  7871. const nodeType = this.getNodeType( builder );
  7872. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7873. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7874. }
  7875. return builder.format( snippet, nodeType, output );
  7876. }
  7877. }
  7878. /**
  7879. * Sets the sampler value.
  7880. *
  7881. * @param {boolean} value - The sampler value to set.
  7882. * @return {TextureNode} A reference to this texture node.
  7883. */
  7884. setSampler( value ) {
  7885. this.sampler = value;
  7886. return this;
  7887. }
  7888. /**
  7889. * Returns the sampler value.
  7890. *
  7891. * @return {boolean} The sampler value.
  7892. */
  7893. getSampler() {
  7894. return this.sampler;
  7895. }
  7896. // @TODO: Move to TSL
  7897. /**
  7898. * @function
  7899. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7900. *
  7901. * @param {Node} uvNode - The uv node.
  7902. * @return {TextureNode} A texture node representing the texture sample.
  7903. */
  7904. uv( uvNode ) { // @deprecated, r172
  7905. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7906. return this.sample( uvNode );
  7907. }
  7908. /**
  7909. * Samples the texture with the given uv node.
  7910. *
  7911. * @param {Node} uvNode - The uv node.
  7912. * @return {TextureNode} A texture node representing the texture sample.
  7913. */
  7914. sample( uvNode ) {
  7915. const textureNode = this.clone();
  7916. textureNode.uvNode = nodeObject( uvNode );
  7917. textureNode.referenceNode = this.getBase();
  7918. return nodeObject( textureNode );
  7919. }
  7920. /**
  7921. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7922. *
  7923. * @param {Node<uvec2>} uvNode - The uv node.
  7924. * @returns {TextureNode} A texture node representing the texture load.
  7925. */
  7926. load( uvNode ) {
  7927. return this.sample( uvNode ).setSampler( false );
  7928. }
  7929. /**
  7930. * Samples a blurred version of the texture by defining an internal bias.
  7931. *
  7932. * @param {Node<float>} amountNode - How blurred the texture should be.
  7933. * @return {TextureNode} A texture node representing the texture sample.
  7934. */
  7935. blur( amountNode ) {
  7936. const textureNode = this.clone();
  7937. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7938. textureNode.referenceNode = this.getBase();
  7939. const map = textureNode.value;
  7940. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7941. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7942. textureNode.biasNode = null;
  7943. }
  7944. return nodeObject( textureNode );
  7945. }
  7946. /**
  7947. * Samples a specific mip of the texture.
  7948. *
  7949. * @param {Node<int>} levelNode - The mip level to sample.
  7950. * @return {TextureNode} A texture node representing the texture sample.
  7951. */
  7952. level( levelNode ) {
  7953. const textureNode = this.clone();
  7954. textureNode.levelNode = nodeObject( levelNode );
  7955. textureNode.referenceNode = this.getBase();
  7956. return nodeObject( textureNode );
  7957. }
  7958. /**
  7959. * Returns the texture size of the requested level.
  7960. *
  7961. * @param {Node<int>} levelNode - The level to compute the size for.
  7962. * @return {TextureSizeNode} The texture size.
  7963. */
  7964. size( levelNode ) {
  7965. return textureSize( this, levelNode );
  7966. }
  7967. /**
  7968. * Samples the texture with the given bias.
  7969. *
  7970. * @param {Node<float>} biasNode - The bias node.
  7971. * @return {TextureNode} A texture node representing the texture sample.
  7972. */
  7973. bias( biasNode ) {
  7974. const textureNode = this.clone();
  7975. textureNode.biasNode = nodeObject( biasNode );
  7976. textureNode.referenceNode = this.getBase();
  7977. return nodeObject( textureNode );
  7978. }
  7979. /**
  7980. * Returns the base texture of this node.
  7981. * @return {TextureNode} The base texture node.
  7982. */
  7983. getBase() {
  7984. return this.referenceNode ? this.referenceNode.getBase() : this.getSelf();
  7985. }
  7986. /**
  7987. * Samples the texture by executing a compare operation.
  7988. *
  7989. * @param {Node<float>} compareNode - The node that defines the compare value.
  7990. * @return {TextureNode} A texture node representing the texture sample.
  7991. */
  7992. compare( compareNode ) {
  7993. const textureNode = this.clone();
  7994. textureNode.compareNode = nodeObject( compareNode );
  7995. textureNode.referenceNode = this.getBase();
  7996. return nodeObject( textureNode );
  7997. }
  7998. /**
  7999. * Samples the texture using an explicit gradient.
  8000. *
  8001. * @param {Node<vec2>} gradNodeX - The gradX node.
  8002. * @param {Node<vec2>} gradNodeY - The gradY node.
  8003. * @return {TextureNode} A texture node representing the texture sample.
  8004. */
  8005. grad( gradNodeX, gradNodeY ) {
  8006. const textureNode = this.clone();
  8007. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8008. textureNode.referenceNode = this.getBase();
  8009. return nodeObject( textureNode );
  8010. }
  8011. /**
  8012. * Samples the texture by defining a depth node.
  8013. *
  8014. * @param {Node<int>} depthNode - The depth node.
  8015. * @return {TextureNode} A texture node representing the texture sample.
  8016. */
  8017. depth( depthNode ) {
  8018. const textureNode = this.clone();
  8019. textureNode.depthNode = nodeObject( depthNode );
  8020. textureNode.referenceNode = this.getBase();
  8021. return nodeObject( textureNode );
  8022. }
  8023. // --
  8024. serialize( data ) {
  8025. super.serialize( data );
  8026. data.value = this.value.toJSON( data.meta ).uuid;
  8027. data.sampler = this.sampler;
  8028. data.updateMatrix = this.updateMatrix;
  8029. data.updateType = this.updateType;
  8030. }
  8031. deserialize( data ) {
  8032. super.deserialize( data );
  8033. this.value = data.meta.textures[ data.value ];
  8034. this.sampler = data.sampler;
  8035. this.updateMatrix = data.updateMatrix;
  8036. this.updateType = data.updateType;
  8037. }
  8038. /**
  8039. * The update is used to implement the update of the uv transformation matrix.
  8040. */
  8041. update() {
  8042. const texture = this.value;
  8043. const matrixUniform = this._matrixUniform;
  8044. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8045. if ( texture.matrixAutoUpdate === true ) {
  8046. texture.updateMatrix();
  8047. }
  8048. }
  8049. /**
  8050. * Clones the texture node.
  8051. *
  8052. * @return {TextureNode} The cloned texture node.
  8053. */
  8054. clone() {
  8055. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8056. newNode.sampler = this.sampler;
  8057. newNode.depthNode = this.depthNode;
  8058. newNode.compareNode = this.compareNode;
  8059. newNode.gradNode = this.gradNode;
  8060. return newNode;
  8061. }
  8062. }
  8063. /**
  8064. * TSL function for creating a texture node.
  8065. *
  8066. * @tsl
  8067. * @function
  8068. * @param {?Texture} value - The texture.
  8069. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8070. * @param {?Node<int>} [levelNode=null] - The level node.
  8071. * @param {?Node<float>} [biasNode=null] - The bias node.
  8072. * @returns {TextureNode}
  8073. */
  8074. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8075. /**
  8076. * TSL function for creating a texture node or sample a texture node already existing.
  8077. *
  8078. * @tsl
  8079. * @function
  8080. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  8081. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8082. * @param {?Node<int>} [levelNode=null] - The level node.
  8083. * @param {?Node<float>} [biasNode=null] - The bias node.
  8084. * @returns {TextureNode}
  8085. */
  8086. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8087. let textureNode;
  8088. if ( value && value.isTextureNode === true ) {
  8089. textureNode = nodeObject( value.clone() );
  8090. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8091. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8092. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8093. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8094. } else {
  8095. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8096. }
  8097. return textureNode;
  8098. };
  8099. /**
  8100. * TSL function for creating a uniform texture node.
  8101. *
  8102. * @tsl
  8103. * @function
  8104. * @param {?Texture} value - The texture.
  8105. * @returns {TextureNode}
  8106. */
  8107. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8108. /**
  8109. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8110. *
  8111. * @tsl
  8112. * @function
  8113. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  8114. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8115. * @param {?Node<int>} [levelNode=null] - The level node.
  8116. * @param {?Node<float>} [biasNode=null] - The bias node.
  8117. * @returns {TextureNode}
  8118. */
  8119. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8120. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8121. /**
  8122. * Converts a texture or texture node to a sampler.
  8123. *
  8124. * @tsl
  8125. * @function
  8126. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8127. * @returns {Node}
  8128. */
  8129. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8130. /**
  8131. * Converts a texture or texture node to a sampler comparison.
  8132. *
  8133. * @tsl
  8134. * @function
  8135. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8136. * @returns {Node}
  8137. */
  8138. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8139. /**
  8140. * A special type of uniform node which represents array-like data
  8141. * as uniform buffers. The access usually happens via `element()`
  8142. * which returns an instance of {@link ArrayElementNode}. For example:
  8143. *
  8144. * ```js
  8145. * const bufferNode = buffer( array, 'mat4', count );
  8146. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8147. * ```
  8148. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8149. * since it handles more input types and automatically cares about buffer paddings.
  8150. *
  8151. * @augments UniformNode
  8152. */
  8153. class BufferNode extends UniformNode {
  8154. static get type() {
  8155. return 'BufferNode';
  8156. }
  8157. /**
  8158. * Constructs a new buffer node.
  8159. *
  8160. * @param {Array<number>} value - Array-like buffer data.
  8161. * @param {string} bufferType - The data type of the buffer.
  8162. * @param {number} [bufferCount=0] - The count of buffer elements.
  8163. */
  8164. constructor( value, bufferType, bufferCount = 0 ) {
  8165. super( value, bufferType );
  8166. /**
  8167. * This flag can be used for type testing.
  8168. *
  8169. * @type {boolean}
  8170. * @readonly
  8171. * @default true
  8172. */
  8173. this.isBufferNode = true;
  8174. /**
  8175. * The data type of the buffer.
  8176. *
  8177. * @type {string}
  8178. */
  8179. this.bufferType = bufferType;
  8180. /**
  8181. * The uniform node that holds the value of the reference node.
  8182. *
  8183. * @type {number}
  8184. * @default 0
  8185. */
  8186. this.bufferCount = bufferCount;
  8187. }
  8188. /**
  8189. * The data type of the buffer elements.
  8190. *
  8191. * @param {NodeBuilder} builder - The current node builder.
  8192. * @return {string} The element type.
  8193. */
  8194. getElementType( builder ) {
  8195. return this.getNodeType( builder );
  8196. }
  8197. /**
  8198. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8199. *
  8200. * @param {NodeBuilder} builder - The current node builder.
  8201. * @return {string} The input type.
  8202. */
  8203. getInputType( /*builder*/ ) {
  8204. return 'buffer';
  8205. }
  8206. }
  8207. /**
  8208. * TSL function for creating a buffer node.
  8209. *
  8210. * @tsl
  8211. * @function
  8212. * @param {Array} value - Array-like buffer data.
  8213. * @param {string} type - The data type of a buffer element.
  8214. * @param {number} count - The count of buffer elements.
  8215. * @returns {BufferNode}
  8216. */
  8217. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8218. /**
  8219. * Represents the element access on uniform array nodes.
  8220. *
  8221. * @augments ArrayElementNode
  8222. */
  8223. class UniformArrayElementNode extends ArrayElementNode {
  8224. static get type() {
  8225. return 'UniformArrayElementNode';
  8226. }
  8227. /**
  8228. * Constructs a new buffer node.
  8229. *
  8230. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8231. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8232. */
  8233. constructor( uniformArrayNode, indexNode ) {
  8234. super( uniformArrayNode, indexNode );
  8235. /**
  8236. * This flag can be used for type testing.
  8237. *
  8238. * @type {boolean}
  8239. * @readonly
  8240. * @default true
  8241. */
  8242. this.isArrayBufferElementNode = true;
  8243. }
  8244. generate( builder ) {
  8245. const snippet = super.generate( builder );
  8246. const type = this.getNodeType();
  8247. const paddedType = this.node.getPaddedType();
  8248. return builder.format( snippet, paddedType, type );
  8249. }
  8250. }
  8251. /**
  8252. * Similar to {@link BufferNode} this module represents array-like data as
  8253. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8254. * data types in the array (e.g `three.js` primitives) and automatically
  8255. * manage buffer padding. It should be the first choice when working with
  8256. * uniforms buffers.
  8257. * ```js
  8258. * const tintColors = uniformArray( [
  8259. * new Color( 1, 0, 0 ),
  8260. * new Color( 0, 1, 0 ),
  8261. * new Color( 0, 0, 1 )
  8262. * ], 'color' );
  8263. *
  8264. * const redColor = tintColors.element( 0 );
  8265. *
  8266. * @augments BufferNode
  8267. */
  8268. class UniformArrayNode extends BufferNode {
  8269. static get type() {
  8270. return 'UniformArrayNode';
  8271. }
  8272. /**
  8273. * Constructs a new uniform array node.
  8274. *
  8275. * @param {Array<any>} value - Array holding the buffer data.
  8276. * @param {?string} [elementType=null] - The data type of a buffer element.
  8277. */
  8278. constructor( value, elementType = null ) {
  8279. super( null );
  8280. /**
  8281. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8282. * hold number primitives as well as three.js objects like vectors, matrices
  8283. * or colors.
  8284. *
  8285. * @type {Array<any>}
  8286. */
  8287. this.array = value;
  8288. /**
  8289. * The data type of an array element.
  8290. *
  8291. * @type {string}
  8292. */
  8293. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8294. /**
  8295. * The padded type. Uniform buffers must conform to a certain buffer layout
  8296. * so a separate type is computed to ensure correct buffer size.
  8297. *
  8298. * @type {string}
  8299. */
  8300. this.paddedType = this.getPaddedType();
  8301. /**
  8302. * Overwritten since uniform array nodes are updated per render.
  8303. *
  8304. * @type {string}
  8305. * @default 'render'
  8306. */
  8307. this.updateType = NodeUpdateType.RENDER;
  8308. /**
  8309. * This flag can be used for type testing.
  8310. *
  8311. * @type {boolean}
  8312. * @readonly
  8313. * @default true
  8314. */
  8315. this.isArrayBufferNode = true;
  8316. }
  8317. /**
  8318. * This method is overwritten since the node type is inferred from the
  8319. * {@link UniformArrayNode#paddedType}.
  8320. *
  8321. * @param {NodeBuilder} builder - The current node builder.
  8322. * @return {string} The node type.
  8323. */
  8324. getNodeType( /*builder*/ ) {
  8325. return this.paddedType;
  8326. }
  8327. /**
  8328. * The data type of the array elements.
  8329. *
  8330. * @param {NodeBuilder} builder - The current node builder.
  8331. * @return {string} The element type.
  8332. */
  8333. getElementType() {
  8334. return this.elementType;
  8335. }
  8336. /**
  8337. * Returns the padded type based on the element type.
  8338. *
  8339. * @return {string} The padded type.
  8340. */
  8341. getPaddedType() {
  8342. const elementType = this.elementType;
  8343. let paddedType = 'vec4';
  8344. if ( elementType === 'mat2' ) {
  8345. paddedType = 'mat2';
  8346. } else if ( /mat/.test( elementType ) === true ) {
  8347. paddedType = 'mat4';
  8348. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8349. paddedType = 'ivec4';
  8350. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8351. paddedType = 'uvec4';
  8352. }
  8353. return paddedType;
  8354. }
  8355. /**
  8356. * The update makes sure to correctly transfer the data from the (complex) objects
  8357. * in the array to the internal, correctly padded value buffer.
  8358. *
  8359. * @param {NodeFrame} frame - A reference to the current node frame.
  8360. */
  8361. update( /*frame*/ ) {
  8362. const { array, value } = this;
  8363. const elementType = this.elementType;
  8364. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8365. for ( let i = 0; i < array.length; i ++ ) {
  8366. const index = i * 4;
  8367. value[ index ] = array[ i ];
  8368. }
  8369. } else if ( elementType === 'color' ) {
  8370. for ( let i = 0; i < array.length; i ++ ) {
  8371. const index = i * 4;
  8372. const vector = array[ i ];
  8373. value[ index ] = vector.r;
  8374. value[ index + 1 ] = vector.g;
  8375. value[ index + 2 ] = vector.b || 0;
  8376. //value[ index + 3 ] = vector.a || 0;
  8377. }
  8378. } else if ( elementType === 'mat2' ) {
  8379. for ( let i = 0; i < array.length; i ++ ) {
  8380. const index = i * 4;
  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 + 3 ] = matrix.elements[ 3 ];
  8386. }
  8387. } else if ( elementType === 'mat3' ) {
  8388. for ( let i = 0; i < array.length; i ++ ) {
  8389. const index = i * 16;
  8390. const matrix = array[ i ];
  8391. value[ index ] = matrix.elements[ 0 ];
  8392. value[ index + 1 ] = matrix.elements[ 1 ];
  8393. value[ index + 2 ] = matrix.elements[ 2 ];
  8394. value[ index + 4 ] = matrix.elements[ 3 ];
  8395. value[ index + 5 ] = matrix.elements[ 4 ];
  8396. value[ index + 6 ] = matrix.elements[ 5 ];
  8397. value[ index + 8 ] = matrix.elements[ 6 ];
  8398. value[ index + 9 ] = matrix.elements[ 7 ];
  8399. value[ index + 10 ] = matrix.elements[ 8 ];
  8400. value[ index + 15 ] = 1;
  8401. }
  8402. } else if ( elementType === 'mat4' ) {
  8403. for ( let i = 0; i < array.length; i ++ ) {
  8404. const index = i * 16;
  8405. const matrix = array[ i ];
  8406. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8407. value[ index + i ] = matrix.elements[ i ];
  8408. }
  8409. }
  8410. } else {
  8411. for ( let i = 0; i < array.length; i ++ ) {
  8412. const index = i * 4;
  8413. const vector = array[ i ];
  8414. value[ index ] = vector.x;
  8415. value[ index + 1 ] = vector.y;
  8416. value[ index + 2 ] = vector.z || 0;
  8417. value[ index + 3 ] = vector.w || 0;
  8418. }
  8419. }
  8420. }
  8421. /**
  8422. * Implement the value buffer creation based on the array data.
  8423. *
  8424. * @param {NodeBuilder} builder - A reference to the current node builder.
  8425. * @return {null}
  8426. */
  8427. setup( builder ) {
  8428. const length = this.array.length;
  8429. const elementType = this.elementType;
  8430. let arrayType = Float32Array;
  8431. const paddedType = this.paddedType;
  8432. const paddedElementLength = builder.getTypeLength( paddedType );
  8433. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8434. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8435. this.value = new arrayType( length * paddedElementLength );
  8436. this.bufferCount = length;
  8437. this.bufferType = paddedType;
  8438. return super.setup( builder );
  8439. }
  8440. /**
  8441. * Overwrites the default `element()` method to provide element access
  8442. * based on {@link UniformArrayNode}.
  8443. *
  8444. * @param {IndexNode} indexNode - The index node.
  8445. * @return {UniformArrayElementNode}
  8446. */
  8447. element( indexNode ) {
  8448. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8449. }
  8450. }
  8451. /**
  8452. * TSL function for creating an uniform array node.
  8453. *
  8454. * @tsl
  8455. * @function
  8456. * @param {Array<any>} values - Array-like data.
  8457. * @param {?string} [nodeType] - The data type of the array elements.
  8458. * @returns {UniformArrayNode}
  8459. */
  8460. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8461. /**
  8462. * The node allows to set values for built-in shader variables. That is
  8463. * required for features like hardware-accelerated vertex clipping.
  8464. *
  8465. * @augments Node
  8466. */
  8467. class BuiltinNode extends Node {
  8468. /**
  8469. * Constructs a new builtin node.
  8470. *
  8471. * @param {string} name - The name of the built-in shader variable.
  8472. */
  8473. constructor( name ) {
  8474. super( 'float' );
  8475. /**
  8476. * The name of the built-in shader variable.
  8477. *
  8478. * @type {string}
  8479. */
  8480. this.name = name;
  8481. /**
  8482. * This flag can be used for type testing.
  8483. *
  8484. * @type {boolean}
  8485. * @readonly
  8486. * @default true
  8487. */
  8488. this.isBuiltinNode = true;
  8489. }
  8490. /**
  8491. * Generates the code snippet of the builtin node.
  8492. *
  8493. * @param {NodeBuilder} builder - The current node builder.
  8494. * @return {string} The generated code snippet.
  8495. */
  8496. generate( /* builder */ ) {
  8497. return this.name;
  8498. }
  8499. }
  8500. /**
  8501. * TSL function for creating a builtin node.
  8502. *
  8503. * @tsl
  8504. * @function
  8505. * @param {string} name - The name of the built-in shader variable.
  8506. * @returns {BuiltinNode}
  8507. */
  8508. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8509. let screenSizeVec, viewportVec;
  8510. /**
  8511. * This node provides a collection of screen related metrics.
  8512. * Depending on {@link ScreenNode#scope}, the nodes can represent
  8513. * resolution or viewport data as well as fragment or uv coordinates.
  8514. *
  8515. * @augments Node
  8516. */
  8517. class ScreenNode extends Node {
  8518. static get type() {
  8519. return 'ScreenNode';
  8520. }
  8521. /**
  8522. * Constructs a new screen node.
  8523. *
  8524. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  8525. */
  8526. constructor( scope ) {
  8527. super();
  8528. /**
  8529. * The node represents different metric depending on which scope is selected.
  8530. *
  8531. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  8532. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  8533. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  8534. * - `ScreenNode.UV`: Normalized coordinates.
  8535. *
  8536. * @type {('coordinate'|'viewport'|'size'|'uv')}
  8537. */
  8538. this.scope = scope;
  8539. /**
  8540. * This flag can be used for type testing.
  8541. *
  8542. * @type {boolean}
  8543. * @readonly
  8544. * @default true
  8545. */
  8546. this.isViewportNode = true;
  8547. }
  8548. /**
  8549. * This method is overwritten since the node type depends on the selected scope.
  8550. *
  8551. * @return {('vec2'|'vec4')} The node type.
  8552. */
  8553. getNodeType() {
  8554. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  8555. else return 'vec2';
  8556. }
  8557. /**
  8558. * This method is overwritten since the node's update type depends on the selected scope.
  8559. *
  8560. * @return {NodeUpdateType} The update type.
  8561. */
  8562. getUpdateType() {
  8563. let updateType = NodeUpdateType.NONE;
  8564. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  8565. updateType = NodeUpdateType.RENDER;
  8566. }
  8567. this.updateType = updateType;
  8568. return updateType;
  8569. }
  8570. /**
  8571. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  8572. * from the current renderer.
  8573. *
  8574. * @param {NodeFrame} frame - A reference to the current node frame.
  8575. */
  8576. update( { renderer } ) {
  8577. const renderTarget = renderer.getRenderTarget();
  8578. if ( this.scope === ScreenNode.VIEWPORT ) {
  8579. if ( renderTarget !== null ) {
  8580. viewportVec.copy( renderTarget.viewport );
  8581. } else {
  8582. renderer.getViewport( viewportVec );
  8583. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  8584. }
  8585. } else {
  8586. if ( renderTarget !== null ) {
  8587. screenSizeVec.width = renderTarget.width;
  8588. screenSizeVec.height = renderTarget.height;
  8589. } else {
  8590. renderer.getDrawingBufferSize( screenSizeVec );
  8591. }
  8592. }
  8593. }
  8594. setup( /*builder*/ ) {
  8595. const scope = this.scope;
  8596. let output = null;
  8597. if ( scope === ScreenNode.SIZE ) {
  8598. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  8599. } else if ( scope === ScreenNode.VIEWPORT ) {
  8600. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  8601. } else {
  8602. output = vec2( screenCoordinate.div( screenSize ) );
  8603. }
  8604. return output;
  8605. }
  8606. generate( builder ) {
  8607. if ( this.scope === ScreenNode.COORDINATE ) {
  8608. let coord = builder.getFragCoord();
  8609. if ( builder.isFlipY() ) {
  8610. // follow webgpu standards
  8611. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  8612. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  8613. }
  8614. return coord;
  8615. }
  8616. return super.generate( builder );
  8617. }
  8618. }
  8619. ScreenNode.COORDINATE = 'coordinate';
  8620. ScreenNode.VIEWPORT = 'viewport';
  8621. ScreenNode.SIZE = 'size';
  8622. ScreenNode.UV = 'uv';
  8623. // Screen
  8624. /**
  8625. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  8626. *
  8627. * @tsl
  8628. * @type {ScreenNode<vec2>}
  8629. */
  8630. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  8631. /**
  8632. * TSL object that represents the screen resolution in physical pixel units.
  8633. *
  8634. * @tsl
  8635. * @type {ScreenNode<vec2>}
  8636. */
  8637. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  8638. /**
  8639. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  8640. *
  8641. * @tsl
  8642. * @type {ScreenNode<vec2>}
  8643. */
  8644. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  8645. // Viewport
  8646. /**
  8647. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  8648. *
  8649. * @tsl
  8650. * @type {ScreenNode<vec4>}
  8651. */
  8652. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  8653. /**
  8654. * TSL object that represents the viewport resolution in physical pixel units.
  8655. *
  8656. * @tsl
  8657. * @type {ScreenNode<vec2>}
  8658. */
  8659. const viewportSize = viewport.zw;
  8660. /**
  8661. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  8662. *
  8663. * @tsl
  8664. * @type {ScreenNode<vec2>}
  8665. */
  8666. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  8667. /**
  8668. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  8669. *
  8670. * @tsl
  8671. * @type {ScreenNode<vec2>}
  8672. */
  8673. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  8674. // Deprecated
  8675. /**
  8676. * @deprecated since r169. Use {@link screenSize} instead.
  8677. */
  8678. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  8679. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  8680. return screenSize;
  8681. }, 'vec2' ).once() )();
  8682. /**
  8683. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8684. *
  8685. * @tsl
  8686. * @type {UniformNode<uint>}
  8687. */
  8688. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8689. /**
  8690. * TSL object that represents the `near` value of the camera used for the current render.
  8691. *
  8692. * @tsl
  8693. * @type {UniformNode<float>}
  8694. */
  8695. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8696. /**
  8697. * TSL object that represents the `far` value of the camera used for the current render.
  8698. *
  8699. * @tsl
  8700. * @type {UniformNode<float>}
  8701. */
  8702. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8703. /**
  8704. * TSL object that represents the projection matrix of the camera used for the current render.
  8705. *
  8706. * @tsl
  8707. * @type {UniformNode<mat4>}
  8708. */
  8709. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8710. let cameraProjectionMatrix;
  8711. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8712. const matrices = [];
  8713. for ( const subCamera of camera.cameras ) {
  8714. matrices.push( subCamera.projectionMatrix );
  8715. }
  8716. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  8717. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  8718. } else {
  8719. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8720. }
  8721. return cameraProjectionMatrix;
  8722. } ).once() )();
  8723. /**
  8724. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8725. *
  8726. * @tsl
  8727. * @type {UniformNode<mat4>}
  8728. */
  8729. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8730. let cameraProjectionMatrixInverse;
  8731. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8732. const matrices = [];
  8733. for ( const subCamera of camera.cameras ) {
  8734. matrices.push( subCamera.projectionMatrixInverse );
  8735. }
  8736. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  8737. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  8738. } else {
  8739. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8740. }
  8741. return cameraProjectionMatrixInverse;
  8742. } ).once() )();
  8743. /**
  8744. * TSL object that represents the view matrix of the camera used for the current render.
  8745. *
  8746. * @tsl
  8747. * @type {UniformNode<mat4>}
  8748. */
  8749. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8750. let cameraViewMatrix;
  8751. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8752. const matrices = [];
  8753. for ( const subCamera of camera.cameras ) {
  8754. matrices.push( subCamera.matrixWorldInverse );
  8755. }
  8756. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  8757. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  8758. } else {
  8759. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8760. }
  8761. return cameraViewMatrix;
  8762. } ).once() )();
  8763. /**
  8764. * TSL object that represents the world matrix of the camera used for the current render.
  8765. *
  8766. * @tsl
  8767. * @type {UniformNode<mat4>}
  8768. */
  8769. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8770. let cameraWorldMatrix;
  8771. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8772. const matrices = [];
  8773. for ( const subCamera of camera.cameras ) {
  8774. matrices.push( subCamera.matrixWorld );
  8775. }
  8776. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  8777. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  8778. } else {
  8779. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8780. }
  8781. return cameraWorldMatrix;
  8782. } ).once() )();
  8783. /**
  8784. * TSL object that represents the normal matrix of the camera used for the current render.
  8785. *
  8786. * @tsl
  8787. * @type {UniformNode<mat3>}
  8788. */
  8789. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8790. let cameraNormalMatrix;
  8791. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8792. const matrices = [];
  8793. for ( const subCamera of camera.cameras ) {
  8794. matrices.push( subCamera.normalMatrix );
  8795. }
  8796. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  8797. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  8798. } else {
  8799. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8800. }
  8801. return cameraNormalMatrix;
  8802. } ).once() )();
  8803. /**
  8804. * TSL object that represents the position in world space of the camera used for the current render.
  8805. *
  8806. * @tsl
  8807. * @type {UniformNode<vec3>}
  8808. */
  8809. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8810. let cameraPosition;
  8811. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8812. const positions = [];
  8813. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  8814. positions.push( new Vector3() );
  8815. }
  8816. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  8817. const subCameras = camera.cameras;
  8818. const array = self.array;
  8819. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  8820. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  8821. }
  8822. } );
  8823. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  8824. } else {
  8825. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8826. }
  8827. return cameraPosition;
  8828. } ).once() )();
  8829. /**
  8830. * TSL object that represents the viewport of the camera used for the current render.
  8831. *
  8832. * @tsl
  8833. * @type {UniformNode<vec4>}
  8834. */
  8835. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8836. let cameraViewport;
  8837. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8838. const viewports = [];
  8839. for ( const subCamera of camera.cameras ) {
  8840. viewports.push( subCamera.viewport );
  8841. }
  8842. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  8843. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  8844. } else {
  8845. // Fallback for single camera
  8846. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  8847. }
  8848. return cameraViewport;
  8849. } ).once() )();
  8850. const _sphere = /*@__PURE__*/ new Sphere();
  8851. /**
  8852. * This node can be used to access transformation related metrics of 3D objects.
  8853. * Depending on the selected scope, a different metric is represented as a uniform
  8854. * in the shader. The following scopes are supported:
  8855. *
  8856. * - `POSITION`: The object's position in world space.
  8857. * - `VIEW_POSITION`: The object's position in view/camera space.
  8858. * - `DIRECTION`: The object's direction in world space.
  8859. * - `SCALE`: The object's scale in world space.
  8860. * - `WORLD_MATRIX`: The object's matrix in world space.
  8861. *
  8862. * @augments Node
  8863. */
  8864. class Object3DNode extends Node {
  8865. static get type() {
  8866. return 'Object3DNode';
  8867. }
  8868. /**
  8869. * Constructs a new object 3D node.
  8870. *
  8871. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8872. * @param {?Object3D} [object3d=null] - The 3D object.
  8873. */
  8874. constructor( scope, object3d = null ) {
  8875. super();
  8876. /**
  8877. * The node reports a different type of transformation depending on the scope.
  8878. *
  8879. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8880. */
  8881. this.scope = scope;
  8882. /**
  8883. * The 3D object.
  8884. *
  8885. * @type {?Object3D}
  8886. * @default null
  8887. */
  8888. this.object3d = object3d;
  8889. /**
  8890. * Overwritten since this type of node is updated per object.
  8891. *
  8892. * @type {string}
  8893. * @default 'object'
  8894. */
  8895. this.updateType = NodeUpdateType.OBJECT;
  8896. /**
  8897. * Holds the value of the node as a uniform.
  8898. *
  8899. * @type {UniformNode}
  8900. */
  8901. this.uniformNode = new UniformNode( null );
  8902. }
  8903. /**
  8904. * Overwritten since the node type is inferred from the scope.
  8905. *
  8906. * @return {string} The node type.
  8907. */
  8908. getNodeType() {
  8909. const scope = this.scope;
  8910. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8911. return 'mat4';
  8912. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8913. return 'vec3';
  8914. } else if ( scope === Object3DNode.RADIUS ) {
  8915. return 'float';
  8916. }
  8917. }
  8918. /**
  8919. * Updates the uniform value depending on the scope.
  8920. *
  8921. * @param {NodeFrame} frame - The current node frame.
  8922. */
  8923. update( frame ) {
  8924. const object = this.object3d;
  8925. const uniformNode = this.uniformNode;
  8926. const scope = this.scope;
  8927. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8928. uniformNode.value = object.matrixWorld;
  8929. } else if ( scope === Object3DNode.POSITION ) {
  8930. uniformNode.value = uniformNode.value || new Vector3();
  8931. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8932. } else if ( scope === Object3DNode.SCALE ) {
  8933. uniformNode.value = uniformNode.value || new Vector3();
  8934. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8935. } else if ( scope === Object3DNode.DIRECTION ) {
  8936. uniformNode.value = uniformNode.value || new Vector3();
  8937. object.getWorldDirection( uniformNode.value );
  8938. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8939. const camera = frame.camera;
  8940. uniformNode.value = uniformNode.value || new Vector3();
  8941. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8942. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8943. } else if ( scope === Object3DNode.RADIUS ) {
  8944. const geometry = frame.object.geometry;
  8945. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8946. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8947. uniformNode.value = _sphere.radius;
  8948. }
  8949. }
  8950. /**
  8951. * Generates the code snippet of the uniform node. The node type of the uniform
  8952. * node also depends on the selected scope.
  8953. *
  8954. * @param {NodeBuilder} builder - The current node builder.
  8955. * @return {string} The generated code snippet.
  8956. */
  8957. generate( builder ) {
  8958. const scope = this.scope;
  8959. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8960. this.uniformNode.nodeType = 'mat4';
  8961. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8962. this.uniformNode.nodeType = 'vec3';
  8963. } else if ( scope === Object3DNode.RADIUS ) {
  8964. this.uniformNode.nodeType = 'float';
  8965. }
  8966. return this.uniformNode.build( builder );
  8967. }
  8968. serialize( data ) {
  8969. super.serialize( data );
  8970. data.scope = this.scope;
  8971. }
  8972. deserialize( data ) {
  8973. super.deserialize( data );
  8974. this.scope = data.scope;
  8975. }
  8976. }
  8977. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8978. Object3DNode.POSITION = 'position';
  8979. Object3DNode.SCALE = 'scale';
  8980. Object3DNode.VIEW_POSITION = 'viewPosition';
  8981. Object3DNode.DIRECTION = 'direction';
  8982. Object3DNode.RADIUS = 'radius';
  8983. /**
  8984. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8985. *
  8986. * @tsl
  8987. * @function
  8988. * @param {?Object3D} [object3d] - The 3D object.
  8989. * @returns {Object3DNode<vec3>}
  8990. */
  8991. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8992. /**
  8993. * TSL function for creating an object 3D node that represents the object's world matrix.
  8994. *
  8995. * @tsl
  8996. * @function
  8997. * @param {?Object3D} [object3d] - The 3D object.
  8998. * @returns {Object3DNode<mat4>}
  8999. */
  9000. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9001. /**
  9002. * TSL function for creating an object 3D node that represents the object's position in world space.
  9003. *
  9004. * @tsl
  9005. * @function
  9006. * @param {?Object3D} [object3d] - The 3D object.
  9007. * @returns {Object3DNode<vec3>}
  9008. */
  9009. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9010. /**
  9011. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9012. *
  9013. * @tsl
  9014. * @function
  9015. * @param {?Object3D} [object3d] - The 3D object.
  9016. * @returns {Object3DNode<vec3>}
  9017. */
  9018. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9019. /**
  9020. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9021. *
  9022. * @tsl
  9023. * @function
  9024. * @param {?Object3D} [object3d] - The 3D object.
  9025. * @returns {Object3DNode<vec3>}
  9026. */
  9027. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9028. /**
  9029. * TSL function for creating an object 3D node that represents the object's radius.
  9030. *
  9031. * @tsl
  9032. * @function
  9033. * @param {?Object3D} [object3d] - The 3D object.
  9034. * @returns {Object3DNode<float>}
  9035. */
  9036. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9037. /**
  9038. * This type of node is a specialized version of `Object3DNode`
  9039. * with larger set of model related metrics. Unlike `Object3DNode`,
  9040. * `ModelNode` extracts the reference to the 3D object from the
  9041. * current node frame state.
  9042. *
  9043. * @augments Object3DNode
  9044. */
  9045. class ModelNode extends Object3DNode {
  9046. static get type() {
  9047. return 'ModelNode';
  9048. }
  9049. /**
  9050. * Constructs a new object model node.
  9051. *
  9052. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9053. */
  9054. constructor( scope ) {
  9055. super( scope );
  9056. }
  9057. /**
  9058. * Extracts the model reference from the frame state and then
  9059. * updates the uniform value depending on the scope.
  9060. *
  9061. * @param {NodeFrame} frame - The current node frame.
  9062. */
  9063. update( frame ) {
  9064. this.object3d = frame.object;
  9065. super.update( frame );
  9066. }
  9067. }
  9068. /**
  9069. * TSL object that represents the object's direction in world space.
  9070. *
  9071. * @tsl
  9072. * @type {ModelNode<vec3>}
  9073. */
  9074. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9075. /**
  9076. * TSL object that represents the object's world matrix.
  9077. *
  9078. * @tsl
  9079. * @type {ModelNode<mat4>}
  9080. */
  9081. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9082. /**
  9083. * TSL object that represents the object's position in world space.
  9084. *
  9085. * @tsl
  9086. * @type {ModelNode<vec3>}
  9087. */
  9088. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9089. /**
  9090. * TSL object that represents the object's scale in world space.
  9091. *
  9092. * @tsl
  9093. * @type {ModelNode<vec3>}
  9094. */
  9095. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9096. /**
  9097. * TSL object that represents the object's position in view/camera space.
  9098. *
  9099. * @tsl
  9100. * @type {ModelNode<vec3>}
  9101. */
  9102. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9103. /**
  9104. * TSL object that represents the object's radius.
  9105. *
  9106. * @tsl
  9107. * @type {ModelNode<float>}
  9108. */
  9109. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9110. /**
  9111. * TSL object that represents the object's normal matrix.
  9112. *
  9113. * @tsl
  9114. * @type {UniformNode<mat3>}
  9115. */
  9116. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9117. /**
  9118. * TSL object that represents the object's inverse world matrix.
  9119. *
  9120. * @tsl
  9121. * @type {UniformNode<mat4>}
  9122. */
  9123. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9124. /**
  9125. * TSL object that represents the object's model view matrix.
  9126. *
  9127. * @tsl
  9128. * @type {Node<mat4>}
  9129. */
  9130. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9131. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9132. } ).once() )().toVar( 'modelViewMatrix' );
  9133. // GPU Precision
  9134. /**
  9135. * TSL object that represents the object's model view in `mediump` precision.
  9136. *
  9137. * @tsl
  9138. * @type {Node<mat4>}
  9139. */
  9140. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9141. // CPU Precision
  9142. /**
  9143. * TSL object that represents the object's model view in `highp` precision
  9144. * which is achieved by computing the matrix in JS and not in the shader.
  9145. *
  9146. * @tsl
  9147. * @type {Node<mat4>}
  9148. */
  9149. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9150. builder.context.isHighPrecisionModelViewMatrix = true;
  9151. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9152. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9153. } );
  9154. } ).once() )().toVar( 'highpModelViewMatrix' );
  9155. /**
  9156. * TSL object that represents the object's model normal view in `highp` precision
  9157. * which is achieved by computing the matrix in JS and not in the shader.
  9158. *
  9159. * @tsl
  9160. * @type {Node<mat3>}
  9161. */
  9162. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9163. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9164. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9165. if ( isHighPrecisionModelViewMatrix !== true ) {
  9166. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9167. }
  9168. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9169. } );
  9170. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9171. /**
  9172. * TSL object that represents the position attribute of the current rendered object.
  9173. *
  9174. * @tsl
  9175. * @type {AttributeNode<vec3>}
  9176. */
  9177. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9178. /**
  9179. * TSL object that represents the vertex position in local space of the current rendered object.
  9180. *
  9181. * @tsl
  9182. * @type {AttributeNode<vec3>}
  9183. */
  9184. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9185. /**
  9186. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9187. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9188. *
  9189. * @tsl
  9190. * @type {AttributeNode<vec3>}
  9191. */
  9192. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9193. /**
  9194. * TSL object that represents the vertex position in world space of the current rendered object.
  9195. *
  9196. * @tsl
  9197. * @type {VaryingNode<vec3>}
  9198. */
  9199. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9200. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9201. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9202. /**
  9203. * TSL object that represents the position world direction of the current rendered object.
  9204. *
  9205. * @tsl
  9206. * @type {Node<vec3>}
  9207. */
  9208. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9209. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9210. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9211. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9212. /**
  9213. * TSL object that represents the vertex position in view space of the current rendered object.
  9214. *
  9215. * @tsl
  9216. * @type {VaryingNode<vec3>}
  9217. */
  9218. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9219. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9220. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9221. /**
  9222. * TSL object that represents the position view direction of the current rendered object.
  9223. *
  9224. * @tsl
  9225. * @type {VaryingNode<vec3>}
  9226. */
  9227. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  9228. /**
  9229. * This node can be used to evaluate whether a primitive is front or back facing.
  9230. *
  9231. * @augments Node
  9232. */
  9233. class FrontFacingNode extends Node {
  9234. static get type() {
  9235. return 'FrontFacingNode';
  9236. }
  9237. /**
  9238. * Constructs a new front facing node.
  9239. */
  9240. constructor() {
  9241. super( 'bool' );
  9242. /**
  9243. * This flag can be used for type testing.
  9244. *
  9245. * @type {boolean}
  9246. * @readonly
  9247. * @default true
  9248. */
  9249. this.isFrontFacingNode = true;
  9250. }
  9251. generate( builder ) {
  9252. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9253. //
  9254. const { renderer, material } = builder;
  9255. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  9256. if ( material.side === BackSide ) {
  9257. return 'false';
  9258. }
  9259. }
  9260. return builder.getFrontFacing();
  9261. }
  9262. }
  9263. /**
  9264. * TSL object that represents whether a primitive is front or back facing
  9265. *
  9266. * @tsl
  9267. * @type {FrontFacingNode<bool>}
  9268. */
  9269. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9270. /**
  9271. * TSL object that represents the front facing status as a number instead of a bool.
  9272. * `1` means front facing, `-1` means back facing.
  9273. *
  9274. * @tsl
  9275. * @type {Node<float>}
  9276. */
  9277. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9278. /**
  9279. * Converts a direction vector to a face direction vector based on the material's side.
  9280. *
  9281. * If the material is set to `BackSide`, the direction is inverted.
  9282. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9283. *
  9284. * @tsl
  9285. * @param {Node<vec3>} direction - The direction vector to convert.
  9286. * @returns {Node<vec3>} The converted direction vector.
  9287. */
  9288. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9289. const side = material.side;
  9290. if ( side === BackSide ) {
  9291. direction = direction.mul( -1 );
  9292. } else if ( side === DoubleSide ) {
  9293. direction = direction.mul( faceDirection );
  9294. }
  9295. return direction;
  9296. } );
  9297. /**
  9298. * TSL object that represents the normal attribute of the current rendered object in local space.
  9299. *
  9300. * @tsl
  9301. * @type {Node<vec3>}
  9302. */
  9303. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9304. /**
  9305. * TSL object that represents the vertex normal of the current rendered object in local space.
  9306. *
  9307. * @tsl
  9308. * @type {Node<vec3>}
  9309. */
  9310. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9311. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9312. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  9313. return vec3( 0, 1, 0 );
  9314. }
  9315. return normalGeometry;
  9316. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9317. /**
  9318. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9319. *
  9320. * @tsl
  9321. * @type {Node<vec3>}
  9322. */
  9323. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9324. /**
  9325. * TSL object that represents the vertex normal of the current rendered object in view space.
  9326. *
  9327. * @tsl
  9328. * @type {Node<vec3>}
  9329. */
  9330. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9331. let node;
  9332. if ( builder.material.flatShading === true ) {
  9333. node = normalFlat;
  9334. } else {
  9335. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9336. }
  9337. return node;
  9338. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9339. /**
  9340. * TSL object that represents the vertex normal of the current rendered object in world space.
  9341. *
  9342. * @tsl
  9343. * @type {Node<vec3>}
  9344. */
  9345. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9346. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9347. if ( builder.material.flatShading !== true ) {
  9348. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9349. }
  9350. return normal.normalize().toVar( 'normalWorldGeometry' );
  9351. }, 'vec3' ).once() )();
  9352. /**
  9353. * TSL object that represents the vertex normal of the current rendered object in view space.
  9354. *
  9355. * @tsl
  9356. * @type {Node<vec3>}
  9357. */
  9358. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9359. let node;
  9360. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9361. node = normalViewGeometry;
  9362. if ( material.flatShading !== true ) {
  9363. node = directionToFaceDirection( node );
  9364. }
  9365. } else {
  9366. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9367. node = context.setupNormal().context( { getUV: null } );
  9368. }
  9369. return node;
  9370. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9371. /**
  9372. * TSL object that represents the vertex normal of the current rendered object in world space.
  9373. *
  9374. * @tsl
  9375. * @type {Node<vec3>}
  9376. */
  9377. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9378. /**
  9379. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9380. *
  9381. * @tsl
  9382. * @type {Node<vec3>}
  9383. */
  9384. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9385. let node;
  9386. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9387. node = normalView;
  9388. } else {
  9389. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9390. node = context.setupClearcoatNormal().context( { getUV: null } );
  9391. }
  9392. return node;
  9393. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9394. /**
  9395. * Transforms the normal with the given matrix.
  9396. *
  9397. * @tsl
  9398. * @function
  9399. * @param {Node<vec3>} normal - The normal.
  9400. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9401. * @return {Node<vec3>} The transformed normal.
  9402. */
  9403. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9404. const m = mat3( matrix );
  9405. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9406. return m.mul( transformedNormal ).xyz;
  9407. } );
  9408. /**
  9409. * Transforms the given normal from local to view space.
  9410. *
  9411. * @tsl
  9412. * @function
  9413. * @param {Node<vec3>} normal - The normal.
  9414. * @param {NodeBuilder} builder - The current node builder.
  9415. * @return {Node<vec3>} The transformed normal.
  9416. */
  9417. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9418. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9419. if ( modelNormalViewMatrix !== null ) {
  9420. return modelNormalViewMatrix.transformDirection( normal );
  9421. }
  9422. //
  9423. const transformedNormal = modelNormalMatrix.mul( normal );
  9424. return cameraViewMatrix.transformDirection( transformedNormal );
  9425. } );
  9426. // Deprecated
  9427. /**
  9428. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9429. *
  9430. * @tsl
  9431. * @type {Node<vec3>}
  9432. * @deprecated since r178. Use `normalView` instead.
  9433. */
  9434. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9435. console.warn( 'THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9436. return normalView;
  9437. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9438. /**
  9439. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9440. *
  9441. * @tsl
  9442. * @type {Node<vec3>}
  9443. * @deprecated since r178. Use `normalWorld` instead.
  9444. */
  9445. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9446. console.warn( 'THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9447. return normalWorld;
  9448. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9449. /**
  9450. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9451. *
  9452. * @tsl
  9453. * @type {Node<vec3>}
  9454. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9455. */
  9456. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9457. console.warn( 'THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9458. return clearcoatNormalView;
  9459. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9460. const _e1$1 = /*@__PURE__*/ new Euler();
  9461. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9462. /**
  9463. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9464. *
  9465. * @tsl
  9466. * @type {UniformNode<float>}
  9467. */
  9468. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9469. /**
  9470. * TSL object that represents the intensity of environment maps of PBR materials.
  9471. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9472. *
  9473. * @tsl
  9474. * @type {Node<float>}
  9475. */
  9476. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9477. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9478. } );
  9479. /**
  9480. * TSL object that represents the rotation of environment maps.
  9481. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9482. * rotation of `scene.environment` instead.
  9483. *
  9484. * @tsl
  9485. * @type {Node<mat4>}
  9486. */
  9487. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9488. return frame.material;
  9489. } ).onObjectUpdate( function ( { material, scene } ) {
  9490. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9491. if ( rotation ) {
  9492. _e1$1.copy( rotation );
  9493. _m1$1.makeRotationFromEuler( _e1$1 );
  9494. } else {
  9495. _m1$1.identity();
  9496. }
  9497. return _m1$1;
  9498. } );
  9499. /**
  9500. * The reflect vector in view space.
  9501. *
  9502. * @tsl
  9503. * @type {Node<vec3>}
  9504. */
  9505. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9506. /**
  9507. * The refract vector in view space.
  9508. *
  9509. * @tsl
  9510. * @type {Node<vec3>}
  9511. */
  9512. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  9513. /**
  9514. * Used for sampling cube maps when using cube reflection mapping.
  9515. *
  9516. * @tsl
  9517. * @type {Node<vec3>}
  9518. */
  9519. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9520. /**
  9521. * Used for sampling cube maps when using cube refraction mapping.
  9522. *
  9523. * @tsl
  9524. * @type {Node<vec3>}
  9525. */
  9526. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9527. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  9528. /**
  9529. * This type of uniform node represents a cube texture.
  9530. *
  9531. * @augments TextureNode
  9532. */
  9533. class CubeTextureNode extends TextureNode {
  9534. static get type() {
  9535. return 'CubeTextureNode';
  9536. }
  9537. /**
  9538. * Constructs a new cube texture node.
  9539. *
  9540. * @param {CubeTexture} value - The cube texture.
  9541. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9542. * @param {?Node<int>} [levelNode=null] - The level node.
  9543. * @param {?Node<float>} [biasNode=null] - The bias node.
  9544. */
  9545. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  9546. super( value, uvNode, levelNode, biasNode );
  9547. /**
  9548. * This flag can be used for type testing.
  9549. *
  9550. * @type {boolean}
  9551. * @readonly
  9552. * @default true
  9553. */
  9554. this.isCubeTextureNode = true;
  9555. }
  9556. /**
  9557. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  9558. *
  9559. * @param {NodeBuilder} builder - The current node builder.
  9560. * @return {string} The input type.
  9561. */
  9562. getInputType( /*builder*/ ) {
  9563. return 'cubeTexture';
  9564. }
  9565. /**
  9566. * Returns a default uvs based on the mapping type of the cube texture.
  9567. *
  9568. * @return {Node<vec3>} The default uv attribute.
  9569. */
  9570. getDefaultUV() {
  9571. const texture = this.value;
  9572. if ( texture.mapping === CubeReflectionMapping ) {
  9573. return reflectVector;
  9574. } else if ( texture.mapping === CubeRefractionMapping ) {
  9575. return refractVector;
  9576. } else {
  9577. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  9578. return vec3( 0, 0, 0 );
  9579. }
  9580. }
  9581. /**
  9582. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  9583. * for cube textures. The uv transformation matrix is not applied to cube textures.
  9584. *
  9585. * @param {boolean} value - The update toggle.
  9586. */
  9587. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  9588. /**
  9589. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  9590. * to modify the uv node for correct sampling.
  9591. *
  9592. * @param {NodeBuilder} builder - The current node builder.
  9593. * @param {Node} uvNode - The uv node to setup.
  9594. * @return {Node} The updated uv node.
  9595. */
  9596. setupUV( builder, uvNode ) {
  9597. const texture = this.value;
  9598. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  9599. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9600. }
  9601. return materialEnvRotation.mul( uvNode );
  9602. }
  9603. /**
  9604. * Generates the uv code snippet.
  9605. *
  9606. * @param {NodeBuilder} builder - The current node builder.
  9607. * @param {Node} cubeUV - The uv node to generate code for.
  9608. * @return {string} The generated code snippet.
  9609. */
  9610. generateUV( builder, cubeUV ) {
  9611. return cubeUV.build( builder, 'vec3' );
  9612. }
  9613. }
  9614. /**
  9615. * TSL function for creating a cube texture node.
  9616. *
  9617. * @tsl
  9618. * @function
  9619. * @param {CubeTexture} value - The cube texture.
  9620. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9621. * @param {?Node<int>} [levelNode=null] - The level node.
  9622. * @param {?Node<float>} [biasNode=null] - The bias node.
  9623. * @returns {CubeTextureNode}
  9624. */
  9625. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  9626. /**
  9627. * TSL function for creating a cube texture uniform node.
  9628. *
  9629. * @tsl
  9630. * @function
  9631. * @param {?CubeTexture|CubeTextureNode} [value=EmptyTexture] - The cube texture.
  9632. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9633. * @param {?Node<int>} [levelNode=null] - The level node.
  9634. * @param {?Node<float>} [biasNode=null] - The bias node.
  9635. * @returns {CubeTextureNode}
  9636. */
  9637. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  9638. let textureNode;
  9639. if ( value && value.isCubeTextureNode === true ) {
  9640. textureNode = nodeObject( value.clone() );
  9641. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  9642. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9643. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9644. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9645. } else {
  9646. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  9647. }
  9648. return textureNode;
  9649. };
  9650. /**
  9651. * TSL function for creating a uniform cube texture node.
  9652. *
  9653. * @tsl
  9654. * @function
  9655. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  9656. * @returns {CubeTextureNode}
  9657. */
  9658. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  9659. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  9660. /**
  9661. * This class is only relevant if the referenced property is array-like.
  9662. * In this case, `ReferenceElementNode` allows to refer to a specific
  9663. * element inside the data structure via an index.
  9664. *
  9665. * @augments ArrayElementNode
  9666. */
  9667. class ReferenceElementNode extends ArrayElementNode {
  9668. static get type() {
  9669. return 'ReferenceElementNode';
  9670. }
  9671. /**
  9672. * Constructs a new reference element node.
  9673. *
  9674. * @param {?ReferenceNode} referenceNode - The reference node.
  9675. * @param {Node} indexNode - The index node that defines the element access.
  9676. */
  9677. constructor( referenceNode, indexNode ) {
  9678. super( referenceNode, indexNode );
  9679. /**
  9680. * Similar to {@link ReferenceNode#reference}, an additional
  9681. * property references to the current node.
  9682. *
  9683. * @type {?ReferenceNode}
  9684. * @default null
  9685. */
  9686. this.referenceNode = referenceNode;
  9687. /**
  9688. * This flag can be used for type testing.
  9689. *
  9690. * @type {boolean}
  9691. * @readonly
  9692. * @default true
  9693. */
  9694. this.isReferenceElementNode = true;
  9695. }
  9696. /**
  9697. * This method is overwritten since the node type is inferred from
  9698. * the uniform type of the reference node.
  9699. *
  9700. * @return {string} The node type.
  9701. */
  9702. getNodeType() {
  9703. return this.referenceNode.uniformType;
  9704. }
  9705. generate( builder ) {
  9706. const snippet = super.generate( builder );
  9707. const arrayType = this.referenceNode.getNodeType();
  9708. const elementType = this.getNodeType();
  9709. return builder.format( snippet, arrayType, elementType );
  9710. }
  9711. }
  9712. /**
  9713. * This type of node establishes a reference to a property of another object.
  9714. * In this way, the value of the node is automatically linked to the value of
  9715. * referenced object. Reference nodes internally represent the linked value
  9716. * as a uniform.
  9717. *
  9718. * @augments Node
  9719. */
  9720. class ReferenceNode extends Node {
  9721. static get type() {
  9722. return 'ReferenceNode';
  9723. }
  9724. /**
  9725. * Constructs a new reference node.
  9726. *
  9727. * @param {string} property - The name of the property the node refers to.
  9728. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  9729. * @param {?Object} [object=null] - The object the property belongs to.
  9730. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  9731. */
  9732. constructor( property, uniformType, object = null, count = null ) {
  9733. super();
  9734. /**
  9735. * The name of the property the node refers to.
  9736. *
  9737. * @type {string}
  9738. */
  9739. this.property = property;
  9740. /**
  9741. * The uniform type that should be used to represent the property value.
  9742. *
  9743. * @type {string}
  9744. */
  9745. this.uniformType = uniformType;
  9746. /**
  9747. * The object the property belongs to.
  9748. *
  9749. * @type {?Object}
  9750. * @default null
  9751. */
  9752. this.object = object;
  9753. /**
  9754. * When the linked property is an array, this parameter defines its length.
  9755. *
  9756. * @type {?number}
  9757. * @default null
  9758. */
  9759. this.count = count;
  9760. /**
  9761. * The property name might have dots so nested properties can be referred.
  9762. * The hierarchy of the names is stored inside this array.
  9763. *
  9764. * @type {Array<string>}
  9765. */
  9766. this.properties = property.split( '.' );
  9767. /**
  9768. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  9769. * since the final reference might be updated from calling code.
  9770. *
  9771. * @type {?Object}
  9772. * @default null
  9773. */
  9774. this.reference = object;
  9775. /**
  9776. * The uniform node that holds the value of the reference node.
  9777. *
  9778. * @type {UniformNode}
  9779. * @default null
  9780. */
  9781. this.node = null;
  9782. /**
  9783. * The uniform group of the internal uniform.
  9784. *
  9785. * @type {UniformGroupNode}
  9786. * @default null
  9787. */
  9788. this.group = null;
  9789. /**
  9790. * An optional label of the internal uniform node.
  9791. *
  9792. * @type {?string}
  9793. * @default null
  9794. */
  9795. this.name = null;
  9796. /**
  9797. * Overwritten since reference nodes are updated per object.
  9798. *
  9799. * @type {string}
  9800. * @default 'object'
  9801. */
  9802. this.updateType = NodeUpdateType.OBJECT;
  9803. }
  9804. /**
  9805. * When the referred property is array-like, this method can be used
  9806. * to access elements via an index node.
  9807. *
  9808. * @param {IndexNode} indexNode - indexNode.
  9809. * @return {ReferenceElementNode} A reference to an element.
  9810. */
  9811. element( indexNode ) {
  9812. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9813. }
  9814. /**
  9815. * Sets the uniform group for this reference node.
  9816. *
  9817. * @param {UniformGroupNode} group - The uniform group to set.
  9818. * @return {ReferenceNode} A reference to this node.
  9819. */
  9820. setGroup( group ) {
  9821. this.group = group;
  9822. return this;
  9823. }
  9824. /**
  9825. * Sets the name for the internal uniform.
  9826. *
  9827. * @param {string} name - The label to set.
  9828. * @return {ReferenceNode} A reference to this node.
  9829. */
  9830. setName( name ) {
  9831. this.name = name;
  9832. return this;
  9833. }
  9834. /**
  9835. * Sets the label for the internal uniform.
  9836. *
  9837. * @deprecated
  9838. * @param {string} name - The label to set.
  9839. * @return {ReferenceNode} A reference to this node.
  9840. */
  9841. label( name ) {
  9842. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  9843. return this.setName( name );
  9844. }
  9845. /**
  9846. * Sets the node type which automatically defines the internal
  9847. * uniform type.
  9848. *
  9849. * @param {string} uniformType - The type to set.
  9850. */
  9851. setNodeType( uniformType ) {
  9852. let node = null;
  9853. if ( this.count !== null ) {
  9854. node = buffer( null, uniformType, this.count );
  9855. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9856. node = uniformArray( null, uniformType );
  9857. } else if ( uniformType === 'texture' ) {
  9858. node = texture( null );
  9859. } else if ( uniformType === 'cubeTexture' ) {
  9860. node = cubeTexture( null );
  9861. } else {
  9862. node = uniform( null, uniformType );
  9863. }
  9864. if ( this.group !== null ) {
  9865. node.setGroup( this.group );
  9866. }
  9867. if ( this.name !== null ) node.setName( this.name );
  9868. this.node = node.getSelf();
  9869. }
  9870. /**
  9871. * This method is overwritten since the node type is inferred from
  9872. * the type of the reference node.
  9873. *
  9874. * @param {NodeBuilder} builder - The current node builder.
  9875. * @return {string} The node type.
  9876. */
  9877. getNodeType( builder ) {
  9878. if ( this.node === null ) {
  9879. this.updateReference( builder );
  9880. this.updateValue();
  9881. }
  9882. return this.node.getNodeType( builder );
  9883. }
  9884. /**
  9885. * Returns the property value from the given referred object.
  9886. *
  9887. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  9888. * @return {any} The value.
  9889. */
  9890. getValueFromReference( object = this.reference ) {
  9891. const { properties } = this;
  9892. let value = object[ properties[ 0 ] ];
  9893. for ( let i = 1; i < properties.length; i ++ ) {
  9894. value = value[ properties[ i ] ];
  9895. }
  9896. return value;
  9897. }
  9898. /**
  9899. * Allows to update the reference based on the given state. The state is only
  9900. * evaluated {@link ReferenceNode#object} is not set.
  9901. *
  9902. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9903. * @return {Object} The updated reference.
  9904. */
  9905. updateReference( state ) {
  9906. this.reference = this.object !== null ? this.object : state.object;
  9907. return this.reference;
  9908. }
  9909. /**
  9910. * The output of the reference node is the internal uniform node.
  9911. *
  9912. * @param {NodeBuilder} builder - The current node builder.
  9913. * @return {UniformNode} The output node.
  9914. */
  9915. setup( /* builder */ ) {
  9916. this.updateValue();
  9917. return this.node;
  9918. }
  9919. /**
  9920. * Overwritten to update the internal uniform value.
  9921. *
  9922. * @param {NodeFrame} frame - A reference to the current node frame.
  9923. */
  9924. update( /*frame*/ ) {
  9925. this.updateValue();
  9926. }
  9927. /**
  9928. * Retrieves the value from the referred object property and uses it
  9929. * to updated the internal uniform.
  9930. */
  9931. updateValue() {
  9932. if ( this.node === null ) this.setNodeType( this.uniformType );
  9933. const value = this.getValueFromReference();
  9934. if ( Array.isArray( value ) ) {
  9935. this.node.array = value;
  9936. } else {
  9937. this.node.value = value;
  9938. }
  9939. }
  9940. }
  9941. /**
  9942. * TSL function for creating a reference node.
  9943. *
  9944. * @tsl
  9945. * @function
  9946. * @param {string} name - The name of the property the node refers to.
  9947. * @param {string} type - The uniform type that should be used to represent the property value.
  9948. * @param {?Object} [object] - The object the property belongs to.
  9949. * @returns {ReferenceNode}
  9950. */
  9951. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9952. /**
  9953. * TSL function for creating a reference node. Use this function if you want need a reference
  9954. * to an array-like property that should be represented as a uniform buffer.
  9955. *
  9956. * @tsl
  9957. * @function
  9958. * @param {string} name - The name of the property the node refers to.
  9959. * @param {string} type - The uniform type that should be used to represent the property value.
  9960. * @param {number} count - The number of value inside the array-like object.
  9961. * @param {Object} object - An array-like object the property belongs to.
  9962. * @returns {ReferenceNode}
  9963. */
  9964. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9965. /**
  9966. * This node is a special type of reference node which is intended
  9967. * for linking material properties with node values.
  9968. * ```js
  9969. * const opacityNode = materialReference( 'opacity', 'float', material );
  9970. * ```
  9971. * When changing `material.opacity`, the node value of `opacityNode` will
  9972. * automatically be updated.
  9973. *
  9974. * @augments ReferenceNode
  9975. */
  9976. class MaterialReferenceNode extends ReferenceNode {
  9977. static get type() {
  9978. return 'MaterialReferenceNode';
  9979. }
  9980. /**
  9981. * Constructs a new material reference node.
  9982. *
  9983. * @param {string} property - The name of the property the node refers to.
  9984. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9985. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9986. * the node refers to the material of the current rendered object.
  9987. */
  9988. constructor( property, inputType, material = null ) {
  9989. super( property, inputType, material );
  9990. /**
  9991. * The material the property belongs to. When no material is set,
  9992. * the node refers to the material of the current rendered object.
  9993. *
  9994. * @type {?Material}
  9995. * @default null
  9996. */
  9997. this.material = material;
  9998. /**
  9999. * This flag can be used for type testing.
  10000. *
  10001. * @type {boolean}
  10002. * @readonly
  10003. * @default true
  10004. */
  10005. this.isMaterialReferenceNode = true;
  10006. }
  10007. /**
  10008. * Updates the reference based on the given state. The state is only evaluated
  10009. * {@link MaterialReferenceNode#material} is not set.
  10010. *
  10011. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10012. * @return {Object} The updated reference.
  10013. */
  10014. updateReference( state ) {
  10015. this.reference = this.material !== null ? this.material : state.material;
  10016. return this.reference;
  10017. }
  10018. }
  10019. /**
  10020. * TSL function for creating a material reference node.
  10021. *
  10022. * @tsl
  10023. * @function
  10024. * @param {string} name - The name of the property the node refers to.
  10025. * @param {string} type - The uniform type that should be used to represent the property value.
  10026. * @param {?Material} [material=null] - The material the property belongs to.
  10027. * When no material is set, the node refers to the material of the current rendered object.
  10028. * @returns {MaterialReferenceNode}
  10029. */
  10030. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10031. // Normal Mapping Without Precomputed Tangents
  10032. // http://www.thetenthplanet.de/archives/1180
  10033. const uv = uv$1();
  10034. const q0 = positionView.dFdx();
  10035. const q1 = positionView.dFdy();
  10036. const st0 = uv.dFdx();
  10037. const st1 = uv.dFdy();
  10038. const N = normalView;
  10039. const q1perp = q1.cross( N );
  10040. const q0perp = N.cross( q0 );
  10041. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10042. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10043. const det = T.dot( T ).max( B.dot( B ) );
  10044. const scale = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10045. /**
  10046. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10047. * Useful for normal mapping without precomputed tangents.
  10048. *
  10049. * Reference: http://www.thetenthplanet.de/archives/1180
  10050. *
  10051. * @tsl
  10052. * @type {Node<vec3>}
  10053. */
  10054. const tangentViewFrame = /*@__PURE__*/ T.mul( scale ).toVar( 'tangentViewFrame' );
  10055. /**
  10056. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10057. * Complements the tangentViewFrame for constructing the tangent space basis.
  10058. *
  10059. * Reference: http://www.thetenthplanet.de/archives/1180
  10060. *
  10061. * @tsl
  10062. * @type {Node<vec3>}
  10063. */
  10064. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale ).toVar( 'bitangentViewFrame' );
  10065. /**
  10066. * TSL object that represents the tangent attribute of the current rendered object.
  10067. *
  10068. * @tsl
  10069. * @type {Node<vec4>}
  10070. */
  10071. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10072. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10073. builder.geometry.computeTangents();
  10074. }
  10075. return attribute( 'tangent', 'vec4' );
  10076. } )();
  10077. /**
  10078. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10079. *
  10080. * @tsl
  10081. * @type {Node<vec3>}
  10082. */
  10083. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10084. /**
  10085. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10086. *
  10087. * @tsl
  10088. * @type {Node<vec3>}
  10089. */
  10090. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10091. let node;
  10092. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10093. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10094. } else {
  10095. node = tangentViewFrame;
  10096. }
  10097. if ( material.flatShading !== true ) {
  10098. node = directionToFaceDirection( node );
  10099. }
  10100. return node;
  10101. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10102. /**
  10103. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10104. *
  10105. * @tsl
  10106. * @type {Node<vec3>}
  10107. */
  10108. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10109. /**
  10110. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10111. *
  10112. * @tsl
  10113. * @private
  10114. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10115. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10116. * @returns {Node<vec3>} The bitangent node.
  10117. */
  10118. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10119. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10120. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10121. bitangent = bitangent.toVarying( varyingName );
  10122. }
  10123. return bitangent;
  10124. } ).once( [ 'NORMAL' ] );
  10125. /**
  10126. * TSL object that represents the bitangent attribute of the current rendered object.
  10127. *
  10128. * @tsl
  10129. * @type {Node<vec3>}
  10130. */
  10131. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10132. /**
  10133. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10134. *
  10135. * @tsl
  10136. * @type {Node<vec3>}
  10137. */
  10138. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10139. /**
  10140. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10141. *
  10142. * @tsl
  10143. * @type {Node<vec3>}
  10144. */
  10145. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10146. let node;
  10147. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10148. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10149. } else {
  10150. node = bitangentViewFrame;
  10151. }
  10152. if ( material.flatShading !== true ) {
  10153. node = directionToFaceDirection( node );
  10154. }
  10155. return node;
  10156. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10157. /**
  10158. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10159. *
  10160. * @tsl
  10161. * @type {Node<vec3>}
  10162. */
  10163. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10164. /**
  10165. * TSL object that represents the TBN matrix in view space.
  10166. *
  10167. * @tsl
  10168. * @type {Node<mat3>}
  10169. */
  10170. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10171. /**
  10172. * TSL object that represents the parallax direction.
  10173. *
  10174. * @tsl
  10175. * @type {Node<mat3>}
  10176. */
  10177. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10178. /**
  10179. * TSL function for computing parallax uv coordinates.
  10180. *
  10181. * @tsl
  10182. * @function
  10183. * @param {Node<vec2>} uv - A uv node.
  10184. * @param {Node<vec2>} scale - A scale node.
  10185. * @returns {Node<vec2>} Parallax uv coordinates.
  10186. */
  10187. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10188. /**
  10189. * TSL function for computing bent normals.
  10190. *
  10191. * @tsl
  10192. * @function
  10193. * @returns {Node<vec3>} Bent normals.
  10194. */
  10195. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10196. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10197. let bentNormal = anisotropyB.cross( positionViewDirection );
  10198. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10199. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10200. return bentNormal;
  10201. } ).once() )();
  10202. /**
  10203. * This class can be used for applying normals maps to materials.
  10204. *
  10205. * ```js
  10206. * material.normalNode = normalMap( texture( normalTex ) );
  10207. * ```
  10208. *
  10209. * @augments TempNode
  10210. */
  10211. class NormalMapNode extends TempNode {
  10212. static get type() {
  10213. return 'NormalMapNode';
  10214. }
  10215. /**
  10216. * Constructs a new normal map node.
  10217. *
  10218. * @param {Node<vec3>} node - Represents the normal map data.
  10219. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10220. */
  10221. constructor( node, scaleNode = null ) {
  10222. super( 'vec3' );
  10223. /**
  10224. * Represents the normal map data.
  10225. *
  10226. * @type {Node<vec3>}
  10227. */
  10228. this.node = node;
  10229. /**
  10230. * Controls the intensity of the effect.
  10231. *
  10232. * @type {?Node<vec2>}
  10233. * @default null
  10234. */
  10235. this.scaleNode = scaleNode;
  10236. /**
  10237. * The normal map type.
  10238. *
  10239. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10240. * @default TangentSpaceNormalMap
  10241. */
  10242. this.normalMapType = TangentSpaceNormalMap;
  10243. }
  10244. setup( { material } ) {
  10245. const { normalMapType, scaleNode } = this;
  10246. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10247. if ( scaleNode !== null ) {
  10248. let scale = scaleNode;
  10249. if ( material.flatShading === true ) {
  10250. scale = directionToFaceDirection( scale );
  10251. }
  10252. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10253. }
  10254. let output = null;
  10255. if ( normalMapType === ObjectSpaceNormalMap ) {
  10256. output = transformNormalToView( normalMap );
  10257. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10258. output = TBNViewMatrix.mul( normalMap ).normalize();
  10259. } else {
  10260. console.error( `THREE.NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10261. output = normalView; // Fallback to default normal view
  10262. }
  10263. return output;
  10264. }
  10265. }
  10266. /**
  10267. * TSL function for creating a normal map node.
  10268. *
  10269. * @tsl
  10270. * @function
  10271. * @param {Node<vec3>} node - Represents the normal map data.
  10272. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10273. * @returns {NormalMapNode}
  10274. */
  10275. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10276. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10277. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10278. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10279. // It's used to preserve the same TextureNode instance
  10280. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10281. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10282. return vec2(
  10283. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10284. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10285. ).mul( bumpScale );
  10286. } );
  10287. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10288. const perturbNormalArb = Fn( ( inputs ) => {
  10289. const { surf_pos, surf_norm, dHdxy } = inputs;
  10290. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10291. const vSigmaX = surf_pos.dFdx().normalize();
  10292. const vSigmaY = surf_pos.dFdy().normalize();
  10293. const vN = surf_norm; // normalized
  10294. const R1 = vSigmaY.cross( vN );
  10295. const R2 = vN.cross( vSigmaX );
  10296. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10297. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10298. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10299. } );
  10300. /**
  10301. * This class can be used for applying bump maps to materials.
  10302. *
  10303. * ```js
  10304. * material.normalNode = bumpMap( texture( bumpTex ) );
  10305. * ```
  10306. *
  10307. * @augments TempNode
  10308. */
  10309. class BumpMapNode extends TempNode {
  10310. static get type() {
  10311. return 'BumpMapNode';
  10312. }
  10313. /**
  10314. * Constructs a new bump map node.
  10315. *
  10316. * @param {Node<float>} textureNode - Represents the bump map data.
  10317. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10318. */
  10319. constructor( textureNode, scaleNode = null ) {
  10320. super( 'vec3' );
  10321. /**
  10322. * Represents the bump map data.
  10323. *
  10324. * @type {Node<float>}
  10325. */
  10326. this.textureNode = textureNode;
  10327. /**
  10328. * Controls the intensity of the bump effect.
  10329. *
  10330. * @type {?Node<float>}
  10331. * @default null
  10332. */
  10333. this.scaleNode = scaleNode;
  10334. }
  10335. setup() {
  10336. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10337. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10338. return perturbNormalArb( {
  10339. surf_pos: positionView,
  10340. surf_norm: normalView,
  10341. dHdxy
  10342. } );
  10343. }
  10344. }
  10345. /**
  10346. * TSL function for creating a bump map node.
  10347. *
  10348. * @tsl
  10349. * @function
  10350. * @param {Node<float>} textureNode - Represents the bump map data.
  10351. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10352. * @returns {BumpMapNode}
  10353. */
  10354. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10355. const _propertyCache = new Map();
  10356. /**
  10357. * This class should simplify the node access to material properties.
  10358. * It internal uses reference nodes to make sure changes to material
  10359. * properties are automatically reflected to predefined TSL objects
  10360. * like e.g. `materialColor`.
  10361. *
  10362. * @augments Node
  10363. */
  10364. class MaterialNode extends Node {
  10365. static get type() {
  10366. return 'MaterialNode';
  10367. }
  10368. /**
  10369. * Constructs a new material node.
  10370. *
  10371. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10372. */
  10373. constructor( scope ) {
  10374. super();
  10375. /**
  10376. * The scope defines what material property is referred by the node.
  10377. *
  10378. * @type {string}
  10379. */
  10380. this.scope = scope;
  10381. }
  10382. /**
  10383. * Returns a cached reference node for the given property and type.
  10384. *
  10385. * @param {string} property - The name of the material property.
  10386. * @param {string} type - The uniform type of the property.
  10387. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10388. */
  10389. getCache( property, type ) {
  10390. let node = _propertyCache.get( property );
  10391. if ( node === undefined ) {
  10392. node = materialReference( property, type );
  10393. _propertyCache.set( property, node );
  10394. }
  10395. return node;
  10396. }
  10397. /**
  10398. * Returns a float-typed material reference node for the given property name.
  10399. *
  10400. * @param {string} property - The name of the material property.
  10401. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10402. */
  10403. getFloat( property ) {
  10404. return this.getCache( property, 'float' );
  10405. }
  10406. /**
  10407. * Returns a color-typed material reference node for the given property name.
  10408. *
  10409. * @param {string} property - The name of the material property.
  10410. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10411. */
  10412. getColor( property ) {
  10413. return this.getCache( property, 'color' );
  10414. }
  10415. /**
  10416. * Returns a texture-typed material reference node for the given property name.
  10417. *
  10418. * @param {string} property - The name of the material property.
  10419. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10420. */
  10421. getTexture( property ) {
  10422. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10423. }
  10424. /**
  10425. * The node setup is done depending on the selected scope. Multiple material properties
  10426. * might be grouped into a single node composition if they logically belong together.
  10427. *
  10428. * @param {NodeBuilder} builder - The current node builder.
  10429. * @return {Node} The node representing the selected scope.
  10430. */
  10431. setup( builder ) {
  10432. const material = builder.context.material;
  10433. const scope = this.scope;
  10434. let node = null;
  10435. if ( scope === MaterialNode.COLOR ) {
  10436. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10437. if ( material.map && material.map.isTexture === true ) {
  10438. node = colorNode.mul( this.getTexture( 'map' ) );
  10439. } else {
  10440. node = colorNode;
  10441. }
  10442. } else if ( scope === MaterialNode.OPACITY ) {
  10443. const opacityNode = this.getFloat( scope );
  10444. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10445. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10446. } else {
  10447. node = opacityNode;
  10448. }
  10449. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10450. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10451. node = this.getTexture( 'specular' ).r;
  10452. } else {
  10453. node = float( 1 );
  10454. }
  10455. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10456. const specularIntensityNode = this.getFloat( scope );
  10457. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10458. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10459. } else {
  10460. node = specularIntensityNode;
  10461. }
  10462. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10463. const specularColorNode = this.getColor( scope );
  10464. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10465. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10466. } else {
  10467. node = specularColorNode;
  10468. }
  10469. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10470. const roughnessNode = this.getFloat( scope );
  10471. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10472. node = roughnessNode.mul( this.getTexture( scope ).g );
  10473. } else {
  10474. node = roughnessNode;
  10475. }
  10476. } else if ( scope === MaterialNode.METALNESS ) {
  10477. const metalnessNode = this.getFloat( scope );
  10478. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10479. node = metalnessNode.mul( this.getTexture( scope ).b );
  10480. } else {
  10481. node = metalnessNode;
  10482. }
  10483. } else if ( scope === MaterialNode.EMISSIVE ) {
  10484. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10485. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10486. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10487. node = emissiveNode.mul( this.getTexture( scope ) );
  10488. } else {
  10489. node = emissiveNode;
  10490. }
  10491. } else if ( scope === MaterialNode.NORMAL ) {
  10492. if ( material.normalMap ) {
  10493. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10494. node.normalMapType = material.normalMapType;
  10495. } else if ( material.bumpMap ) {
  10496. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10497. } else {
  10498. node = normalView;
  10499. }
  10500. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10501. const clearcoatNode = this.getFloat( scope );
  10502. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10503. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10504. } else {
  10505. node = clearcoatNode;
  10506. }
  10507. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  10508. const clearcoatRoughnessNode = this.getFloat( scope );
  10509. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  10510. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  10511. } else {
  10512. node = clearcoatRoughnessNode;
  10513. }
  10514. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  10515. if ( material.clearcoatNormalMap ) {
  10516. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  10517. } else {
  10518. node = normalView;
  10519. }
  10520. } else if ( scope === MaterialNode.SHEEN ) {
  10521. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  10522. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  10523. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  10524. } else {
  10525. node = sheenNode;
  10526. }
  10527. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  10528. const sheenRoughnessNode = this.getFloat( scope );
  10529. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  10530. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  10531. } else {
  10532. node = sheenRoughnessNode;
  10533. }
  10534. node = node.clamp( 0.07, 1.0 );
  10535. } else if ( scope === MaterialNode.ANISOTROPY ) {
  10536. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  10537. const anisotropyPolar = this.getTexture( scope );
  10538. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  10539. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  10540. } else {
  10541. node = materialAnisotropyVector;
  10542. }
  10543. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  10544. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  10545. if ( material.iridescenceThicknessMap ) {
  10546. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  10547. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  10548. } else {
  10549. node = iridescenceThicknessMaximum;
  10550. }
  10551. } else if ( scope === MaterialNode.TRANSMISSION ) {
  10552. const transmissionNode = this.getFloat( scope );
  10553. if ( material.transmissionMap ) {
  10554. node = transmissionNode.mul( this.getTexture( scope ).r );
  10555. } else {
  10556. node = transmissionNode;
  10557. }
  10558. } else if ( scope === MaterialNode.THICKNESS ) {
  10559. const thicknessNode = this.getFloat( scope );
  10560. if ( material.thicknessMap ) {
  10561. node = thicknessNode.mul( this.getTexture( scope ).g );
  10562. } else {
  10563. node = thicknessNode;
  10564. }
  10565. } else if ( scope === MaterialNode.IOR ) {
  10566. node = this.getFloat( scope );
  10567. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  10568. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  10569. } else if ( scope === MaterialNode.AO ) {
  10570. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  10571. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  10572. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  10573. } else {
  10574. const outputType = this.getNodeType( builder );
  10575. node = this.getCache( scope, outputType );
  10576. }
  10577. return node;
  10578. }
  10579. }
  10580. MaterialNode.ALPHA_TEST = 'alphaTest';
  10581. MaterialNode.COLOR = 'color';
  10582. MaterialNode.OPACITY = 'opacity';
  10583. MaterialNode.SHININESS = 'shininess';
  10584. MaterialNode.SPECULAR = 'specular';
  10585. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  10586. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  10587. MaterialNode.SPECULAR_COLOR = 'specularColor';
  10588. MaterialNode.REFLECTIVITY = 'reflectivity';
  10589. MaterialNode.ROUGHNESS = 'roughness';
  10590. MaterialNode.METALNESS = 'metalness';
  10591. MaterialNode.NORMAL = 'normal';
  10592. MaterialNode.CLEARCOAT = 'clearcoat';
  10593. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  10594. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  10595. MaterialNode.EMISSIVE = 'emissive';
  10596. MaterialNode.ROTATION = 'rotation';
  10597. MaterialNode.SHEEN = 'sheen';
  10598. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  10599. MaterialNode.ANISOTROPY = 'anisotropy';
  10600. MaterialNode.IRIDESCENCE = 'iridescence';
  10601. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  10602. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  10603. MaterialNode.IOR = 'ior';
  10604. MaterialNode.TRANSMISSION = 'transmission';
  10605. MaterialNode.THICKNESS = 'thickness';
  10606. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  10607. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  10608. MaterialNode.LINE_SCALE = 'scale';
  10609. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  10610. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  10611. MaterialNode.LINE_WIDTH = 'linewidth';
  10612. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  10613. MaterialNode.POINT_SIZE = 'size';
  10614. MaterialNode.DISPERSION = 'dispersion';
  10615. MaterialNode.LIGHT_MAP = 'light';
  10616. MaterialNode.AO = 'ao';
  10617. /**
  10618. * TSL object that represents alpha test of the current material.
  10619. *
  10620. * @tsl
  10621. * @type {Node<float>}
  10622. */
  10623. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  10624. /**
  10625. * TSL object that represents the diffuse color of the current material.
  10626. * The value is composed via `color` * `map`.
  10627. *
  10628. * @tsl
  10629. * @type {Node<vec3>}
  10630. */
  10631. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  10632. /**
  10633. * TSL object that represents the shininess of the current material.
  10634. *
  10635. * @tsl
  10636. * @type {Node<float>}
  10637. */
  10638. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  10639. /**
  10640. * TSL object that represents the emissive color of the current material.
  10641. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  10642. *
  10643. * @tsl
  10644. * @type {Node<vec3>}
  10645. */
  10646. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  10647. /**
  10648. * TSL object that represents the opacity of the current material.
  10649. * The value is composed via `opacity` * `alphaMap`.
  10650. *
  10651. * @tsl
  10652. * @type {Node<float>}
  10653. */
  10654. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  10655. /**
  10656. * TSL object that represents the specular of the current material.
  10657. *
  10658. * @tsl
  10659. * @type {Node<vec3>}
  10660. */
  10661. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  10662. /**
  10663. * TSL object that represents the specular intensity of the current material.
  10664. * The value is composed via `specularIntensity` * `specularMap.a`.
  10665. *
  10666. * @tsl
  10667. * @type {Node<float>}
  10668. */
  10669. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  10670. /**
  10671. * TSL object that represents the specular color of the current material.
  10672. * The value is composed via `specularColor` * `specularMap.rgb`.
  10673. *
  10674. * @tsl
  10675. * @type {Node<vec3>}
  10676. */
  10677. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  10678. /**
  10679. * TSL object that represents the specular strength of the current material.
  10680. * The value is composed via `specularMap.r`.
  10681. *
  10682. * @tsl
  10683. * @type {Node<float>}
  10684. */
  10685. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  10686. /**
  10687. * TSL object that represents the reflectivity of the current material.
  10688. *
  10689. * @tsl
  10690. * @type {Node<float>}
  10691. */
  10692. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  10693. /**
  10694. * TSL object that represents the roughness of the current material.
  10695. * The value is composed via `roughness` * `roughnessMap.g`.
  10696. *
  10697. * @tsl
  10698. * @type {Node<float>}
  10699. */
  10700. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  10701. /**
  10702. * TSL object that represents the metalness of the current material.
  10703. * The value is composed via `metalness` * `metalnessMap.b`.
  10704. *
  10705. * @tsl
  10706. * @type {Node<float>}
  10707. */
  10708. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  10709. /**
  10710. * TSL object that represents the normal of the current material.
  10711. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  10712. *
  10713. * @tsl
  10714. * @type {Node<vec3>}
  10715. */
  10716. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  10717. /**
  10718. * TSL object that represents the clearcoat of the current material.
  10719. * The value is composed via `clearcoat` * `clearcoatMap.r`
  10720. *
  10721. * @tsl
  10722. * @type {Node<float>}
  10723. */
  10724. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  10725. /**
  10726. * TSL object that represents the clearcoat roughness of the current material.
  10727. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  10728. *
  10729. * @tsl
  10730. * @type {Node<float>}
  10731. */
  10732. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  10733. /**
  10734. * TSL object that represents the clearcoat normal of the current material.
  10735. * The value will be either `clearcoatNormalMap` or `normalView`.
  10736. *
  10737. * @tsl
  10738. * @type {Node<vec3>}
  10739. */
  10740. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  10741. /**
  10742. * TSL object that represents the rotation of the current sprite material.
  10743. *
  10744. * @tsl
  10745. * @type {Node<float>}
  10746. */
  10747. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  10748. /**
  10749. * TSL object that represents the sheen color of the current material.
  10750. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  10751. *
  10752. * @tsl
  10753. * @type {Node<vec3>}
  10754. */
  10755. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  10756. /**
  10757. * TSL object that represents the sheen roughness of the current material.
  10758. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  10759. *
  10760. * @tsl
  10761. * @type {Node<float>}
  10762. */
  10763. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  10764. /**
  10765. * TSL object that represents the anisotropy of the current material.
  10766. *
  10767. * @tsl
  10768. * @type {Node<vec2>}
  10769. */
  10770. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  10771. /**
  10772. * TSL object that represents the iridescence of the current material.
  10773. *
  10774. * @tsl
  10775. * @type {Node<float>}
  10776. */
  10777. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  10778. /**
  10779. * TSL object that represents the iridescence IOR of the current material.
  10780. *
  10781. * @tsl
  10782. * @type {Node<float>}
  10783. */
  10784. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  10785. /**
  10786. * TSL object that represents the iridescence thickness of the current material.
  10787. *
  10788. * @tsl
  10789. * @type {Node<float>}
  10790. */
  10791. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  10792. /**
  10793. * TSL object that represents the transmission of the current material.
  10794. * The value is composed via `transmission` * `transmissionMap.r`.
  10795. *
  10796. * @tsl
  10797. * @type {Node<float>}
  10798. */
  10799. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  10800. /**
  10801. * TSL object that represents the thickness of the current material.
  10802. * The value is composed via `thickness` * `thicknessMap.g`.
  10803. *
  10804. * @tsl
  10805. * @type {Node<float>}
  10806. */
  10807. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  10808. /**
  10809. * TSL object that represents the IOR of the current material.
  10810. *
  10811. * @tsl
  10812. * @type {Node<float>}
  10813. */
  10814. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10815. /**
  10816. * TSL object that represents the attenuation distance of the current material.
  10817. *
  10818. * @tsl
  10819. * @type {Node<float>}
  10820. */
  10821. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10822. /**
  10823. * TSL object that represents the attenuation color of the current material.
  10824. *
  10825. * @tsl
  10826. * @type {Node<vec3>}
  10827. */
  10828. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10829. /**
  10830. * TSL object that represents the scale of the current dashed line material.
  10831. *
  10832. * @tsl
  10833. * @type {Node<float>}
  10834. */
  10835. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10836. /**
  10837. * TSL object that represents the dash size of the current dashed line material.
  10838. *
  10839. * @tsl
  10840. * @type {Node<float>}
  10841. */
  10842. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10843. /**
  10844. * TSL object that represents the gap size of the current dashed line material.
  10845. *
  10846. * @tsl
  10847. * @type {Node<float>}
  10848. */
  10849. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10850. /**
  10851. * TSL object that represents the line width of the current line material.
  10852. *
  10853. * @tsl
  10854. * @type {Node<float>}
  10855. */
  10856. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10857. /**
  10858. * TSL object that represents the dash offset of the current line material.
  10859. *
  10860. * @tsl
  10861. * @type {Node<float>}
  10862. */
  10863. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  10864. /**
  10865. * TSL object that represents the point size of the current points material.
  10866. *
  10867. * @tsl
  10868. * @type {Node<float>}
  10869. */
  10870. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  10871. /**
  10872. * TSL object that represents the dispersion of the current material.
  10873. *
  10874. * @tsl
  10875. * @type {Node<float>}
  10876. */
  10877. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  10878. /**
  10879. * TSL object that represents the light map of the current material.
  10880. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  10881. *
  10882. * @tsl
  10883. * @type {Node<vec3>}
  10884. */
  10885. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  10886. /**
  10887. * TSL object that represents the ambient occlusion map of the current material.
  10888. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  10889. *
  10890. * @tsl
  10891. * @type {Node<float>}
  10892. */
  10893. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  10894. /**
  10895. * TSL object that represents the anisotropy vector of the current material.
  10896. *
  10897. * @tsl
  10898. * @type {Node<vec2>}
  10899. */
  10900. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  10901. return frame.material;
  10902. } ).onRenderUpdate( function ( { material } ) {
  10903. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  10904. } );
  10905. /**
  10906. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  10907. *
  10908. * @tsl
  10909. * @type {VaryingNode<vec4>}
  10910. */
  10911. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10912. return builder.context.setupModelViewProjection();
  10913. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10914. /**
  10915. * This class represents shader indices of different types. The following predefined node
  10916. * objects cover frequent use cases:
  10917. *
  10918. * - `vertexIndex`: The index of a vertex within a mesh.
  10919. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10920. * - `drawIndex`: The index of a draw call.
  10921. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10922. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10923. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10924. *
  10925. * @augments Node
  10926. */
  10927. class IndexNode extends Node {
  10928. static get type() {
  10929. return 'IndexNode';
  10930. }
  10931. /**
  10932. * Constructs a new index node.
  10933. *
  10934. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10935. */
  10936. constructor( scope ) {
  10937. super( 'uint' );
  10938. /**
  10939. * The scope of the index node.
  10940. *
  10941. * @type {string}
  10942. */
  10943. this.scope = scope;
  10944. /**
  10945. * This flag can be used for type testing.
  10946. *
  10947. * @type {boolean}
  10948. * @readonly
  10949. * @default true
  10950. */
  10951. this.isIndexNode = true;
  10952. }
  10953. generate( builder ) {
  10954. const nodeType = this.getNodeType( builder );
  10955. const scope = this.scope;
  10956. let propertyName;
  10957. if ( scope === IndexNode.VERTEX ) {
  10958. propertyName = builder.getVertexIndex();
  10959. } else if ( scope === IndexNode.INSTANCE ) {
  10960. propertyName = builder.getInstanceIndex();
  10961. } else if ( scope === IndexNode.DRAW ) {
  10962. propertyName = builder.getDrawIndex();
  10963. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10964. propertyName = builder.getInvocationLocalIndex();
  10965. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10966. propertyName = builder.getInvocationSubgroupIndex();
  10967. } else if ( scope === IndexNode.SUBGROUP ) {
  10968. propertyName = builder.getSubgroupIndex();
  10969. } else {
  10970. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10971. }
  10972. let output;
  10973. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10974. output = propertyName;
  10975. } else {
  10976. const nodeVarying = varying( this );
  10977. output = nodeVarying.build( builder, nodeType );
  10978. }
  10979. return output;
  10980. }
  10981. }
  10982. IndexNode.VERTEX = 'vertex';
  10983. IndexNode.INSTANCE = 'instance';
  10984. IndexNode.SUBGROUP = 'subgroup';
  10985. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10986. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10987. IndexNode.DRAW = 'draw';
  10988. /**
  10989. * TSL object that represents the index of a vertex within a mesh.
  10990. *
  10991. * @tsl
  10992. * @type {IndexNode}
  10993. */
  10994. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10995. /**
  10996. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10997. *
  10998. * @tsl
  10999. * @type {IndexNode}
  11000. */
  11001. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  11002. /**
  11003. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  11004. *
  11005. * @tsl
  11006. * @type {IndexNode}
  11007. */
  11008. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11009. /**
  11010. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11011. *
  11012. * @tsl
  11013. * @type {IndexNode}
  11014. */
  11015. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11016. /**
  11017. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11018. *
  11019. * @tsl
  11020. * @type {IndexNode}
  11021. */
  11022. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11023. /**
  11024. * TSL object that represents the index of a draw call.
  11025. *
  11026. * @tsl
  11027. * @type {IndexNode}
  11028. */
  11029. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11030. /**
  11031. * This node implements the vertex shader logic which is required
  11032. * when rendering 3D objects via instancing. The code makes sure
  11033. * vertex positions, normals and colors can be modified via instanced
  11034. * data.
  11035. *
  11036. * @augments Node
  11037. */
  11038. class InstanceNode extends Node {
  11039. static get type() {
  11040. return 'InstanceNode';
  11041. }
  11042. /**
  11043. * Constructs a new instance node.
  11044. *
  11045. * @param {number} count - The number of instances.
  11046. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11047. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11048. */
  11049. constructor( count, instanceMatrix, instanceColor = null ) {
  11050. super( 'void' );
  11051. /**
  11052. * The number of instances.
  11053. *
  11054. * @type {number}
  11055. */
  11056. this.count = count;
  11057. /**
  11058. * Instanced buffer attribute representing the transformation of instances.
  11059. *
  11060. * @type {InstancedBufferAttribute}
  11061. */
  11062. this.instanceMatrix = instanceMatrix;
  11063. /**
  11064. * Instanced buffer attribute representing the color of instances.
  11065. *
  11066. * @type {InstancedBufferAttribute}
  11067. */
  11068. this.instanceColor = instanceColor;
  11069. /**
  11070. * The node that represents the instance matrix data.
  11071. *
  11072. * @type {?Node}
  11073. */
  11074. this.instanceMatrixNode = null;
  11075. /**
  11076. * The node that represents the instance color data.
  11077. *
  11078. * @type {?Node}
  11079. * @default null
  11080. */
  11081. this.instanceColorNode = null;
  11082. /**
  11083. * The update type is set to `frame` since an update
  11084. * of instanced buffer data must be checked per frame.
  11085. *
  11086. * @type {string}
  11087. * @default 'frame'
  11088. */
  11089. this.updateType = NodeUpdateType.FRAME;
  11090. /**
  11091. * A reference to a buffer that is used by `instanceMatrixNode`.
  11092. *
  11093. * @type {?InstancedInterleavedBuffer}
  11094. */
  11095. this.buffer = null;
  11096. /**
  11097. * A reference to a buffer that is used by `instanceColorNode`.
  11098. *
  11099. * @type {?InstancedBufferAttribute}
  11100. */
  11101. this.bufferColor = null;
  11102. }
  11103. /**
  11104. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11105. * to predefined node variables for accumulation. That follows the same patterns
  11106. * like with morph and skinning nodes.
  11107. *
  11108. * @param {NodeBuilder} builder - The current node builder.
  11109. */
  11110. setup( builder ) {
  11111. const { instanceMatrix, instanceColor } = this;
  11112. const { count } = instanceMatrix;
  11113. let { instanceMatrixNode, instanceColorNode } = this;
  11114. if ( instanceMatrixNode === null ) {
  11115. // 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.
  11116. if ( count <= 1000 ) {
  11117. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11118. } else {
  11119. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11120. this.buffer = buffer;
  11121. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11122. const instanceBuffers = [
  11123. // F.Signature -> bufferAttribute( array, type, stride, offset )
  11124. bufferFn( buffer, 'vec4', 16, 0 ),
  11125. bufferFn( buffer, 'vec4', 16, 4 ),
  11126. bufferFn( buffer, 'vec4', 16, 8 ),
  11127. bufferFn( buffer, 'vec4', 16, 12 )
  11128. ];
  11129. instanceMatrixNode = mat4( ...instanceBuffers );
  11130. }
  11131. this.instanceMatrixNode = instanceMatrixNode;
  11132. }
  11133. if ( instanceColor && instanceColorNode === null ) {
  11134. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11135. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11136. this.bufferColor = buffer;
  11137. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11138. this.instanceColorNode = instanceColorNode;
  11139. }
  11140. // POSITION
  11141. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11142. positionLocal.assign( instancePosition );
  11143. // NORMAL
  11144. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11145. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11146. // ASSIGNS
  11147. normalLocal.assign( instanceNormal );
  11148. }
  11149. // COLOR
  11150. if ( this.instanceColorNode !== null ) {
  11151. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11152. }
  11153. }
  11154. /**
  11155. * Checks if the internal buffers required an update.
  11156. *
  11157. * @param {NodeFrame} frame - The current node frame.
  11158. */
  11159. update( /*frame*/ ) {
  11160. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  11161. this.buffer.version = this.instanceMatrix.version;
  11162. }
  11163. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  11164. this.bufferColor.version = this.instanceColor.version;
  11165. }
  11166. }
  11167. }
  11168. /**
  11169. * TSL function for creating an instance node.
  11170. *
  11171. * @tsl
  11172. * @function
  11173. * @param {number} count - The number of instances.
  11174. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11175. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11176. * @returns {InstanceNode}
  11177. */
  11178. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11179. /**
  11180. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11181. * It allows an easier setup of the instance node.
  11182. *
  11183. * @augments InstanceNode
  11184. */
  11185. class InstancedMeshNode extends InstanceNode {
  11186. static get type() {
  11187. return 'InstancedMeshNode';
  11188. }
  11189. /**
  11190. * Constructs a new instanced mesh node.
  11191. *
  11192. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11193. */
  11194. constructor( instancedMesh ) {
  11195. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11196. super( count, instanceMatrix, instanceColor );
  11197. /**
  11198. * A reference to the instanced mesh.
  11199. *
  11200. * @type {InstancedMesh}
  11201. */
  11202. this.instancedMesh = instancedMesh;
  11203. }
  11204. }
  11205. /**
  11206. * TSL function for creating an instanced mesh node.
  11207. *
  11208. * @tsl
  11209. * @function
  11210. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11211. * @returns {InstancedMeshNode}
  11212. */
  11213. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11214. /**
  11215. * This node implements the vertex shader logic which is required
  11216. * when rendering 3D objects via batching. `BatchNode` must be used
  11217. * with instances of {@link BatchedMesh}.
  11218. *
  11219. * @augments Node
  11220. */
  11221. class BatchNode extends Node {
  11222. static get type() {
  11223. return 'BatchNode';
  11224. }
  11225. /**
  11226. * Constructs a new batch node.
  11227. *
  11228. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11229. */
  11230. constructor( batchMesh ) {
  11231. super( 'void' );
  11232. /**
  11233. * A reference to batched mesh.
  11234. *
  11235. * @type {BatchedMesh}
  11236. */
  11237. this.batchMesh = batchMesh;
  11238. /**
  11239. * The batching index node.
  11240. *
  11241. * @type {?IndexNode}
  11242. * @default null
  11243. */
  11244. this.batchingIdNode = null;
  11245. }
  11246. /**
  11247. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11248. * to predefined node variables for accumulation. That follows the same patterns
  11249. * like with morph and skinning nodes.
  11250. *
  11251. * @param {NodeBuilder} builder - The current node builder.
  11252. */
  11253. setup( builder ) {
  11254. if ( this.batchingIdNode === null ) {
  11255. if ( builder.getDrawIndex() === null ) {
  11256. this.batchingIdNode = instanceIndex;
  11257. } else {
  11258. this.batchingIdNode = drawIndex;
  11259. }
  11260. }
  11261. const getIndirectIndex = Fn( ( [ id ] ) => {
  11262. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  11263. const x = int( id ).mod( size );
  11264. const y = int( id ).div( size );
  11265. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11266. } ).setLayout( {
  11267. name: 'getIndirectIndex',
  11268. type: 'uint',
  11269. inputs: [
  11270. { name: 'id', type: 'int' }
  11271. ]
  11272. } );
  11273. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11274. const matricesTexture = this.batchMesh._matricesTexture;
  11275. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  11276. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  11277. const x = j.mod( size );
  11278. const y = j.div( size );
  11279. const batchingMatrix = mat4(
  11280. textureLoad( matricesTexture, ivec2( x, y ) ),
  11281. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11282. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11283. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11284. );
  11285. const colorsTexture = this.batchMesh._colorsTexture;
  11286. if ( colorsTexture !== null ) {
  11287. const getBatchingColor = Fn( ( [ id ] ) => {
  11288. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  11289. const j = id;
  11290. const x = j.mod( size );
  11291. const y = j.div( size );
  11292. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11293. } ).setLayout( {
  11294. name: 'getBatchingColor',
  11295. type: 'vec3',
  11296. inputs: [
  11297. { name: 'id', type: 'int' }
  11298. ]
  11299. } );
  11300. const color = getBatchingColor( indirectId );
  11301. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11302. }
  11303. const bm = mat3( batchingMatrix );
  11304. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11305. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11306. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11307. normalLocal.assign( batchingNormal );
  11308. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11309. tangentLocal.mulAssign( bm );
  11310. }
  11311. }
  11312. }
  11313. /**
  11314. * TSL function for creating a batch node.
  11315. *
  11316. * @tsl
  11317. * @function
  11318. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11319. * @returns {BatchNode}
  11320. */
  11321. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11322. /**
  11323. * This class enables element access on instances of {@link StorageBufferNode}.
  11324. * In most cases, it is indirectly used when accessing elements with the
  11325. * {@link StorageBufferNode#element} method.
  11326. *
  11327. * ```js
  11328. * const position = positionStorage.element( instanceIndex );
  11329. * ```
  11330. *
  11331. * @augments ArrayElementNode
  11332. */
  11333. class StorageArrayElementNode extends ArrayElementNode {
  11334. static get type() {
  11335. return 'StorageArrayElementNode';
  11336. }
  11337. /**
  11338. * Constructs storage buffer element node.
  11339. *
  11340. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11341. * @param {Node} indexNode - The index node that defines the element access.
  11342. */
  11343. constructor( storageBufferNode, indexNode ) {
  11344. super( storageBufferNode, indexNode );
  11345. /**
  11346. * This flag can be used for type testing.
  11347. *
  11348. * @type {boolean}
  11349. * @readonly
  11350. * @default true
  11351. */
  11352. this.isStorageArrayElementNode = true;
  11353. }
  11354. /**
  11355. * The storage buffer node.
  11356. *
  11357. * @param {Node} value
  11358. * @type {StorageBufferNode}
  11359. */
  11360. set storageBufferNode( value ) {
  11361. this.node = value;
  11362. }
  11363. get storageBufferNode() {
  11364. return this.node;
  11365. }
  11366. getMemberType( builder, name ) {
  11367. const structTypeNode = this.storageBufferNode.structTypeNode;
  11368. if ( structTypeNode ) {
  11369. return structTypeNode.getMemberType( builder, name );
  11370. }
  11371. return 'void';
  11372. }
  11373. setup( builder ) {
  11374. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11375. if ( this.node.isPBO === true ) {
  11376. builder.setupPBO( this.node );
  11377. }
  11378. }
  11379. return super.setup( builder );
  11380. }
  11381. generate( builder, output ) {
  11382. let snippet;
  11383. const isAssignContext = builder.context.assign;
  11384. //
  11385. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11386. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11387. snippet = builder.generatePBO( this );
  11388. } else {
  11389. snippet = this.node.build( builder );
  11390. }
  11391. } else {
  11392. snippet = super.generate( builder );
  11393. }
  11394. if ( isAssignContext !== true ) {
  11395. const type = this.getNodeType( builder );
  11396. snippet = builder.format( snippet, type, output );
  11397. }
  11398. return snippet;
  11399. }
  11400. }
  11401. /**
  11402. * TSL function for creating a storage element node.
  11403. *
  11404. * @tsl
  11405. * @function
  11406. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11407. * @param {Node} indexNode - The index node that defines the element access.
  11408. * @returns {StorageArrayElementNode}
  11409. */
  11410. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11411. /**
  11412. * This node is used in context of compute shaders and allows to define a
  11413. * storage buffer for data. A typical workflow is to create instances of
  11414. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11415. * setup up a compute shader that writes into the buffers and then convert
  11416. * the storage buffers to attribute nodes for rendering.
  11417. *
  11418. * ```js
  11419. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11420. *
  11421. * const computeInit = Fn( () => { // the compute shader
  11422. *
  11423. * const position = positionBuffer.element( instanceIndex );
  11424. *
  11425. * // compute position data
  11426. *
  11427. * position.x = 1;
  11428. * position.y = 1;
  11429. * position.z = 1;
  11430. *
  11431. * } )().compute( particleCount );
  11432. *
  11433. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11434. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11435. *
  11436. * renderer.computeAsync( computeInit );
  11437. *
  11438. * ```
  11439. *
  11440. * @augments BufferNode
  11441. */
  11442. class StorageBufferNode extends BufferNode {
  11443. static get type() {
  11444. return 'StorageBufferNode';
  11445. }
  11446. /**
  11447. * Constructs a new storage buffer node.
  11448. *
  11449. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11450. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11451. * @param {number} [bufferCount=0] - The buffer count.
  11452. */
  11453. constructor( value, bufferType = null, bufferCount = 0 ) {
  11454. let nodeType, structTypeNode = null;
  11455. if ( bufferType && bufferType.isStruct ) {
  11456. nodeType = 'struct';
  11457. structTypeNode = bufferType.layout;
  11458. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11459. bufferCount = value.count;
  11460. }
  11461. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11462. nodeType = getTypeFromLength( value.itemSize );
  11463. bufferCount = value.count;
  11464. } else {
  11465. nodeType = bufferType;
  11466. }
  11467. super( value, nodeType, bufferCount );
  11468. /**
  11469. * This flag can be used for type testing.
  11470. *
  11471. * @type {boolean}
  11472. * @readonly
  11473. * @default true
  11474. */
  11475. this.isStorageBufferNode = true;
  11476. /**
  11477. * The buffer struct type.
  11478. *
  11479. * @type {?StructTypeNode}
  11480. * @default null
  11481. */
  11482. this.structTypeNode = structTypeNode;
  11483. /**
  11484. * The access type of the texture node.
  11485. *
  11486. * @type {string}
  11487. * @default 'readWrite'
  11488. */
  11489. this.access = NodeAccess.READ_WRITE;
  11490. /**
  11491. * Whether the node is atomic or not.
  11492. *
  11493. * @type {boolean}
  11494. * @default false
  11495. */
  11496. this.isAtomic = false;
  11497. /**
  11498. * Whether the node represents a PBO or not.
  11499. * Only relevant for WebGL.
  11500. *
  11501. * @type {boolean}
  11502. * @default false
  11503. */
  11504. this.isPBO = false;
  11505. /**
  11506. * A reference to the internal buffer attribute node.
  11507. *
  11508. * @type {?BufferAttributeNode}
  11509. * @default null
  11510. */
  11511. this._attribute = null;
  11512. /**
  11513. * A reference to the internal varying node.
  11514. *
  11515. * @type {?VaryingNode}
  11516. * @default null
  11517. */
  11518. this._varying = null;
  11519. /**
  11520. * `StorageBufferNode` sets this property to `true` by default.
  11521. *
  11522. * @type {boolean}
  11523. * @default true
  11524. */
  11525. this.global = true;
  11526. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11527. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11528. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11529. else value.isStorageBufferAttribute = true;
  11530. }
  11531. }
  11532. /**
  11533. * This method is overwritten since the buffer data might be shared
  11534. * and thus the hash should be shared as well.
  11535. *
  11536. * @param {NodeBuilder} builder - The current node builder.
  11537. * @return {string} The hash.
  11538. */
  11539. getHash( builder ) {
  11540. if ( this.bufferCount === 0 ) {
  11541. let bufferData = builder.globalCache.getData( this.value );
  11542. if ( bufferData === undefined ) {
  11543. bufferData = {
  11544. node: this
  11545. };
  11546. builder.globalCache.setData( this.value, bufferData );
  11547. }
  11548. return bufferData.node.uuid;
  11549. }
  11550. return this.uuid;
  11551. }
  11552. /**
  11553. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11554. *
  11555. * @param {NodeBuilder} builder - The current node builder.
  11556. * @return {string} The input type.
  11557. */
  11558. getInputType( /*builder*/ ) {
  11559. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11560. }
  11561. /**
  11562. * Enables element access with the given index node.
  11563. *
  11564. * @param {IndexNode} indexNode - The index node.
  11565. * @return {StorageArrayElementNode} A node representing the element access.
  11566. */
  11567. element( indexNode ) {
  11568. return storageElement( this, indexNode );
  11569. }
  11570. /**
  11571. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11572. *
  11573. * @param {boolean} value - The value so set.
  11574. * @return {StorageBufferNode} A reference to this node.
  11575. */
  11576. setPBO( value ) {
  11577. this.isPBO = value;
  11578. return this;
  11579. }
  11580. /**
  11581. * Returns the `isPBO` value.
  11582. *
  11583. * @return {boolean} Whether the node represents a PBO or not.
  11584. */
  11585. getPBO() {
  11586. return this.isPBO;
  11587. }
  11588. /**
  11589. * Defines the node access.
  11590. *
  11591. * @param {string} value - The node access.
  11592. * @return {StorageBufferNode} A reference to this node.
  11593. */
  11594. setAccess( value ) {
  11595. this.access = value;
  11596. return this;
  11597. }
  11598. /**
  11599. * Convenience method for configuring a read-only node access.
  11600. *
  11601. * @return {StorageBufferNode} A reference to this node.
  11602. */
  11603. toReadOnly() {
  11604. return this.setAccess( NodeAccess.READ_ONLY );
  11605. }
  11606. /**
  11607. * Defines whether the node is atomic or not.
  11608. *
  11609. * @param {boolean} value - The atomic flag.
  11610. * @return {StorageBufferNode} A reference to this node.
  11611. */
  11612. setAtomic( value ) {
  11613. this.isAtomic = value;
  11614. return this;
  11615. }
  11616. /**
  11617. * Convenience method for making this node atomic.
  11618. *
  11619. * @return {StorageBufferNode} A reference to this node.
  11620. */
  11621. toAtomic() {
  11622. return this.setAtomic( true );
  11623. }
  11624. /**
  11625. * Returns attribute data for this storage buffer node.
  11626. *
  11627. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11628. */
  11629. getAttributeData() {
  11630. if ( this._attribute === null ) {
  11631. this._attribute = bufferAttribute( this.value );
  11632. this._varying = varying( this._attribute );
  11633. }
  11634. return {
  11635. attribute: this._attribute,
  11636. varying: this._varying
  11637. };
  11638. }
  11639. /**
  11640. * This method is overwritten since the node type from the availability of storage buffers
  11641. * and the attribute data.
  11642. *
  11643. * @param {NodeBuilder} builder - The current node builder.
  11644. * @return {string} The node type.
  11645. */
  11646. getNodeType( builder ) {
  11647. if ( this.structTypeNode !== null ) {
  11648. return this.structTypeNode.getNodeType( builder );
  11649. }
  11650. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11651. return super.getNodeType( builder );
  11652. }
  11653. const { attribute } = this.getAttributeData();
  11654. return attribute.getNodeType( builder );
  11655. }
  11656. /**
  11657. * Returns the type of a member of the struct.
  11658. *
  11659. * @param {NodeBuilder} builder - The current node builder.
  11660. * @param {string} name - The name of the member.
  11661. * @return {string} The type of the member.
  11662. */
  11663. getMemberType( builder, name ) {
  11664. if ( this.structTypeNode !== null ) {
  11665. return this.structTypeNode.getMemberType( builder, name );
  11666. }
  11667. return 'void';
  11668. }
  11669. /**
  11670. * Generates the code snippet of the storage buffer node.
  11671. *
  11672. * @param {NodeBuilder} builder - The current node builder.
  11673. * @return {string} The generated code snippet.
  11674. */
  11675. generate( builder ) {
  11676. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11677. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11678. return super.generate( builder );
  11679. }
  11680. const { attribute, varying } = this.getAttributeData();
  11681. const output = varying.build( builder );
  11682. builder.registerTransform( output, attribute );
  11683. return output;
  11684. }
  11685. }
  11686. /**
  11687. * TSL function for creating a storage buffer node.
  11688. *
  11689. * @tsl
  11690. * @function
  11691. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11692. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11693. * @param {number} [count=0] - The buffer count.
  11694. * @returns {StorageBufferNode}
  11695. */
  11696. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11697. /**
  11698. * @tsl
  11699. * @function
  11700. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11701. *
  11702. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11703. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  11704. * @param {number} count - The buffer count.
  11705. * @returns {StorageBufferNode}
  11706. */
  11707. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11708. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11709. return storage( value, type, count ).setPBO( true );
  11710. };
  11711. const _frameId = new WeakMap();
  11712. /**
  11713. * This node implements the vertex transformation shader logic which is required
  11714. * for skinning/skeletal animation.
  11715. *
  11716. * @augments Node
  11717. */
  11718. class SkinningNode extends Node {
  11719. static get type() {
  11720. return 'SkinningNode';
  11721. }
  11722. /**
  11723. * Constructs a new skinning node.
  11724. *
  11725. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11726. */
  11727. constructor( skinnedMesh ) {
  11728. super( 'void' );
  11729. /**
  11730. * The skinned mesh.
  11731. *
  11732. * @type {SkinnedMesh}
  11733. */
  11734. this.skinnedMesh = skinnedMesh;
  11735. /**
  11736. * The update type overwritten since skinning nodes are updated per object.
  11737. *
  11738. * @type {string}
  11739. */
  11740. this.updateType = NodeUpdateType.OBJECT;
  11741. //
  11742. /**
  11743. * The skin index attribute.
  11744. *
  11745. * @type {AttributeNode}
  11746. */
  11747. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  11748. /**
  11749. * The skin weight attribute.
  11750. *
  11751. * @type {AttributeNode}
  11752. */
  11753. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  11754. /**
  11755. * The bind matrix node.
  11756. *
  11757. * @type {Node<mat4>}
  11758. */
  11759. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  11760. /**
  11761. * The bind matrix inverse node.
  11762. *
  11763. * @type {Node<mat4>}
  11764. */
  11765. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  11766. /**
  11767. * The bind matrices as a uniform buffer node.
  11768. *
  11769. * @type {Node}
  11770. */
  11771. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11772. /**
  11773. * The current vertex position in local space.
  11774. *
  11775. * @type {Node<vec3>}
  11776. */
  11777. this.positionNode = positionLocal;
  11778. /**
  11779. * The result of vertex position in local space.
  11780. *
  11781. * @type {Node<vec3>}
  11782. */
  11783. this.toPositionNode = positionLocal;
  11784. /**
  11785. * The previous bind matrices as a uniform buffer node.
  11786. * Required for computing motion vectors.
  11787. *
  11788. * @type {?Node}
  11789. * @default null
  11790. */
  11791. this.previousBoneMatricesNode = null;
  11792. }
  11793. /**
  11794. * Transforms the given vertex position via skinning.
  11795. *
  11796. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11797. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  11798. * @return {Node<vec3>} The transformed vertex position.
  11799. */
  11800. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  11801. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11802. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11803. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11804. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11805. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11806. // POSITION
  11807. const skinVertex = bindMatrixNode.mul( position );
  11808. const skinned = add(
  11809. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  11810. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11811. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11812. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11813. );
  11814. return bindMatrixInverseNode.mul( skinned ).xyz;
  11815. }
  11816. /**
  11817. * Transforms the given vertex normal via skinning.
  11818. *
  11819. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11820. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11821. * @return {Node<vec3>} The transformed vertex normal.
  11822. */
  11823. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11824. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11825. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11826. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11827. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11828. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11829. // NORMAL
  11830. let skinMatrix = add(
  11831. skinWeightNode.x.mul( boneMatX ),
  11832. skinWeightNode.y.mul( boneMatY ),
  11833. skinWeightNode.z.mul( boneMatZ ),
  11834. skinWeightNode.w.mul( boneMatW )
  11835. );
  11836. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11837. return skinMatrix.transformDirection( normal ).xyz;
  11838. }
  11839. /**
  11840. * Computes the transformed/skinned vertex position of the previous frame.
  11841. *
  11842. * @param {NodeBuilder} builder - The current node builder.
  11843. * @return {Node<vec3>} The skinned position from the previous frame.
  11844. */
  11845. getPreviousSkinnedPosition( builder ) {
  11846. const skinnedMesh = builder.object;
  11847. if ( this.previousBoneMatricesNode === null ) {
  11848. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11849. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11850. }
  11851. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  11852. }
  11853. /**
  11854. * Returns `true` if bone matrices from the previous frame are required. Relevant
  11855. * when computing motion vectors with {@link VelocityNode}.
  11856. *
  11857. * @param {NodeBuilder} builder - The current node builder.
  11858. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  11859. */
  11860. needsPreviousBoneMatrices( builder ) {
  11861. const mrt = builder.renderer.getMRT();
  11862. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  11863. }
  11864. /**
  11865. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  11866. *
  11867. * @param {NodeBuilder} builder - The current node builder.
  11868. * @return {Node<vec3>} The transformed vertex position.
  11869. */
  11870. setup( builder ) {
  11871. if ( this.needsPreviousBoneMatrices( builder ) ) {
  11872. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  11873. }
  11874. const skinPosition = this.getSkinnedPosition();
  11875. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  11876. //
  11877. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11878. const skinNormal = this.getSkinnedNormal();
  11879. normalLocal.assign( skinNormal );
  11880. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11881. tangentLocal.assign( skinNormal );
  11882. }
  11883. }
  11884. return skinPosition;
  11885. }
  11886. /**
  11887. * Generates the code snippet of the skinning node.
  11888. *
  11889. * @param {NodeBuilder} builder - The current node builder.
  11890. * @param {string} output - The current output.
  11891. * @return {string} The generated code snippet.
  11892. */
  11893. generate( builder, output ) {
  11894. if ( output !== 'void' ) {
  11895. return super.generate( builder, output );
  11896. }
  11897. }
  11898. /**
  11899. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  11900. *
  11901. * @param {NodeFrame} frame - The current node frame.
  11902. */
  11903. update( frame ) {
  11904. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  11905. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  11906. _frameId.set( skeleton, frame.frameId );
  11907. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  11908. skeleton.update();
  11909. }
  11910. }
  11911. /**
  11912. * TSL function for creating a skinning node.
  11913. *
  11914. * @tsl
  11915. * @function
  11916. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11917. * @returns {SkinningNode}
  11918. */
  11919. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  11920. /**
  11921. * TSL function for computing skinning.
  11922. *
  11923. * @tsl
  11924. * @function
  11925. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11926. * @param {Node<vec3>} [toPosition=null] - The target position.
  11927. * @returns {SkinningNode}
  11928. */
  11929. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11930. const node = new SkinningNode( skinnedMesh );
  11931. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11932. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11933. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11934. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11935. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11936. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11937. node.toPositionNode = toPosition;
  11938. return nodeObject( node );
  11939. };
  11940. /**
  11941. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11942. * ```js
  11943. * Loop( count, ( { i } ) => {
  11944. *
  11945. * } );
  11946. * ```
  11947. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11948. * ```js
  11949. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11950. *
  11951. * } );
  11952. *```
  11953. * Nested loops can be defined in a compacted form:
  11954. * ```js
  11955. * Loop( 10, 5, ( { i, j } ) => {
  11956. *
  11957. * } );
  11958. * ```
  11959. * Loops that should run backwards can be defined like so:
  11960. * ```js
  11961. * Loop( { start: 10 }, () => {} );
  11962. * ```
  11963. * It is possible to execute with boolean values, similar to the `while` syntax.
  11964. * ```js
  11965. * const value = float( 0 ).toVar();
  11966. *
  11967. * Loop( value.lessThan( 10 ), () => {
  11968. *
  11969. * value.addAssign( 1 );
  11970. *
  11971. * } );
  11972. * ```
  11973. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11974. * @augments Node
  11975. */
  11976. class LoopNode extends Node {
  11977. static get type() {
  11978. return 'LoopNode';
  11979. }
  11980. /**
  11981. * Constructs a new loop node.
  11982. *
  11983. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11984. */
  11985. constructor( params = [] ) {
  11986. super();
  11987. this.params = params;
  11988. }
  11989. /**
  11990. * Returns a loop variable name based on an index. The pattern is
  11991. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11992. *
  11993. * @param {number} index - The index.
  11994. * @return {string} The loop variable name.
  11995. */
  11996. getVarName( index ) {
  11997. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11998. }
  11999. /**
  12000. * Returns properties about this node.
  12001. *
  12002. * @param {NodeBuilder} builder - The current node builder.
  12003. * @return {Object} The node properties.
  12004. */
  12005. getProperties( builder ) {
  12006. const properties = builder.getNodeProperties( this );
  12007. if ( properties.stackNode !== undefined ) return properties;
  12008. //
  12009. const inputs = {};
  12010. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12011. const param = this.params[ i ];
  12012. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12013. const type = ( param.isNode !== true && param.type ) || 'int';
  12014. inputs[ name ] = expression( name, type );
  12015. }
  12016. const stack = builder.addStack(); // TODO: cache() it
  12017. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  12018. properties.stackNode = stack;
  12019. const baseParam = this.params[ 0 ];
  12020. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12021. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  12022. }
  12023. builder.removeStack();
  12024. return properties;
  12025. }
  12026. /**
  12027. * This method is overwritten since the node type is inferred based on the loop configuration.
  12028. *
  12029. * @param {NodeBuilder} builder - The current node builder.
  12030. * @return {string} The node type.
  12031. */
  12032. getNodeType( builder ) {
  12033. const { returnsNode } = this.getProperties( builder );
  12034. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  12035. }
  12036. setup( builder ) {
  12037. // setup properties
  12038. this.getProperties( builder );
  12039. }
  12040. generate( builder ) {
  12041. const properties = this.getProperties( builder );
  12042. const params = this.params;
  12043. const stackNode = properties.stackNode;
  12044. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12045. const param = params[ i ];
  12046. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12047. if ( param.isNode ) {
  12048. if ( param.getNodeType( builder ) === 'bool' ) {
  12049. isWhile = true;
  12050. type = 'bool';
  12051. end = param.build( builder, type );
  12052. } else {
  12053. type = 'int';
  12054. name = this.getVarName( i );
  12055. start = '0';
  12056. end = param.build( builder, type );
  12057. condition = '<';
  12058. }
  12059. } else {
  12060. type = param.type || 'int';
  12061. name = param.name || this.getVarName( i );
  12062. start = param.start;
  12063. end = param.end;
  12064. condition = param.condition;
  12065. update = param.update;
  12066. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12067. else if ( start && start.isNode ) start = start.build( builder, type );
  12068. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12069. else if ( end && end.isNode ) end = end.build( builder, type );
  12070. if ( start !== undefined && end === undefined ) {
  12071. start = start + ' - 1';
  12072. end = '0';
  12073. condition = '>=';
  12074. } else if ( end !== undefined && start === undefined ) {
  12075. start = '0';
  12076. condition = '<';
  12077. }
  12078. if ( condition === undefined ) {
  12079. if ( Number( start ) > Number( end ) ) {
  12080. condition = '>=';
  12081. } else {
  12082. condition = '<';
  12083. }
  12084. }
  12085. }
  12086. let loopSnippet;
  12087. if ( isWhile ) {
  12088. loopSnippet = `while ( ${ end } )`;
  12089. } else {
  12090. const internalParam = { start, end};
  12091. //
  12092. const startSnippet = internalParam.start;
  12093. const endSnippet = internalParam.end;
  12094. let updateSnippet;
  12095. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12096. if ( update !== undefined && update !== null ) {
  12097. switch ( typeof update ) {
  12098. case 'function':
  12099. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12100. const snippet = flow.code.replace( /\t|;/g, '' );
  12101. updateSnippet = snippet;
  12102. break;
  12103. case 'number':
  12104. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12105. break;
  12106. case 'string':
  12107. updateSnippet = name + ' ' + update;
  12108. break;
  12109. default:
  12110. if ( update.isNode ) {
  12111. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12112. } else {
  12113. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12114. updateSnippet = 'break /* invalid update */';
  12115. }
  12116. }
  12117. } else {
  12118. if ( type === 'int' || type === 'uint' ) {
  12119. update = condition.includes( '<' ) ? '++' : '--';
  12120. } else {
  12121. update = deltaOperator() + ' 1.';
  12122. }
  12123. updateSnippet = name + ' ' + update;
  12124. }
  12125. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12126. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12127. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12128. }
  12129. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12130. }
  12131. const stackSnippet = stackNode.build( builder, 'void' );
  12132. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  12133. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12134. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12135. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12136. }
  12137. builder.addFlowTab();
  12138. return returnsSnippet;
  12139. }
  12140. }
  12141. /**
  12142. * TSL function for creating a loop node.
  12143. *
  12144. * @tsl
  12145. * @function
  12146. * @param {...any} params - A list of parameters.
  12147. * @returns {LoopNode}
  12148. */
  12149. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  12150. /**
  12151. * TSL function for creating a `Continue()` expression.
  12152. *
  12153. * @tsl
  12154. * @function
  12155. * @returns {ExpressionNode}
  12156. */
  12157. const Continue = () => expression( 'continue' ).toStack();
  12158. /**
  12159. * TSL function for creating a `Break()` expression.
  12160. *
  12161. * @tsl
  12162. * @function
  12163. * @returns {ExpressionNode}
  12164. */
  12165. const Break = () => expression( 'break' ).toStack();
  12166. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12167. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12168. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12169. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12170. const y = texelIndex.div( width );
  12171. const x = texelIndex.sub( y.mul( width ) );
  12172. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12173. return bufferAttrib.mul( influence );
  12174. } );
  12175. function getEntry( geometry ) {
  12176. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12177. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12178. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12179. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12180. // into an array of data textures. Each layer represents a single morph target.
  12181. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12182. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12183. let entry = _morphTextures.get( geometry );
  12184. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12185. if ( entry !== undefined ) entry.texture.dispose();
  12186. const morphTargets = geometry.morphAttributes.position || [];
  12187. const morphNormals = geometry.morphAttributes.normal || [];
  12188. const morphColors = geometry.morphAttributes.color || [];
  12189. let vertexDataCount = 0;
  12190. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12191. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12192. if ( hasMorphColors === true ) vertexDataCount = 3;
  12193. let width = geometry.attributes.position.count * vertexDataCount;
  12194. let height = 1;
  12195. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12196. if ( width > maxTextureSize ) {
  12197. height = Math.ceil( width / maxTextureSize );
  12198. width = maxTextureSize;
  12199. }
  12200. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12201. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12202. bufferTexture.type = FloatType;
  12203. bufferTexture.needsUpdate = true;
  12204. // fill buffer
  12205. const vertexDataStride = vertexDataCount * 4;
  12206. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12207. const morphTarget = morphTargets[ i ];
  12208. const morphNormal = morphNormals[ i ];
  12209. const morphColor = morphColors[ i ];
  12210. const offset = width * height * 4 * i;
  12211. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12212. const stride = j * vertexDataStride;
  12213. if ( hasMorphPosition === true ) {
  12214. _morphVec4.fromBufferAttribute( morphTarget, j );
  12215. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12216. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12217. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12218. buffer[ offset + stride + 3 ] = 0;
  12219. }
  12220. if ( hasMorphNormals === true ) {
  12221. _morphVec4.fromBufferAttribute( morphNormal, j );
  12222. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12223. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12224. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12225. buffer[ offset + stride + 7 ] = 0;
  12226. }
  12227. if ( hasMorphColors === true ) {
  12228. _morphVec4.fromBufferAttribute( morphColor, j );
  12229. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12230. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12231. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12232. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12233. }
  12234. }
  12235. }
  12236. entry = {
  12237. count: morphTargetsCount,
  12238. texture: bufferTexture,
  12239. stride: vertexDataCount,
  12240. size: new Vector2( width, height )
  12241. };
  12242. _morphTextures.set( geometry, entry );
  12243. function disposeTexture() {
  12244. bufferTexture.dispose();
  12245. _morphTextures.delete( geometry );
  12246. geometry.removeEventListener( 'dispose', disposeTexture );
  12247. }
  12248. geometry.addEventListener( 'dispose', disposeTexture );
  12249. }
  12250. return entry;
  12251. }
  12252. /**
  12253. * This node implements the vertex transformation shader logic which is required
  12254. * for morph target animation.
  12255. *
  12256. * @augments Node
  12257. */
  12258. class MorphNode extends Node {
  12259. static get type() {
  12260. return 'MorphNode';
  12261. }
  12262. /**
  12263. * Constructs a new morph node.
  12264. *
  12265. * @param {Mesh} mesh - The mesh holding the morph targets.
  12266. */
  12267. constructor( mesh ) {
  12268. super( 'void' );
  12269. /**
  12270. * The mesh holding the morph targets.
  12271. *
  12272. * @type {Mesh}
  12273. */
  12274. this.mesh = mesh;
  12275. /**
  12276. * A uniform node which represents the morph base influence value.
  12277. *
  12278. * @type {UniformNode<float>}
  12279. */
  12280. this.morphBaseInfluence = uniform( 1 );
  12281. /**
  12282. * The update type overwritten since morph nodes are updated per object.
  12283. *
  12284. * @type {string}
  12285. */
  12286. this.updateType = NodeUpdateType.OBJECT;
  12287. }
  12288. /**
  12289. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12290. *
  12291. * @param {NodeBuilder} builder - The current node builder.
  12292. */
  12293. setup( builder ) {
  12294. const { geometry } = builder;
  12295. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12296. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12297. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12298. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12299. // nodes
  12300. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12301. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12302. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12303. const width = int( size.width );
  12304. Loop( morphTargetsCount, ( { i } ) => {
  12305. const influence = float( 0 ).toVar();
  12306. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12307. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12308. } else {
  12309. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12310. }
  12311. If( influence.notEqual( 0 ), () => {
  12312. if ( hasMorphPosition === true ) {
  12313. positionLocal.addAssign( getMorph( {
  12314. bufferMap,
  12315. influence,
  12316. stride,
  12317. width,
  12318. depth: i,
  12319. offset: int( 0 )
  12320. } ) );
  12321. }
  12322. if ( hasMorphNormals === true ) {
  12323. normalLocal.addAssign( getMorph( {
  12324. bufferMap,
  12325. influence,
  12326. stride,
  12327. width,
  12328. depth: i,
  12329. offset: int( 1 )
  12330. } ) );
  12331. }
  12332. } );
  12333. } );
  12334. }
  12335. /**
  12336. * Updates the state of the morphed mesh by updating the base influence.
  12337. *
  12338. * @param {NodeFrame} frame - The current node frame.
  12339. */
  12340. update( /*frame*/ ) {
  12341. const morphBaseInfluence = this.morphBaseInfluence;
  12342. if ( this.mesh.geometry.morphTargetsRelative ) {
  12343. morphBaseInfluence.value = 1;
  12344. } else {
  12345. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12346. }
  12347. }
  12348. }
  12349. /**
  12350. * TSL function for creating a morph node.
  12351. *
  12352. * @tsl
  12353. * @function
  12354. * @param {Mesh} mesh - The mesh holding the morph targets.
  12355. * @returns {MorphNode}
  12356. */
  12357. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12358. /**
  12359. * Base class for lighting nodes.
  12360. *
  12361. * @augments Node
  12362. */
  12363. class LightingNode extends Node {
  12364. static get type() {
  12365. return 'LightingNode';
  12366. }
  12367. /**
  12368. * Constructs a new lighting node.
  12369. */
  12370. constructor() {
  12371. super( 'vec3' );
  12372. /**
  12373. * This flag can be used for type testing.
  12374. *
  12375. * @type {boolean}
  12376. * @readonly
  12377. * @default true
  12378. */
  12379. this.isLightingNode = true;
  12380. }
  12381. }
  12382. /**
  12383. * A generic class that can be used by nodes which contribute
  12384. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12385. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12386. *
  12387. * @augments LightingNode
  12388. */
  12389. class AONode extends LightingNode {
  12390. static get type() {
  12391. return 'AONode';
  12392. }
  12393. /**
  12394. * Constructs a new AO node.
  12395. *
  12396. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12397. */
  12398. constructor( aoNode = null ) {
  12399. super();
  12400. /**
  12401. * The ambient occlusion node.
  12402. *
  12403. * @type {?Node<float>}
  12404. * @default null
  12405. */
  12406. this.aoNode = aoNode;
  12407. }
  12408. setup( builder ) {
  12409. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12410. }
  12411. }
  12412. /**
  12413. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12414. * by adding lighting specific context data. It represents the runtime context of
  12415. * {@link LightsNode}.
  12416. *
  12417. * @augments ContextNode
  12418. */
  12419. class LightingContextNode extends ContextNode {
  12420. static get type() {
  12421. return 'LightingContextNode';
  12422. }
  12423. /**
  12424. * Constructs a new lighting context node.
  12425. *
  12426. * @param {LightsNode} lightsNode - The lights node.
  12427. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12428. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12429. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12430. */
  12431. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12432. super( lightsNode );
  12433. /**
  12434. * The current lighting model.
  12435. *
  12436. * @type {?LightingModel}
  12437. * @default null
  12438. */
  12439. this.lightingModel = lightingModel;
  12440. /**
  12441. * A backdrop node.
  12442. *
  12443. * @type {?Node<vec3>}
  12444. * @default null
  12445. */
  12446. this.backdropNode = backdropNode;
  12447. /**
  12448. * A backdrop alpha node.
  12449. *
  12450. * @type {?Node<float>}
  12451. * @default null
  12452. */
  12453. this.backdropAlphaNode = backdropAlphaNode;
  12454. this._value = null;
  12455. }
  12456. /**
  12457. * Returns a lighting context object.
  12458. *
  12459. * @return {{
  12460. * radiance: Node<vec3>,
  12461. * irradiance: Node<vec3>,
  12462. * iblIrradiance: Node<vec3>,
  12463. * ambientOcclusion: Node<float>,
  12464. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12465. * backdrop: Node<vec3>,
  12466. * backdropAlpha: Node<float>
  12467. * }} The lighting context object.
  12468. */
  12469. getContext() {
  12470. const { backdropNode, backdropAlphaNode } = this;
  12471. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12472. directSpecular = vec3().toVar( 'directSpecular' ),
  12473. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12474. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12475. const reflectedLight = {
  12476. directDiffuse,
  12477. directSpecular,
  12478. indirectDiffuse,
  12479. indirectSpecular
  12480. };
  12481. const context = {
  12482. radiance: vec3().toVar( 'radiance' ),
  12483. irradiance: vec3().toVar( 'irradiance' ),
  12484. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12485. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12486. reflectedLight,
  12487. backdrop: backdropNode,
  12488. backdropAlpha: backdropAlphaNode
  12489. };
  12490. return context;
  12491. }
  12492. setup( builder ) {
  12493. this.value = this._value || ( this._value = this.getContext() );
  12494. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  12495. return super.setup( builder );
  12496. }
  12497. }
  12498. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  12499. /**
  12500. * A generic class that can be used by nodes which contribute
  12501. * irradiance to the scene. E.g. a light map node can be used
  12502. * as input for this module. Used in {@link NodeMaterial}.
  12503. *
  12504. * @augments LightingNode
  12505. */
  12506. class IrradianceNode extends LightingNode {
  12507. static get type() {
  12508. return 'IrradianceNode';
  12509. }
  12510. /**
  12511. * Constructs a new irradiance node.
  12512. *
  12513. * @param {Node<vec3>} node - A node contributing irradiance.
  12514. */
  12515. constructor( node ) {
  12516. super();
  12517. /**
  12518. * A node contributing irradiance.
  12519. *
  12520. * @type {Node<vec3>}
  12521. */
  12522. this.node = node;
  12523. }
  12524. setup( builder ) {
  12525. builder.context.irradiance.addAssign( this.node );
  12526. }
  12527. }
  12528. const _size$4 = /*@__PURE__*/ new Vector2();
  12529. /**
  12530. * A special type of texture node which represents the data of the current viewport
  12531. * as a texture. The module extracts data from the current bound framebuffer with
  12532. * a copy operation so no extra render pass is required to produce the texture data
  12533. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  12534. * variety of effects like refractive or transmissive materials.
  12535. *
  12536. * @augments TextureNode
  12537. */
  12538. class ViewportTextureNode extends TextureNode {
  12539. static get type() {
  12540. return 'ViewportTextureNode';
  12541. }
  12542. /**
  12543. * Constructs a new viewport texture node.
  12544. *
  12545. * @param {Node} [uvNode=screenUV] - The uv node.
  12546. * @param {?Node} [levelNode=null] - The level node.
  12547. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12548. */
  12549. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12550. let defaultFramebuffer = null;
  12551. if ( framebufferTexture === null ) {
  12552. defaultFramebuffer = new FramebufferTexture();
  12553. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  12554. framebufferTexture = defaultFramebuffer;
  12555. } else {
  12556. defaultFramebuffer = framebufferTexture;
  12557. }
  12558. super( framebufferTexture, uvNode, levelNode );
  12559. /**
  12560. * Whether to generate mipmaps or not.
  12561. *
  12562. * @type {boolean}
  12563. * @default false
  12564. */
  12565. this.generateMipmaps = false;
  12566. /**
  12567. * The reference framebuffer texture. This is used to store the framebuffer texture
  12568. * for the current render target. If the render target changes, a new framebuffer texture
  12569. * is created automatically.
  12570. *
  12571. * @type {FramebufferTexture}
  12572. * @default null
  12573. */
  12574. this.defaultFramebuffer = defaultFramebuffer;
  12575. /**
  12576. * This flag can be used for type testing.
  12577. *
  12578. * @type {boolean}
  12579. * @readonly
  12580. * @default true
  12581. */
  12582. this.isOutputTextureNode = true;
  12583. /**
  12584. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  12585. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  12586. *
  12587. * @type {string}
  12588. * @default 'frame'
  12589. */
  12590. this.updateBeforeType = NodeUpdateType.FRAME;
  12591. /**
  12592. * The framebuffer texture for the current renderer context.
  12593. *
  12594. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  12595. * @private
  12596. */
  12597. this._cacheTextures = new WeakMap();
  12598. }
  12599. /**
  12600. * This methods returns a texture for the given render target reference.
  12601. *
  12602. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  12603. * for different render contexts.
  12604. *
  12605. * @param {?RenderTarget} [reference=null] - The render target reference.
  12606. * @return {Texture} The framebuffer texture.
  12607. */
  12608. getTextureForReference( reference = null ) {
  12609. let defaultFramebuffer;
  12610. let cacheTextures;
  12611. if ( this.referenceNode ) {
  12612. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  12613. cacheTextures = this.referenceNode._cacheTextures;
  12614. } else {
  12615. defaultFramebuffer = this.defaultFramebuffer;
  12616. cacheTextures = this._cacheTextures;
  12617. }
  12618. if ( reference === null ) {
  12619. return defaultFramebuffer;
  12620. }
  12621. if ( cacheTextures.has( reference ) === false ) {
  12622. const framebufferTexture = defaultFramebuffer.clone();
  12623. cacheTextures.set( reference, framebufferTexture );
  12624. }
  12625. return cacheTextures.get( reference );
  12626. }
  12627. updateReference( frame ) {
  12628. const renderTarget = frame.renderer.getRenderTarget();
  12629. this.value = this.getTextureForReference( renderTarget );
  12630. return this.value;
  12631. }
  12632. updateBefore( frame ) {
  12633. const renderer = frame.renderer;
  12634. const renderTarget = renderer.getRenderTarget();
  12635. if ( renderTarget === null ) {
  12636. renderer.getDrawingBufferSize( _size$4 );
  12637. } else {
  12638. _size$4.set( renderTarget.width, renderTarget.height );
  12639. }
  12640. //
  12641. const framebufferTexture = this.getTextureForReference( renderTarget );
  12642. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  12643. framebufferTexture.image.width = _size$4.width;
  12644. framebufferTexture.image.height = _size$4.height;
  12645. framebufferTexture.needsUpdate = true;
  12646. }
  12647. //
  12648. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12649. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12650. renderer.copyFramebufferToTexture( framebufferTexture );
  12651. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12652. }
  12653. clone() {
  12654. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12655. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12656. return viewportTextureNode;
  12657. }
  12658. }
  12659. /**
  12660. * TSL function for creating a viewport texture node.
  12661. *
  12662. * @tsl
  12663. * @function
  12664. * @param {?Node} [uvNode=screenUV] - The uv node.
  12665. * @param {?Node} [levelNode=null] - The level node.
  12666. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12667. * @returns {ViewportTextureNode}
  12668. */
  12669. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12670. /**
  12671. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12672. *
  12673. * @tsl
  12674. * @function
  12675. * @param {?Node} [uvNode=screenUV] - The uv node.
  12676. * @param {?Node} [levelNode=null] - The level node.
  12677. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12678. * @returns {ViewportTextureNode}
  12679. */
  12680. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12681. let _sharedDepthbuffer = null;
  12682. /**
  12683. * Represents the depth of the current viewport as a texture. This module
  12684. * can be used in combination with viewport texture to achieve effects
  12685. * that require depth evaluation.
  12686. *
  12687. * @augments ViewportTextureNode
  12688. */
  12689. class ViewportDepthTextureNode extends ViewportTextureNode {
  12690. static get type() {
  12691. return 'ViewportDepthTextureNode';
  12692. }
  12693. /**
  12694. * Constructs a new viewport depth texture node.
  12695. *
  12696. * @param {Node} [uvNode=screenUV] - The uv node.
  12697. * @param {?Node} [levelNode=null] - The level node.
  12698. */
  12699. constructor( uvNode = screenUV, levelNode = null ) {
  12700. if ( _sharedDepthbuffer === null ) {
  12701. _sharedDepthbuffer = new DepthTexture();
  12702. }
  12703. super( uvNode, levelNode, _sharedDepthbuffer );
  12704. }
  12705. /**
  12706. * Overwritten so the method always returns the unique shared
  12707. * depth texture.
  12708. *
  12709. * @return {DepthTexture} The shared depth texture.
  12710. */
  12711. getTextureForReference() {
  12712. return _sharedDepthbuffer;
  12713. }
  12714. }
  12715. /**
  12716. * TSL function for a viewport depth texture node.
  12717. *
  12718. * @tsl
  12719. * @function
  12720. * @param {?Node} [uvNode=screenUV] - The uv node.
  12721. * @param {?Node} [levelNode=null] - The level node.
  12722. * @returns {ViewportDepthTextureNode}
  12723. */
  12724. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12725. /**
  12726. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12727. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12728. * fragment or for depth evaluation purposes.
  12729. *
  12730. * @augments Node
  12731. */
  12732. class ViewportDepthNode extends Node {
  12733. static get type() {
  12734. return 'ViewportDepthNode';
  12735. }
  12736. /**
  12737. * Constructs a new viewport depth node.
  12738. *
  12739. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12740. * @param {?Node} [valueNode=null] - The value node.
  12741. */
  12742. constructor( scope, valueNode = null ) {
  12743. super( 'float' );
  12744. /**
  12745. * The node behaves differently depending on which scope is selected.
  12746. *
  12747. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12748. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12749. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12750. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12751. *
  12752. * @type {('depth'|'depthBase'|'linearDepth')}
  12753. */
  12754. this.scope = scope;
  12755. /**
  12756. * Can be used to define a custom depth value.
  12757. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12758. *
  12759. * @type {?Node}
  12760. * @default null
  12761. */
  12762. this.valueNode = valueNode;
  12763. /**
  12764. * This flag can be used for type testing.
  12765. *
  12766. * @type {boolean}
  12767. * @readonly
  12768. * @default true
  12769. */
  12770. this.isViewportDepthNode = true;
  12771. }
  12772. generate( builder ) {
  12773. const { scope } = this;
  12774. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12775. return builder.getFragDepth();
  12776. }
  12777. return super.generate( builder );
  12778. }
  12779. setup( { camera } ) {
  12780. const { scope } = this;
  12781. const value = this.valueNode;
  12782. let node = null;
  12783. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12784. if ( value !== null ) {
  12785. node = depthBase().assign( value );
  12786. }
  12787. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12788. if ( camera.isPerspectiveCamera ) {
  12789. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12790. } else {
  12791. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12792. }
  12793. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12794. if ( value !== null ) {
  12795. if ( camera.isPerspectiveCamera ) {
  12796. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12797. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12798. } else {
  12799. node = value;
  12800. }
  12801. } else {
  12802. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12803. }
  12804. }
  12805. return node;
  12806. }
  12807. }
  12808. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12809. ViewportDepthNode.DEPTH = 'depth';
  12810. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12811. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12812. /**
  12813. * TSL function for converting a viewZ value to an orthographic depth value.
  12814. *
  12815. * @tsl
  12816. * @function
  12817. * @param {Node<float>} viewZ - The viewZ node.
  12818. * @param {Node<float>} near - The camera's near value.
  12819. * @param {Node<float>} far - The camera's far value.
  12820. * @returns {Node<float>}
  12821. */
  12822. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12823. /**
  12824. * TSL function for converting an orthographic depth value to a viewZ value.
  12825. *
  12826. * @tsl
  12827. * @function
  12828. * @param {Node<float>} depth - The orthographic depth.
  12829. * @param {Node<float>} near - The camera's near value.
  12830. * @param {Node<float>} far - The camera's far value.
  12831. * @returns {Node<float>}
  12832. */
  12833. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12834. /**
  12835. * TSL function for converting a viewZ value to a perspective depth value.
  12836. *
  12837. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12838. *
  12839. * @tsl
  12840. * @function
  12841. * @param {Node<float>} viewZ - The viewZ node.
  12842. * @param {Node<float>} near - The camera's near value.
  12843. * @param {Node<float>} far - The camera's far value.
  12844. * @returns {Node<float>}
  12845. */
  12846. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12847. /**
  12848. * TSL function for converting a perspective depth value to a viewZ value.
  12849. *
  12850. * @tsl
  12851. * @function
  12852. * @param {Node<float>} depth - The perspective depth.
  12853. * @param {Node<float>} near - The camera's near value.
  12854. * @param {Node<float>} far - The camera's far value.
  12855. * @returns {Node<float>}
  12856. */
  12857. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12858. /**
  12859. * TSL function for converting a viewZ value to a logarithmic depth value.
  12860. *
  12861. * @tsl
  12862. * @function
  12863. * @param {Node<float>} viewZ - The viewZ node.
  12864. * @param {Node<float>} near - The camera's near value.
  12865. * @param {Node<float>} far - The camera's far value.
  12866. * @returns {Node<float>}
  12867. */
  12868. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12869. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12870. // The final logarithmic depth formula used here is adapted from one described in an
  12871. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12872. // which was an improvement upon an earlier formula one described in an
  12873. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12874. // Ulrich's formula is the following:
  12875. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12876. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12877. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12878. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12879. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12880. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12881. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12882. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12883. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12884. // Outerra eventually made another improvement to their original "C-constant" variant,
  12885. // but it still does not incorporate the camera near plane (for this version,
  12886. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12887. // Here we make 4 changes to Ulrich's formula:
  12888. // 1. Clamp the camera near plane so we don't divide by 0.
  12889. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12890. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12891. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12892. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12893. // so we do the same here, hence the 'viewZ.negate()' call.
  12894. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12895. near = near.max( 1e-6 ).toVar();
  12896. const numerator = log2( viewZ.negate().div( near ) );
  12897. const denominator = log2( far.div( near ) );
  12898. return numerator.div( denominator );
  12899. };
  12900. /**
  12901. * TSL function for converting a logarithmic depth value to a viewZ value.
  12902. *
  12903. * @tsl
  12904. * @function
  12905. * @param {Node<float>} depth - The logarithmic depth.
  12906. * @param {Node<float>} near - The camera's near value.
  12907. * @param {Node<float>} far - The camera's far value.
  12908. * @returns {Node<float>}
  12909. */
  12910. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12911. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12912. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12913. // a negative viewZ).
  12914. const exponent = depth.mul( log( far.div( near ) ) );
  12915. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12916. };
  12917. /**
  12918. * TSL function for defining a value for the current fragment's depth.
  12919. *
  12920. * @tsl
  12921. * @function
  12922. * @param {Node<float>} value - The depth value to set.
  12923. * @returns {ViewportDepthNode<float>}
  12924. */
  12925. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12926. /**
  12927. * TSL object that represents the depth value for the current fragment.
  12928. *
  12929. * @tsl
  12930. * @type {ViewportDepthNode}
  12931. */
  12932. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12933. /**
  12934. * TSL function for converting a perspective depth value to linear depth.
  12935. *
  12936. * @tsl
  12937. * @function
  12938. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12939. * @returns {ViewportDepthNode<float>}
  12940. */
  12941. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12942. /**
  12943. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12944. *
  12945. * @tsl
  12946. * @type {ViewportDepthNode}
  12947. */
  12948. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12949. depth.assign = ( value ) => depthBase( value );
  12950. /**
  12951. * This node is used in {@link NodeMaterial} to setup the clipping
  12952. * which can happen hardware-accelerated (if supported) and optionally
  12953. * use alpha-to-coverage for anti-aliasing clipped edges.
  12954. *
  12955. * @augments Node
  12956. */
  12957. class ClippingNode extends Node {
  12958. static get type() {
  12959. return 'ClippingNode';
  12960. }
  12961. /**
  12962. * Constructs a new clipping node.
  12963. *
  12964. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12965. * the selected scope influences the behavior of the node and what type of code is generated.
  12966. */
  12967. constructor( scope = ClippingNode.DEFAULT ) {
  12968. super();
  12969. /**
  12970. * The node's scope. Similar to other nodes, the selected scope influences
  12971. * the behavior of the node and what type of code is generated.
  12972. *
  12973. * @type {('default'|'hardware'|'alphaToCoverage')}
  12974. */
  12975. this.scope = scope;
  12976. }
  12977. /**
  12978. * Setups the node depending on the selected scope.
  12979. *
  12980. * @param {NodeBuilder} builder - The current node builder.
  12981. * @return {Node} The result node.
  12982. */
  12983. setup( builder ) {
  12984. super.setup( builder );
  12985. const clippingContext = builder.clippingContext;
  12986. const { intersectionPlanes, unionPlanes } = clippingContext;
  12987. this.hardwareClipping = builder.material.hardwareClipping;
  12988. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12989. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12990. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12991. return this.setupHardwareClipping( unionPlanes, builder );
  12992. } else {
  12993. return this.setupDefault( intersectionPlanes, unionPlanes );
  12994. }
  12995. }
  12996. /**
  12997. * Setups alpha to coverage.
  12998. *
  12999. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13000. * @param {Array<Vector4>} unionPlanes - The union planes.
  13001. * @return {Node} The result node.
  13002. */
  13003. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13004. return Fn( () => {
  13005. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13006. const distanceGradient = float().toVar( 'distanceToGradient' );
  13007. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13008. const numUnionPlanes = unionPlanes.length;
  13009. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13010. const clippingPlanes = uniformArray( unionPlanes );
  13011. Loop( numUnionPlanes, ( { i } ) => {
  13012. const plane = clippingPlanes.element( i );
  13013. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13014. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13015. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13016. } );
  13017. }
  13018. const numIntersectionPlanes = intersectionPlanes.length;
  13019. if ( numIntersectionPlanes > 0 ) {
  13020. const clippingPlanes = uniformArray( intersectionPlanes );
  13021. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13022. Loop( numIntersectionPlanes, ( { i } ) => {
  13023. const plane = clippingPlanes.element( i );
  13024. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13025. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13026. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13027. } );
  13028. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13029. }
  13030. diffuseColor.a.mulAssign( clipOpacity );
  13031. diffuseColor.a.equal( 0.0 ).discard();
  13032. } )();
  13033. }
  13034. /**
  13035. * Setups the default clipping.
  13036. *
  13037. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13038. * @param {Array<Vector4>} unionPlanes - The union planes.
  13039. * @return {Node} The result node.
  13040. */
  13041. setupDefault( intersectionPlanes, unionPlanes ) {
  13042. return Fn( () => {
  13043. const numUnionPlanes = unionPlanes.length;
  13044. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13045. const clippingPlanes = uniformArray( unionPlanes );
  13046. Loop( numUnionPlanes, ( { i } ) => {
  13047. const plane = clippingPlanes.element( i );
  13048. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13049. } );
  13050. }
  13051. const numIntersectionPlanes = intersectionPlanes.length;
  13052. if ( numIntersectionPlanes > 0 ) {
  13053. const clippingPlanes = uniformArray( intersectionPlanes );
  13054. const clipped = bool( true ).toVar( 'clipped' );
  13055. Loop( numIntersectionPlanes, ( { i } ) => {
  13056. const plane = clippingPlanes.element( i );
  13057. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13058. } );
  13059. clipped.discard();
  13060. }
  13061. } )();
  13062. }
  13063. /**
  13064. * Setups hardware clipping.
  13065. *
  13066. * @param {Array<Vector4>} unionPlanes - The union planes.
  13067. * @param {NodeBuilder} builder - The current node builder.
  13068. * @return {Node} The result node.
  13069. */
  13070. setupHardwareClipping( unionPlanes, builder ) {
  13071. const numUnionPlanes = unionPlanes.length;
  13072. builder.enableHardwareClipping( numUnionPlanes );
  13073. return Fn( () => {
  13074. const clippingPlanes = uniformArray( unionPlanes );
  13075. const hw_clip_distances = builtin( builder.getClipDistance() );
  13076. Loop( numUnionPlanes, ( { i } ) => {
  13077. const plane = clippingPlanes.element( i );
  13078. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13079. hw_clip_distances.element( i ).assign( distance );
  13080. } );
  13081. } )();
  13082. }
  13083. }
  13084. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13085. ClippingNode.DEFAULT = 'default';
  13086. ClippingNode.HARDWARE = 'hardware';
  13087. /**
  13088. * TSL function for setting up the default clipping logic.
  13089. *
  13090. * @tsl
  13091. * @function
  13092. * @returns {ClippingNode}
  13093. */
  13094. const clipping = () => nodeObject( new ClippingNode() );
  13095. /**
  13096. * TSL function for setting up alpha to coverage.
  13097. *
  13098. * @tsl
  13099. * @function
  13100. * @returns {ClippingNode}
  13101. */
  13102. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13103. /**
  13104. * TSL function for setting up hardware-based clipping.
  13105. *
  13106. * @tsl
  13107. * @function
  13108. * @returns {ClippingNode}
  13109. */
  13110. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13111. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13112. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13113. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13114. 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 ) ) ) ) ) );
  13115. } );
  13116. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13117. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13118. } );
  13119. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13120. // Find the discretized derivatives of our coordinates
  13121. const maxDeriv = max$1(
  13122. length( dFdx( position.xyz ) ),
  13123. length( dFdy( position.xyz ) )
  13124. );
  13125. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13126. // Find two nearest log-discretized noise scales
  13127. const pixScales = vec2(
  13128. exp2( floor( log2( pixScale ) ) ),
  13129. exp2( ceil( log2( pixScale ) ) )
  13130. );
  13131. // Compute alpha thresholds at our two noise scales
  13132. const alpha = vec2(
  13133. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13134. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13135. );
  13136. // Factor to interpolate lerp with
  13137. const lerpFactor = fract( log2( pixScale ) );
  13138. // Interpolate alpha threshold from noise at two scales
  13139. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13140. // Pass into CDF to compute uniformly distrib threshold
  13141. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13142. const cases = vec3(
  13143. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13144. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13145. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13146. // Find our final, uniformly distributed alpha threshold (ατ)
  13147. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13148. // Avoids ατ == 0. Could also do ατ =1-ατ
  13149. return clamp( threshold, 1.0e-6, 1.0 );
  13150. } ).setLayout( {
  13151. name: 'getAlphaHashThreshold',
  13152. type: 'float',
  13153. inputs: [
  13154. { name: 'position', type: 'vec3' }
  13155. ]
  13156. } );
  13157. /**
  13158. * An attribute node for representing vertex colors.
  13159. *
  13160. * @augments AttributeNode
  13161. */
  13162. class VertexColorNode extends AttributeNode {
  13163. static get type() {
  13164. return 'VertexColorNode';
  13165. }
  13166. /**
  13167. * Constructs a new vertex color node.
  13168. *
  13169. * @param {number} index - The attribute index.
  13170. */
  13171. constructor( index ) {
  13172. super( null, 'vec4' );
  13173. /**
  13174. * This flag can be used for type testing.
  13175. *
  13176. * @type {boolean}
  13177. * @readonly
  13178. * @default true
  13179. */
  13180. this.isVertexColorNode = true;
  13181. /**
  13182. * The attribute index to enable more than one sets of vertex colors.
  13183. *
  13184. * @type {number}
  13185. * @default 0
  13186. */
  13187. this.index = index;
  13188. }
  13189. /**
  13190. * Overwrites the default implementation by honoring the attribute index.
  13191. *
  13192. * @param {NodeBuilder} builder - The current node builder.
  13193. * @return {string} The attribute name.
  13194. */
  13195. getAttributeName( /*builder*/ ) {
  13196. const index = this.index;
  13197. return 'color' + ( index > 0 ? index : '' );
  13198. }
  13199. generate( builder ) {
  13200. const attributeName = this.getAttributeName( builder );
  13201. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13202. let result;
  13203. if ( geometryAttribute === true ) {
  13204. result = super.generate( builder );
  13205. } else {
  13206. // Vertex color fallback should be white
  13207. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13208. }
  13209. return result;
  13210. }
  13211. serialize( data ) {
  13212. super.serialize( data );
  13213. data.index = this.index;
  13214. }
  13215. deserialize( data ) {
  13216. super.deserialize( data );
  13217. this.index = data.index;
  13218. }
  13219. }
  13220. /**
  13221. * TSL function for creating a reference node.
  13222. *
  13223. * @tsl
  13224. * @function
  13225. * @param {number} [index=0] - The attribute index.
  13226. * @returns {VertexColorNode}
  13227. */
  13228. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13229. /**
  13230. * Represents a "Color Burn" blend mode.
  13231. *
  13232. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13233. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13234. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13235. *
  13236. * @tsl
  13237. * @function
  13238. * @param {Node<vec3>} base - The base color.
  13239. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13240. * @return {Node<vec3>} The result.
  13241. */
  13242. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13243. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13244. } ).setLayout( {
  13245. name: 'blendBurn',
  13246. type: 'vec3',
  13247. inputs: [
  13248. { name: 'base', type: 'vec3' },
  13249. { name: 'blend', type: 'vec3' }
  13250. ]
  13251. } );
  13252. /**
  13253. * Represents a "Color Dodge" blend mode.
  13254. *
  13255. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13256. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13257. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13258. *
  13259. * @tsl
  13260. * @function
  13261. * @param {Node<vec3>} base - The base color.
  13262. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13263. * @return {Node<vec3>} The result.
  13264. */
  13265. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13266. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13267. } ).setLayout( {
  13268. name: 'blendDodge',
  13269. type: 'vec3',
  13270. inputs: [
  13271. { name: 'base', type: 'vec3' },
  13272. { name: 'blend', type: 'vec3' }
  13273. ]
  13274. } );
  13275. /**
  13276. * Represents a "Screen" blend mode.
  13277. *
  13278. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13279. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13280. * effects.
  13281. *
  13282. * @tsl
  13283. * @function
  13284. * @param {Node<vec3>} base - The base color.
  13285. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13286. * @return {Node<vec3>} The result.
  13287. */
  13288. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13289. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13290. } ).setLayout( {
  13291. name: 'blendScreen',
  13292. type: 'vec3',
  13293. inputs: [
  13294. { name: 'base', type: 'vec3' },
  13295. { name: 'blend', type: 'vec3' }
  13296. ]
  13297. } );
  13298. /**
  13299. * Represents a "Overlay" blend mode.
  13300. *
  13301. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13302. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13303. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13304. *
  13305. * @tsl
  13306. * @function
  13307. * @param {Node<vec3>} base - The base color.
  13308. * @param {Node<vec3>} blend - The blend color
  13309. * @return {Node<vec3>} The result.
  13310. */
  13311. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13312. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13313. } ).setLayout( {
  13314. name: 'blendOverlay',
  13315. type: 'vec3',
  13316. inputs: [
  13317. { name: 'base', type: 'vec3' },
  13318. { name: 'blend', type: 'vec3' }
  13319. ]
  13320. } );
  13321. /**
  13322. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13323. * It assumes both input colors have non-premultiplied alpha.
  13324. *
  13325. * @tsl
  13326. * @function
  13327. * @param {Node<vec4>} base - The base color.
  13328. * @param {Node<vec4>} blend - The blend color
  13329. * @return {Node<vec4>} The result.
  13330. */
  13331. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13332. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13333. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13334. } ).setLayout( {
  13335. name: 'blendColor',
  13336. type: 'vec4',
  13337. inputs: [
  13338. { name: 'base', type: 'vec4' },
  13339. { name: 'blend', type: 'vec4' }
  13340. ]
  13341. } );
  13342. /**
  13343. * Premultiplies the RGB channels of a color by its alpha channel.
  13344. *
  13345. * This function is useful for converting a non-premultiplied alpha color
  13346. * into a premultiplied alpha format, where the RGB values are scaled
  13347. * by the alpha value. Premultiplied alpha is often used in graphics
  13348. * rendering for certain operations, such as compositing and image processing.
  13349. *
  13350. * @tsl
  13351. * @function
  13352. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13353. * @return {Node<vec4>} The color with premultiplied alpha.
  13354. */
  13355. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13356. return vec4( color.rgb.mul( color.a ), color.a );
  13357. }, { color: 'vec4', return: 'vec4' } );
  13358. /**
  13359. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13360. *
  13361. * This function is useful for converting a premultiplied alpha color
  13362. * back into a non-premultiplied alpha format, where the RGB values are
  13363. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13364. * rendering for certain operations, such as compositing and image processing.
  13365. *
  13366. * @tsl
  13367. * @function
  13368. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13369. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13370. */
  13371. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13372. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13373. return vec4( color.rgb.div( color.a ), color.a );
  13374. }, { color: 'vec4', return: 'vec4' } );
  13375. // Deprecated
  13376. /**
  13377. * @tsl
  13378. * @function
  13379. * @deprecated since r171. Use {@link blendBurn} instead.
  13380. *
  13381. * @param {...any} params
  13382. * @returns {Function}
  13383. */
  13384. const burn = ( ...params ) => { // @deprecated, r171
  13385. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13386. return blendBurn( params );
  13387. };
  13388. /**
  13389. * @tsl
  13390. * @function
  13391. * @deprecated since r171. Use {@link blendDodge} instead.
  13392. *
  13393. * @param {...any} params
  13394. * @returns {Function}
  13395. */
  13396. const dodge = ( ...params ) => { // @deprecated, r171
  13397. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13398. return blendDodge( params );
  13399. };
  13400. /**
  13401. * @tsl
  13402. * @function
  13403. * @deprecated since r171. Use {@link blendScreen} instead.
  13404. *
  13405. * @param {...any} params
  13406. * @returns {Function}
  13407. */
  13408. const screen = ( ...params ) => { // @deprecated, r171
  13409. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13410. return blendScreen( params );
  13411. };
  13412. /**
  13413. * @tsl
  13414. * @function
  13415. * @deprecated since r171. Use {@link blendOverlay} instead.
  13416. *
  13417. * @param {...any} params
  13418. * @returns {Function}
  13419. */
  13420. const overlay = ( ...params ) => { // @deprecated, r171
  13421. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13422. return blendOverlay( params );
  13423. };
  13424. /**
  13425. * Base class for all node materials.
  13426. *
  13427. * @augments Material
  13428. */
  13429. class NodeMaterial extends Material {
  13430. static get type() {
  13431. return 'NodeMaterial';
  13432. }
  13433. /**
  13434. * Represents the type of the node material.
  13435. *
  13436. * @type {string}
  13437. */
  13438. get type() {
  13439. return this.constructor.type;
  13440. }
  13441. set type( _value ) { /* */ }
  13442. /**
  13443. * Constructs a new node material.
  13444. */
  13445. constructor() {
  13446. super();
  13447. /**
  13448. * This flag can be used for type testing.
  13449. *
  13450. * @type {boolean}
  13451. * @readonly
  13452. * @default true
  13453. */
  13454. this.isNodeMaterial = true;
  13455. /**
  13456. * Whether this material is affected by fog or not.
  13457. *
  13458. * @type {boolean}
  13459. * @default true
  13460. */
  13461. this.fog = true;
  13462. /**
  13463. * Whether this material is affected by lights or not.
  13464. *
  13465. * @type {boolean}
  13466. * @default false
  13467. */
  13468. this.lights = false;
  13469. /**
  13470. * Whether this material uses hardware clipping or not.
  13471. * This property is managed by the engine and should not be
  13472. * modified by apps.
  13473. *
  13474. * @type {boolean}
  13475. * @default false
  13476. */
  13477. this.hardwareClipping = false;
  13478. /**
  13479. * Node materials which set their `lights` property to `true`
  13480. * are affected by all lights of the scene. Sometimes selective
  13481. * lighting is wanted which means only _some_ lights in the scene
  13482. * affect a material. This can be achieved by creating an instance
  13483. * of {@link LightsNode} with a list of selective
  13484. * lights and assign the node to this property.
  13485. *
  13486. * ```js
  13487. * const customLightsNode = lights( [ light1, light2 ] );
  13488. * material.lightsNode = customLightsNode;
  13489. * ```
  13490. *
  13491. * @type {?LightsNode}
  13492. * @default null
  13493. */
  13494. this.lightsNode = null;
  13495. /**
  13496. * The environment of node materials can be defined by an environment
  13497. * map assigned to the `envMap` property or by `Scene.environment`
  13498. * if the node material is a PBR material. This node property allows to overwrite
  13499. * the default behavior and define the environment with a custom node.
  13500. *
  13501. * ```js
  13502. * material.envNode = pmremTexture( renderTarget.texture );
  13503. * ```
  13504. *
  13505. * @type {?Node<vec3>}
  13506. * @default null
  13507. */
  13508. this.envNode = null;
  13509. /**
  13510. * The lighting of node materials might be influenced by ambient occlusion.
  13511. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13512. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13513. * the default and define the ambient occlusion with a custom node instead.
  13514. *
  13515. * If you don't want to overwrite the diffuse color but modify the existing
  13516. * values instead, use {@link materialAO}.
  13517. *
  13518. * @type {?Node<float>}
  13519. * @default null
  13520. */
  13521. this.aoNode = null;
  13522. /**
  13523. * The diffuse color of node materials is by default inferred from the
  13524. * `color` and `map` properties. This node property allows to overwrite the default
  13525. * and define the diffuse color with a node instead.
  13526. *
  13527. * ```js
  13528. * material.colorNode = color( 0xff0000 ); // define red color
  13529. * ```
  13530. *
  13531. * If you don't want to overwrite the diffuse color but modify the existing
  13532. * values instead, use {@link materialColor}.
  13533. *
  13534. * ```js
  13535. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  13536. * ```
  13537. *
  13538. * @type {?Node<vec3>}
  13539. * @default null
  13540. */
  13541. this.colorNode = null;
  13542. /**
  13543. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  13544. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  13545. * and define the normals with a node instead.
  13546. *
  13547. * If you don't want to overwrite the normals but modify the existing values instead,
  13548. * use {@link materialNormal}.
  13549. *
  13550. * @type {?Node<vec3>}
  13551. * @default null
  13552. */
  13553. this.normalNode = null;
  13554. /**
  13555. * The opacity of node materials is by default inferred from the `opacity`
  13556. * and `alphaMap` properties. This node property allows to overwrite the default
  13557. * and define the opacity with a node instead.
  13558. *
  13559. * If you don't want to overwrite the normals but modify the existing
  13560. * value instead, use {@link materialOpacity}.
  13561. *
  13562. * @type {?Node<float>}
  13563. * @default null
  13564. */
  13565. this.opacityNode = null;
  13566. /**
  13567. * This node can be used to implement a variety of filter-like effects. The idea is
  13568. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  13569. * to create an arbitrary effect and then assign the node composition to this property.
  13570. * Everything behind the object using this material will now be affected by a filter.
  13571. *
  13572. * ```js
  13573. * const material = new NodeMaterial()
  13574. * material.transparent = true;
  13575. *
  13576. * // everything behind the object will be monochromatic
  13577. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  13578. * ```
  13579. *
  13580. * Backdrop computations are part of the lighting so only lit materials can use this property.
  13581. *
  13582. * @type {?Node<vec3>}
  13583. * @default null
  13584. */
  13585. this.backdropNode = null;
  13586. /**
  13587. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  13588. *
  13589. * @type {?Node<float>}
  13590. * @default null
  13591. */
  13592. this.backdropAlphaNode = null;
  13593. /**
  13594. * The alpha test of node materials is by default inferred from the `alphaTest`
  13595. * property. This node property allows to overwrite the default and define the
  13596. * alpha test with a node instead.
  13597. *
  13598. * If you don't want to overwrite the alpha test but modify the existing
  13599. * value instead, use {@link materialAlphaTest}.
  13600. *
  13601. * @type {?Node<float>}
  13602. * @default null
  13603. */
  13604. this.alphaTestNode = null;
  13605. /**
  13606. * Discards the fragment if the mask value is `false`.
  13607. *
  13608. * @type {?Node<bool>}
  13609. * @default null
  13610. */
  13611. this.maskNode = null;
  13612. /**
  13613. * The local vertex positions are computed based on multiple factors like the
  13614. * attribute data, morphing or skinning. This node property allows to overwrite
  13615. * the default and define local vertex positions with nodes instead.
  13616. *
  13617. * If you don't want to overwrite the vertex positions but modify the existing
  13618. * values instead, use {@link positionLocal}.
  13619. *
  13620. *```js
  13621. * material.positionNode = positionLocal.add( displace );
  13622. * ```
  13623. *
  13624. * @type {?Node<vec3>}
  13625. * @default null
  13626. */
  13627. this.positionNode = null;
  13628. /**
  13629. * This node property is intended for logic which modifies geometry data once or per animation step.
  13630. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  13631. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  13632. * can be implemented.
  13633. *
  13634. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  13635. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  13636. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  13637. * eventually assigned to `geometryNode`.
  13638. *
  13639. * @type {?Function}
  13640. * @default null
  13641. */
  13642. this.geometryNode = null;
  13643. /**
  13644. * Allows to overwrite depth values in the fragment shader.
  13645. *
  13646. * @type {?Node<float>}
  13647. * @default null
  13648. */
  13649. this.depthNode = null;
  13650. /**
  13651. * Allows to overwrite the position used for shadow map rendering which
  13652. * is by default {@link positionWorld}, the vertex position
  13653. * in world space.
  13654. *
  13655. * @type {?Node<float>}
  13656. * @default null
  13657. */
  13658. this.receivedShadowPositionNode = null;
  13659. /**
  13660. * Allows to overwrite the geometry position used for shadow map projection which
  13661. * is by default {@link positionLocal}, the vertex position in local space.
  13662. *
  13663. * @type {?Node<float>}
  13664. * @default null
  13665. */
  13666. this.castShadowPositionNode = null;
  13667. /**
  13668. * This node can be used to influence how an object using this node material
  13669. * receive shadows.
  13670. *
  13671. * ```js
  13672. * const totalShadows = float( 1 ).toVar();
  13673. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  13674. * totalShadows.mulAssign( shadow );
  13675. * //return float( 1 ); // bypass received shadows
  13676. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  13677. * } );
  13678. *
  13679. * @type {?(Function|FunctionNode<vec4>)}
  13680. * @default null
  13681. */
  13682. this.receivedShadowNode = null;
  13683. /**
  13684. * This node can be used to influence how an object using this node material
  13685. * casts shadows. To apply a color to shadows, you can simply do:
  13686. *
  13687. * ```js
  13688. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  13689. * ```
  13690. *
  13691. * Which can be nice to fake colored shadows of semi-transparent objects. It
  13692. * is also common to use the property with `Fn` function so checks are performed
  13693. * per fragment.
  13694. *
  13695. * ```js
  13696. * materialCustomShadow.castShadowNode = Fn( () => {
  13697. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  13698. * return materialColor;
  13699. * } )();
  13700. * ```
  13701. *
  13702. * @type {?Node<vec4>}
  13703. * @default null
  13704. */
  13705. this.castShadowNode = null;
  13706. /**
  13707. * This node can be used to define the final output of the material.
  13708. *
  13709. * TODO: Explain the differences to `fragmentNode`.
  13710. *
  13711. * @type {?Node<vec4>}
  13712. * @default null
  13713. */
  13714. this.outputNode = null;
  13715. /**
  13716. * MRT configuration is done on renderer or pass level. This node allows to
  13717. * overwrite what values are written into MRT targets on material level. This
  13718. * can be useful for implementing selective FX features that should only affect
  13719. * specific objects.
  13720. *
  13721. * @type {?MRTNode}
  13722. * @default null
  13723. */
  13724. this.mrtNode = null;
  13725. /**
  13726. * This node property can be used if you need complete freedom in implementing
  13727. * the fragment shader. Assigning a node will replace the built-in material
  13728. * logic used in the fragment stage.
  13729. *
  13730. * @type {?Node<vec4>}
  13731. * @default null
  13732. */
  13733. this.fragmentNode = null;
  13734. /**
  13735. * This node property can be used if you need complete freedom in implementing
  13736. * the vertex shader. Assigning a node will replace the built-in material logic
  13737. * used in the vertex stage.
  13738. *
  13739. * @type {?Node<vec4>}
  13740. * @default null
  13741. */
  13742. this.vertexNode = null;
  13743. // Deprecated properties
  13744. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  13745. get: () => {
  13746. return this.receivedShadowPositionNode;
  13747. },
  13748. set: ( value ) => {
  13749. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  13750. this.receivedShadowPositionNode = value;
  13751. }
  13752. } );
  13753. }
  13754. /**
  13755. * Allows to define a custom cache key that influence the material key computation
  13756. * for render objects.
  13757. *
  13758. * @return {string} The custom cache key.
  13759. */
  13760. customProgramCacheKey() {
  13761. return this.type + getCacheKey$1( this );
  13762. }
  13763. /**
  13764. * Builds this material with the given node builder.
  13765. *
  13766. * @param {NodeBuilder} builder - The current node builder.
  13767. */
  13768. build( builder ) {
  13769. this.setup( builder );
  13770. }
  13771. /**
  13772. * Setups a node material observer with the given builder.
  13773. *
  13774. * @param {NodeBuilder} builder - The current node builder.
  13775. * @return {NodeMaterialObserver} The node material observer.
  13776. */
  13777. setupObserver( builder ) {
  13778. return new NodeMaterialObserver( builder );
  13779. }
  13780. /**
  13781. * Setups the vertex and fragment stage of this node material.
  13782. *
  13783. * @param {NodeBuilder} builder - The current node builder.
  13784. */
  13785. setup( builder ) {
  13786. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  13787. builder.context.setupPositionView = () => this.setupPositionView( builder );
  13788. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  13789. const renderer = builder.renderer;
  13790. const renderTarget = renderer.getRenderTarget();
  13791. // < VERTEX STAGE >
  13792. builder.addStack();
  13793. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  13794. const vertexNode = this.vertexNode || mvp;
  13795. builder.stack.outputNode = vertexNode;
  13796. this.setupHardwareClipping( builder );
  13797. if ( this.geometryNode !== null ) {
  13798. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  13799. }
  13800. builder.addFlow( 'vertex', builder.removeStack() );
  13801. // < FRAGMENT STAGE >
  13802. builder.addStack();
  13803. let resultNode;
  13804. const clippingNode = this.setupClipping( builder );
  13805. if ( this.depthWrite === true || this.depthTest === true ) {
  13806. // only write depth if depth buffer is configured
  13807. if ( renderTarget !== null ) {
  13808. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  13809. } else {
  13810. if ( renderer.depth === true ) this.setupDepth( builder );
  13811. }
  13812. }
  13813. if ( this.fragmentNode === null ) {
  13814. this.setupDiffuseColor( builder );
  13815. this.setupVariants( builder );
  13816. const outgoingLightNode = this.setupLighting( builder );
  13817. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  13818. // force unsigned floats - useful for RenderTargets
  13819. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  13820. resultNode = this.setupOutput( builder, basicOutput );
  13821. // OUTPUT NODE
  13822. output.assign( resultNode );
  13823. //
  13824. const isCustomOutput = this.outputNode !== null;
  13825. if ( isCustomOutput ) resultNode = this.outputNode;
  13826. // MRT
  13827. if ( renderTarget !== null ) {
  13828. const mrt = renderer.getMRT();
  13829. const materialMRT = this.mrtNode;
  13830. if ( mrt !== null ) {
  13831. if ( isCustomOutput ) output.assign( resultNode );
  13832. resultNode = mrt;
  13833. if ( materialMRT !== null ) {
  13834. resultNode = mrt.merge( materialMRT );
  13835. }
  13836. } else if ( materialMRT !== null ) {
  13837. resultNode = materialMRT;
  13838. }
  13839. }
  13840. } else {
  13841. let fragmentNode = this.fragmentNode;
  13842. if ( fragmentNode.isOutputStructNode !== true ) {
  13843. fragmentNode = vec4( fragmentNode );
  13844. }
  13845. resultNode = this.setupOutput( builder, fragmentNode );
  13846. }
  13847. builder.stack.outputNode = resultNode;
  13848. builder.addFlow( 'fragment', builder.removeStack() );
  13849. // < OBSERVER >
  13850. builder.observer = this.setupObserver( builder );
  13851. }
  13852. /**
  13853. * Setups the clipping node.
  13854. *
  13855. * @param {NodeBuilder} builder - The current node builder.
  13856. * @return {ClippingNode} The clipping node.
  13857. */
  13858. setupClipping( builder ) {
  13859. if ( builder.clippingContext === null ) return null;
  13860. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  13861. let result = null;
  13862. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  13863. const samples = builder.renderer.samples;
  13864. if ( this.alphaToCoverage && samples > 1 ) {
  13865. // to be added to flow when the color/alpha value has been determined
  13866. result = clippingAlpha();
  13867. } else {
  13868. builder.stack.add( clipping() );
  13869. }
  13870. }
  13871. return result;
  13872. }
  13873. /**
  13874. * Setups the hardware clipping if available on the current device.
  13875. *
  13876. * @param {NodeBuilder} builder - The current node builder.
  13877. */
  13878. setupHardwareClipping( builder ) {
  13879. this.hardwareClipping = false;
  13880. if ( builder.clippingContext === null ) return;
  13881. const candidateCount = builder.clippingContext.unionPlanes.length;
  13882. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  13883. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  13884. builder.stack.add( hardwareClipping() );
  13885. this.hardwareClipping = true;
  13886. }
  13887. return;
  13888. }
  13889. /**
  13890. * Setups the depth of this material.
  13891. *
  13892. * @param {NodeBuilder} builder - The current node builder.
  13893. */
  13894. setupDepth( builder ) {
  13895. const { renderer, camera } = builder;
  13896. // Depth
  13897. let depthNode = this.depthNode;
  13898. if ( depthNode === null ) {
  13899. const mrt = renderer.getMRT();
  13900. if ( mrt && mrt.has( 'depth' ) ) {
  13901. depthNode = mrt.get( 'depth' );
  13902. } else if ( renderer.logarithmicDepthBuffer === true ) {
  13903. if ( camera.isPerspectiveCamera ) {
  13904. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  13905. } else {
  13906. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13907. }
  13908. }
  13909. }
  13910. if ( depthNode !== null ) {
  13911. depth.assign( depthNode ).toStack();
  13912. }
  13913. }
  13914. /**
  13915. * Setups the position node in view space. This method exists
  13916. * so derived node materials can modify the implementation e.g. sprite materials.
  13917. *
  13918. * @param {NodeBuilder} builder - The current node builder.
  13919. * @return {Node<vec3>} The position in view space.
  13920. */
  13921. setupPositionView( /*builder*/ ) {
  13922. return modelViewMatrix.mul( positionLocal ).xyz;
  13923. }
  13924. /**
  13925. * Setups the position in clip space.
  13926. *
  13927. * @param {NodeBuilder} builder - The current node builder.
  13928. * @return {Node<vec4>} The position in view space.
  13929. */
  13930. setupModelViewProjection( /*builder*/ ) {
  13931. return cameraProjectionMatrix.mul( positionView );
  13932. }
  13933. /**
  13934. * Setups the logic for the vertex stage.
  13935. *
  13936. * @param {NodeBuilder} builder - The current node builder.
  13937. * @return {Node<vec4>} The position in clip space.
  13938. */
  13939. setupVertex( builder ) {
  13940. builder.addStack();
  13941. this.setupPosition( builder );
  13942. builder.context.vertex = builder.removeStack();
  13943. return modelViewProjection;
  13944. }
  13945. /**
  13946. * Setups the computation of the position in local space.
  13947. *
  13948. * @param {NodeBuilder} builder - The current node builder.
  13949. * @return {Node<vec3>} The position in local space.
  13950. */
  13951. setupPosition( builder ) {
  13952. const { object, geometry } = builder;
  13953. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  13954. morphReference( object ).toStack();
  13955. }
  13956. if ( object.isSkinnedMesh === true ) {
  13957. skinning( object ).toStack();
  13958. }
  13959. if ( this.displacementMap ) {
  13960. const displacementMap = materialReference( 'displacementMap', 'texture' );
  13961. const displacementScale = materialReference( 'displacementScale', 'float' );
  13962. const displacementBias = materialReference( 'displacementBias', 'float' );
  13963. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  13964. }
  13965. if ( object.isBatchedMesh ) {
  13966. batch( object ).toStack();
  13967. }
  13968. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  13969. instancedMesh( object ).toStack();
  13970. }
  13971. if ( this.positionNode !== null ) {
  13972. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  13973. }
  13974. return positionLocal;
  13975. }
  13976. /**
  13977. * Setups the computation of the material's diffuse color.
  13978. *
  13979. * @param {NodeBuilder} builder - The current node builder.
  13980. * @param {BufferGeometry} geometry - The geometry.
  13981. */
  13982. setupDiffuseColor( { object, geometry } ) {
  13983. // MASK
  13984. if ( this.maskNode !== null ) {
  13985. // Discard if the mask is `false`
  13986. bool( this.maskNode ).not().discard();
  13987. }
  13988. // COLOR
  13989. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  13990. // VERTEX COLORS
  13991. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  13992. colorNode = colorNode.mul( vertexColor() );
  13993. }
  13994. // INSTANCED COLORS
  13995. if ( object.instanceColor ) {
  13996. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  13997. colorNode = instanceColor.mul( colorNode );
  13998. }
  13999. if ( object.isBatchedMesh && object._colorsTexture ) {
  14000. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14001. colorNode = batchColor.mul( colorNode );
  14002. }
  14003. // DIFFUSE COLOR
  14004. diffuseColor.assign( colorNode );
  14005. // OPACITY
  14006. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14007. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14008. // ALPHA TEST
  14009. let alphaTestNode = null;
  14010. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14011. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14012. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14013. }
  14014. // ALPHA HASH
  14015. if ( this.alphaHash === true ) {
  14016. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14017. }
  14018. // OPAQUE
  14019. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  14020. if ( isOpaque ) {
  14021. diffuseColor.a.assign( 1.0 );
  14022. } else if ( alphaTestNode === null ) {
  14023. diffuseColor.a.lessThanEqual( 0 ).discard();
  14024. }
  14025. }
  14026. /**
  14027. * Abstract interface method that can be implemented by derived materials
  14028. * to setup material-specific node variables.
  14029. *
  14030. * @abstract
  14031. * @param {NodeBuilder} builder - The current node builder.
  14032. */
  14033. setupVariants( /*builder*/ ) {
  14034. // Interface function.
  14035. }
  14036. /**
  14037. * Setups the outgoing light node variable
  14038. *
  14039. * @return {Node<vec3>} The outgoing light node.
  14040. */
  14041. setupOutgoingLight() {
  14042. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14043. }
  14044. /**
  14045. * Setups the normal node from the material.
  14046. *
  14047. * @return {Node<vec3>} The normal node.
  14048. */
  14049. setupNormal() {
  14050. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14051. }
  14052. /**
  14053. * Setups the environment node from the material.
  14054. *
  14055. * @param {NodeBuilder} builder - The current node builder.
  14056. * @return {Node<vec4>} The environment node.
  14057. */
  14058. setupEnvironment( /*builder*/ ) {
  14059. let node = null;
  14060. if ( this.envNode ) {
  14061. node = this.envNode;
  14062. } else if ( this.envMap ) {
  14063. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14064. }
  14065. return node;
  14066. }
  14067. /**
  14068. * Setups the light map node from the material.
  14069. *
  14070. * @param {NodeBuilder} builder - The current node builder.
  14071. * @return {Node<vec3>} The light map node.
  14072. */
  14073. setupLightMap( builder ) {
  14074. let node = null;
  14075. if ( builder.material.lightMap ) {
  14076. node = new IrradianceNode( materialLightMap );
  14077. }
  14078. return node;
  14079. }
  14080. /**
  14081. * Setups the lights node based on the scene, environment and material.
  14082. *
  14083. * @param {NodeBuilder} builder - The current node builder.
  14084. * @return {LightsNode} The lights node.
  14085. */
  14086. setupLights( builder ) {
  14087. const materialLightsNode = [];
  14088. //
  14089. const envNode = this.setupEnvironment( builder );
  14090. if ( envNode && envNode.isLightingNode ) {
  14091. materialLightsNode.push( envNode );
  14092. }
  14093. const lightMapNode = this.setupLightMap( builder );
  14094. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14095. materialLightsNode.push( lightMapNode );
  14096. }
  14097. if ( this.aoNode !== null || builder.material.aoMap ) {
  14098. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14099. materialLightsNode.push( new AONode( aoNode ) );
  14100. }
  14101. let lightsN = this.lightsNode || builder.lightsNode;
  14102. if ( materialLightsNode.length > 0 ) {
  14103. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14104. }
  14105. return lightsN;
  14106. }
  14107. /**
  14108. * This method should be implemented by most derived materials
  14109. * since it defines the material's lighting model.
  14110. *
  14111. * @abstract
  14112. * @param {NodeBuilder} builder - The current node builder.
  14113. * @return {LightingModel} The lighting model.
  14114. */
  14115. setupLightingModel( /*builder*/ ) {
  14116. // Interface function.
  14117. }
  14118. /**
  14119. * Setups the outgoing light node.
  14120. *
  14121. * @param {NodeBuilder} builder - The current node builder.
  14122. * @return {Node<vec3>} The outgoing light node.
  14123. */
  14124. setupLighting( builder ) {
  14125. const { material } = builder;
  14126. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14127. // OUTGOING LIGHT
  14128. const lights = this.lights === true || this.lightsNode !== null;
  14129. const lightsNode = lights ? this.setupLights( builder ) : null;
  14130. let outgoingLightNode = this.setupOutgoingLight( builder );
  14131. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14132. const lightingModel = this.setupLightingModel( builder ) || null;
  14133. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14134. } else if ( backdropNode !== null ) {
  14135. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14136. }
  14137. // EMISSIVE
  14138. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14139. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14140. outgoingLightNode = outgoingLightNode.add( emissive );
  14141. }
  14142. return outgoingLightNode;
  14143. }
  14144. /**
  14145. * Setup the fog.
  14146. *
  14147. * @param {NodeBuilder} builder - The current node builder.
  14148. * @param {Node<vec4>} outputNode - The existing output node.
  14149. * @return {Node<vec4>} The output node.
  14150. */
  14151. setupFog( builder, outputNode ) {
  14152. const fogNode = builder.fogNode;
  14153. if ( fogNode ) {
  14154. output.assign( outputNode );
  14155. outputNode = vec4( fogNode.toVar() );
  14156. }
  14157. return outputNode;
  14158. }
  14159. /**
  14160. * Setups premultiplied alpha.
  14161. *
  14162. * @param {NodeBuilder} builder - The current node builder.
  14163. * @param {Node<vec4>} outputNode - The existing output node.
  14164. * @return {Node<vec4>} The output node.
  14165. */
  14166. setupPremultipliedAlpha( builder, outputNode ) {
  14167. return premultiplyAlpha( outputNode );
  14168. }
  14169. /**
  14170. * Setups the output node.
  14171. *
  14172. * @param {NodeBuilder} builder - The current node builder.
  14173. * @param {Node<vec4>} outputNode - The existing output node.
  14174. * @return {Node<vec4>} The output node.
  14175. */
  14176. setupOutput( builder, outputNode ) {
  14177. // FOG
  14178. if ( this.fog === true ) {
  14179. outputNode = this.setupFog( builder, outputNode );
  14180. }
  14181. // PREMULTIPLIED ALPHA
  14182. if ( this.premultipliedAlpha === true ) {
  14183. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14184. }
  14185. return outputNode;
  14186. }
  14187. /**
  14188. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14189. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14190. * defining all material properties of the classic type in the node type.
  14191. *
  14192. * @param {Material} material - The material to copy properties with their values to this node material.
  14193. */
  14194. setDefaultValues( material ) {
  14195. // This approach is to reuse the native refreshUniforms*
  14196. // and turn available the use of features like transmission and environment in core
  14197. for ( const property in material ) {
  14198. const value = material[ property ];
  14199. if ( this[ property ] === undefined ) {
  14200. this[ property ] = value;
  14201. if ( value && value.clone ) this[ property ] = value.clone();
  14202. }
  14203. }
  14204. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14205. for ( const key in descriptors ) {
  14206. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14207. descriptors[ key ].get !== undefined ) {
  14208. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14209. }
  14210. }
  14211. }
  14212. /**
  14213. * Serializes this material to JSON.
  14214. *
  14215. * @param {?(Object|string)} meta - The meta information for serialization.
  14216. * @return {Object} The serialized node.
  14217. */
  14218. toJSON( meta ) {
  14219. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14220. if ( isRoot ) {
  14221. meta = {
  14222. textures: {},
  14223. images: {},
  14224. nodes: {}
  14225. };
  14226. }
  14227. const data = Material.prototype.toJSON.call( this, meta );
  14228. const nodeChildren = getNodeChildren( this );
  14229. data.inputNodes = {};
  14230. for ( const { property, childNode } of nodeChildren ) {
  14231. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14232. }
  14233. // TODO: Copied from Object3D.toJSON
  14234. function extractFromCache( cache ) {
  14235. const values = [];
  14236. for ( const key in cache ) {
  14237. const data = cache[ key ];
  14238. delete data.metadata;
  14239. values.push( data );
  14240. }
  14241. return values;
  14242. }
  14243. if ( isRoot ) {
  14244. const textures = extractFromCache( meta.textures );
  14245. const images = extractFromCache( meta.images );
  14246. const nodes = extractFromCache( meta.nodes );
  14247. if ( textures.length > 0 ) data.textures = textures;
  14248. if ( images.length > 0 ) data.images = images;
  14249. if ( nodes.length > 0 ) data.nodes = nodes;
  14250. }
  14251. return data;
  14252. }
  14253. /**
  14254. * Copies the properties of the given node material to this instance.
  14255. *
  14256. * @param {NodeMaterial} source - The material to copy.
  14257. * @return {NodeMaterial} A reference to this node material.
  14258. */
  14259. copy( source ) {
  14260. this.lightsNode = source.lightsNode;
  14261. this.envNode = source.envNode;
  14262. this.colorNode = source.colorNode;
  14263. this.normalNode = source.normalNode;
  14264. this.opacityNode = source.opacityNode;
  14265. this.backdropNode = source.backdropNode;
  14266. this.backdropAlphaNode = source.backdropAlphaNode;
  14267. this.alphaTestNode = source.alphaTestNode;
  14268. this.maskNode = source.maskNode;
  14269. this.positionNode = source.positionNode;
  14270. this.geometryNode = source.geometryNode;
  14271. this.depthNode = source.depthNode;
  14272. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14273. this.castShadowPositionNode = source.castShadowPositionNode;
  14274. this.receivedShadowNode = source.receivedShadowNode;
  14275. this.castShadowNode = source.castShadowNode;
  14276. this.outputNode = source.outputNode;
  14277. this.mrtNode = source.mrtNode;
  14278. this.fragmentNode = source.fragmentNode;
  14279. this.vertexNode = source.vertexNode;
  14280. return super.copy( source );
  14281. }
  14282. }
  14283. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14284. /**
  14285. * Node material version of {@link LineBasicMaterial}.
  14286. *
  14287. * @augments NodeMaterial
  14288. */
  14289. class LineBasicNodeMaterial extends NodeMaterial {
  14290. static get type() {
  14291. return 'LineBasicNodeMaterial';
  14292. }
  14293. /**
  14294. * Constructs a new line basic node material.
  14295. *
  14296. * @param {Object} [parameters] - The configuration parameter.
  14297. */
  14298. constructor( parameters ) {
  14299. super();
  14300. /**
  14301. * This flag can be used for type testing.
  14302. *
  14303. * @type {boolean}
  14304. * @readonly
  14305. * @default true
  14306. */
  14307. this.isLineBasicNodeMaterial = true;
  14308. this.setDefaultValues( _defaultValues$d );
  14309. this.setValues( parameters );
  14310. }
  14311. }
  14312. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14313. /**
  14314. * Node material version of {@link LineDashedMaterial}.
  14315. *
  14316. * @augments NodeMaterial
  14317. */
  14318. class LineDashedNodeMaterial extends NodeMaterial {
  14319. static get type() {
  14320. return 'LineDashedNodeMaterial';
  14321. }
  14322. /**
  14323. * Constructs a new line dashed node material.
  14324. *
  14325. * @param {Object} [parameters] - The configuration parameter.
  14326. */
  14327. constructor( parameters ) {
  14328. super();
  14329. /**
  14330. * This flag can be used for type testing.
  14331. *
  14332. * @type {boolean}
  14333. * @readonly
  14334. * @default true
  14335. */
  14336. this.isLineDashedNodeMaterial = true;
  14337. this.setDefaultValues( _defaultValues$c );
  14338. /**
  14339. * The dash offset.
  14340. *
  14341. * @type {number}
  14342. * @default 0
  14343. */
  14344. this.dashOffset = 0;
  14345. /**
  14346. * The offset of dash materials is by default inferred from the `dashOffset`
  14347. * property. This node property allows to overwrite the default
  14348. * and define the offset with a node instead.
  14349. *
  14350. * If you don't want to overwrite the offset but modify the existing
  14351. * value instead, use {@link materialLineDashOffset}.
  14352. *
  14353. * @type {?Node<float>}
  14354. * @default null
  14355. */
  14356. this.offsetNode = null;
  14357. /**
  14358. * The scale of dash materials is by default inferred from the `scale`
  14359. * property. This node property allows to overwrite the default
  14360. * and define the scale with a node instead.
  14361. *
  14362. * If you don't want to overwrite the scale but modify the existing
  14363. * value instead, use {@link materialLineScale}.
  14364. *
  14365. * @type {?Node<float>}
  14366. * @default null
  14367. */
  14368. this.dashScaleNode = null;
  14369. /**
  14370. * The dash size of dash materials is by default inferred from the `dashSize`
  14371. * property. This node property allows to overwrite the default
  14372. * and define the dash size with a node instead.
  14373. *
  14374. * If you don't want to overwrite the dash size but modify the existing
  14375. * value instead, use {@link materialLineDashSize}.
  14376. *
  14377. * @type {?Node<float>}
  14378. * @default null
  14379. */
  14380. this.dashSizeNode = null;
  14381. /**
  14382. * The gap size of dash materials is by default inferred from the `gapSize`
  14383. * property. This node property allows to overwrite the default
  14384. * and define the gap size with a node instead.
  14385. *
  14386. * If you don't want to overwrite the gap size but modify the existing
  14387. * value instead, use {@link materialLineGapSize}.
  14388. *
  14389. * @type {?Node<float>}
  14390. * @default null
  14391. */
  14392. this.gapSizeNode = null;
  14393. this.setValues( parameters );
  14394. }
  14395. /**
  14396. * Setups the dash specific node variables.
  14397. *
  14398. * @param {NodeBuilder} builder - The current node builder.
  14399. */
  14400. setupVariants( /* builder */ ) {
  14401. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14402. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14403. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14404. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14405. dashSize.assign( dashSizeNode );
  14406. gapSize.assign( gapSizeNode );
  14407. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14408. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14409. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14410. }
  14411. }
  14412. let _sharedFramebuffer = null;
  14413. /**
  14414. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14415. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14416. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14417. *
  14418. * @augments ViewportTextureNode
  14419. */
  14420. class ViewportSharedTextureNode extends ViewportTextureNode {
  14421. static get type() {
  14422. return 'ViewportSharedTextureNode';
  14423. }
  14424. /**
  14425. * Constructs a new viewport shared texture node.
  14426. *
  14427. * @param {Node} [uvNode=screenUV] - The uv node.
  14428. * @param {?Node} [levelNode=null] - The level node.
  14429. */
  14430. constructor( uvNode = screenUV, levelNode = null ) {
  14431. if ( _sharedFramebuffer === null ) {
  14432. _sharedFramebuffer = new FramebufferTexture();
  14433. }
  14434. super( uvNode, levelNode, _sharedFramebuffer );
  14435. }
  14436. /**
  14437. * Overwritten so the method always returns the unique shared
  14438. * framebuffer texture.
  14439. *
  14440. * @return {FramebufferTexture} The shared framebuffer texture.
  14441. */
  14442. getTextureForReference() {
  14443. return _sharedFramebuffer;
  14444. }
  14445. updateReference() {
  14446. return this;
  14447. }
  14448. }
  14449. /**
  14450. * TSL function for creating a shared viewport texture node.
  14451. *
  14452. * @tsl
  14453. * @function
  14454. * @param {?Node} [uvNode=screenUV] - The uv node.
  14455. * @param {?Node} [levelNode=null] - The level node.
  14456. * @returns {ViewportSharedTextureNode}
  14457. */
  14458. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14459. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14460. /**
  14461. * This node material can be used to render lines with a size larger than one
  14462. * by representing them as instanced meshes.
  14463. *
  14464. * @augments NodeMaterial
  14465. */
  14466. class Line2NodeMaterial extends NodeMaterial {
  14467. static get type() {
  14468. return 'Line2NodeMaterial';
  14469. }
  14470. /**
  14471. * Constructs a new node material for wide line rendering.
  14472. *
  14473. * @param {Object} [parameters={}] - The configuration parameter.
  14474. */
  14475. constructor( parameters = {} ) {
  14476. super();
  14477. /**
  14478. * This flag can be used for type testing.
  14479. *
  14480. * @type {boolean}
  14481. * @readonly
  14482. * @default true
  14483. */
  14484. this.isLine2NodeMaterial = true;
  14485. this.setDefaultValues( _defaultValues$b );
  14486. /**
  14487. * Whether vertex colors should be used or not.
  14488. *
  14489. * @type {boolean}
  14490. * @default false
  14491. */
  14492. this.useColor = parameters.vertexColors;
  14493. /**
  14494. * The dash offset.
  14495. *
  14496. * @type {number}
  14497. * @default 0
  14498. */
  14499. this.dashOffset = 0;
  14500. /**
  14501. * Defines the lines color.
  14502. *
  14503. * @type {?Node<vec3>}
  14504. * @default null
  14505. */
  14506. this.lineColorNode = null;
  14507. /**
  14508. * Defines the offset.
  14509. *
  14510. * @type {?Node<float>}
  14511. * @default null
  14512. */
  14513. this.offsetNode = null;
  14514. /**
  14515. * Defines the dash scale.
  14516. *
  14517. * @type {?Node<float>}
  14518. * @default null
  14519. */
  14520. this.dashScaleNode = null;
  14521. /**
  14522. * Defines the dash size.
  14523. *
  14524. * @type {?Node<float>}
  14525. * @default null
  14526. */
  14527. this.dashSizeNode = null;
  14528. /**
  14529. * Defines the gap size.
  14530. *
  14531. * @type {?Node<float>}
  14532. * @default null
  14533. */
  14534. this.gapSizeNode = null;
  14535. /**
  14536. * Blending is set to `NoBlending` since transparency
  14537. * is not supported, yet.
  14538. *
  14539. * @type {number}
  14540. * @default 0
  14541. */
  14542. this.blending = NoBlending;
  14543. this._useDash = parameters.dashed;
  14544. this._useAlphaToCoverage = true;
  14545. this._useWorldUnits = false;
  14546. this.setValues( parameters );
  14547. }
  14548. /**
  14549. * Setups the vertex and fragment stage of this node material.
  14550. *
  14551. * @param {NodeBuilder} builder - The current node builder.
  14552. */
  14553. setup( builder ) {
  14554. const { renderer } = builder;
  14555. const useAlphaToCoverage = this._useAlphaToCoverage;
  14556. const useColor = this.useColor;
  14557. const useDash = this._useDash;
  14558. const useWorldUnits = this._useWorldUnits;
  14559. const trimSegment = Fn( ( { start, end } ) => {
  14560. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  14561. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  14562. const nearEstimate = b.mul( -0.5 ).div( a );
  14563. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  14564. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  14565. } ).setLayout( {
  14566. name: 'trimSegment',
  14567. type: 'vec4',
  14568. inputs: [
  14569. { name: 'start', type: 'vec4' },
  14570. { name: 'end', type: 'vec4' }
  14571. ]
  14572. } );
  14573. this.vertexNode = Fn( () => {
  14574. const instanceStart = attribute( 'instanceStart' );
  14575. const instanceEnd = attribute( 'instanceEnd' );
  14576. // camera space
  14577. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  14578. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  14579. if ( useDash ) {
  14580. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14581. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14582. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  14583. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  14584. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  14585. lineDistance = lineDistance.add( offsetNode );
  14586. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  14587. }
  14588. if ( useWorldUnits ) {
  14589. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  14590. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  14591. }
  14592. const aspect = viewport.z.div( viewport.w );
  14593. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  14594. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  14595. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  14596. // perhaps there is a more elegant solution -- WestLangley
  14597. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  14598. If( perspective, () => {
  14599. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  14600. end.assign( trimSegment( { start: start, end: end } ) );
  14601. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  14602. start.assign( trimSegment( { start: end, end: start } ) );
  14603. } );
  14604. } );
  14605. // clip space
  14606. const clipStart = cameraProjectionMatrix.mul( start );
  14607. const clipEnd = cameraProjectionMatrix.mul( end );
  14608. // ndc space
  14609. const ndcStart = clipStart.xyz.div( clipStart.w );
  14610. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  14611. // direction
  14612. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  14613. // account for clip-space aspect ratio
  14614. dir.x.assign( dir.x.mul( aspect ) );
  14615. dir.assign( dir.normalize() );
  14616. const clip = vec4().toVar();
  14617. if ( useWorldUnits ) {
  14618. // get the offset direction as perpendicular to the view vector
  14619. const worldDir = end.xyz.sub( start.xyz ).normalize();
  14620. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  14621. const worldUp = worldDir.cross( tmpFwd ).normalize();
  14622. const worldFwd = worldDir.cross( worldUp );
  14623. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  14624. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  14625. // height offset
  14626. const hw = materialLineWidth.mul( 0.5 );
  14627. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  14628. // don't extend the line if we're rendering dashes because we
  14629. // won't be rendering the endcaps
  14630. if ( ! useDash ) {
  14631. // cap extension
  14632. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  14633. // add width to the box
  14634. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  14635. // endcaps
  14636. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  14637. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  14638. } );
  14639. }
  14640. // project the worldpos
  14641. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  14642. // shift the depth of the projected points so the line
  14643. // segments overlap neatly
  14644. const clipPose = vec3().toVar();
  14645. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  14646. clip.z.assign( clipPose.z.mul( clip.w ) );
  14647. } else {
  14648. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  14649. // undo aspect ratio adjustment
  14650. dir.x.assign( dir.x.div( aspect ) );
  14651. offset.x.assign( offset.x.div( aspect ) );
  14652. // sign flip
  14653. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  14654. // endcaps
  14655. If( positionGeometry.y.lessThan( 0.0 ), () => {
  14656. offset.assign( offset.sub( dir ) );
  14657. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  14658. offset.assign( offset.add( dir ) );
  14659. } );
  14660. // adjust for linewidth
  14661. offset.assign( offset.mul( materialLineWidth ) );
  14662. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  14663. offset.assign( offset.div( viewport.w ) );
  14664. // select end
  14665. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  14666. // back to clip space
  14667. offset.assign( offset.mul( clip.w ) );
  14668. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  14669. }
  14670. return clip;
  14671. } )();
  14672. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  14673. const p13 = p1.sub( p3 );
  14674. const p43 = p4.sub( p3 );
  14675. const p21 = p2.sub( p1 );
  14676. const d1343 = p13.dot( p43 );
  14677. const d4321 = p43.dot( p21 );
  14678. const d1321 = p13.dot( p21 );
  14679. const d4343 = p43.dot( p43 );
  14680. const d2121 = p21.dot( p21 );
  14681. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  14682. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  14683. const mua = numer.div( denom ).clamp();
  14684. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  14685. return vec2( mua, mub );
  14686. } );
  14687. this.colorNode = Fn( () => {
  14688. const vUv = uv$1();
  14689. if ( useDash ) {
  14690. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14691. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14692. dashSize.assign( dashSizeNode );
  14693. gapSize.assign( gapSizeNode );
  14694. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  14695. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  14696. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  14697. }
  14698. const alpha = float( 1 ).toVar( 'alpha' );
  14699. if ( useWorldUnits ) {
  14700. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  14701. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  14702. // Find the closest points on the view ray and the line segment
  14703. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  14704. const lineDir = worldEnd.sub( worldStart );
  14705. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  14706. const p1 = worldStart.add( lineDir.mul( params.x ) );
  14707. const p2 = rayEnd.mul( params.y );
  14708. const delta = p1.sub( p2 );
  14709. const len = delta.length();
  14710. const norm = len.div( materialLineWidth );
  14711. if ( ! useDash ) {
  14712. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14713. const dnorm = norm.fwidth();
  14714. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  14715. } else {
  14716. norm.greaterThan( 0.5 ).discard();
  14717. }
  14718. }
  14719. } else {
  14720. // round endcaps
  14721. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  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. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  14726. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14727. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  14728. } );
  14729. } else {
  14730. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14731. const a = vUv.x;
  14732. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14733. const len2 = a.mul( a ).add( b.mul( b ) );
  14734. len2.greaterThan( 1.0 ).discard();
  14735. } );
  14736. }
  14737. }
  14738. let lineColorNode;
  14739. if ( this.lineColorNode ) {
  14740. lineColorNode = this.lineColorNode;
  14741. } else {
  14742. if ( useColor ) {
  14743. const instanceColorStart = attribute( 'instanceColorStart' );
  14744. const instanceColorEnd = attribute( 'instanceColorEnd' );
  14745. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  14746. lineColorNode = instanceColor.mul( materialColor );
  14747. } else {
  14748. lineColorNode = materialColor;
  14749. }
  14750. }
  14751. return vec4( lineColorNode, alpha );
  14752. } )();
  14753. if ( this.transparent ) {
  14754. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14755. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  14756. }
  14757. super.setup( builder );
  14758. }
  14759. /**
  14760. * Whether the lines should sized in world units or not.
  14761. * When set to `false` the unit is pixel.
  14762. *
  14763. * @type {boolean}
  14764. * @default false
  14765. */
  14766. get worldUnits() {
  14767. return this._useWorldUnits;
  14768. }
  14769. set worldUnits( value ) {
  14770. if ( this._useWorldUnits !== value ) {
  14771. this._useWorldUnits = value;
  14772. this.needsUpdate = true;
  14773. }
  14774. }
  14775. /**
  14776. * Whether the lines should be dashed or not.
  14777. *
  14778. * @type {boolean}
  14779. * @default false
  14780. */
  14781. get dashed() {
  14782. return this._useDash;
  14783. }
  14784. set dashed( value ) {
  14785. if ( this._useDash !== value ) {
  14786. this._useDash = value;
  14787. this.needsUpdate = true;
  14788. }
  14789. }
  14790. /**
  14791. * Whether alpha to coverage should be used or not.
  14792. *
  14793. * @type {boolean}
  14794. * @default true
  14795. */
  14796. get alphaToCoverage() {
  14797. return this._useAlphaToCoverage;
  14798. }
  14799. set alphaToCoverage( value ) {
  14800. if ( this._useAlphaToCoverage !== value ) {
  14801. this._useAlphaToCoverage = value;
  14802. this.needsUpdate = true;
  14803. }
  14804. }
  14805. }
  14806. /**
  14807. * Packs a direction vector into a color value.
  14808. *
  14809. * @tsl
  14810. * @function
  14811. * @param {Node<vec3>} node - The direction to pack.
  14812. * @return {Node<vec3>} The color.
  14813. */
  14814. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  14815. /**
  14816. * Unpacks a color value into a direction vector.
  14817. *
  14818. * @tsl
  14819. * @function
  14820. * @param {Node<vec3>} node - The color to unpack.
  14821. * @return {Node<vec3>} The direction.
  14822. */
  14823. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  14824. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  14825. /**
  14826. * Node material version of {@link MeshNormalMaterial}.
  14827. *
  14828. * @augments NodeMaterial
  14829. */
  14830. class MeshNormalNodeMaterial extends NodeMaterial {
  14831. static get type() {
  14832. return 'MeshNormalNodeMaterial';
  14833. }
  14834. /**
  14835. * Constructs a new mesh normal node material.
  14836. *
  14837. * @param {Object} [parameters] - The configuration parameter.
  14838. */
  14839. constructor( parameters ) {
  14840. super();
  14841. /**
  14842. * This flag can be used for type testing.
  14843. *
  14844. * @type {boolean}
  14845. * @readonly
  14846. * @default true
  14847. */
  14848. this.isMeshNormalNodeMaterial = true;
  14849. this.setDefaultValues( _defaultValues$a );
  14850. this.setValues( parameters );
  14851. }
  14852. /**
  14853. * Overwrites the default implementation by computing the diffuse color
  14854. * based on the normal data.
  14855. */
  14856. setupDiffuseColor() {
  14857. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14858. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  14859. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  14860. }
  14861. }
  14862. /**
  14863. * TSL function for creating an equirect uv node.
  14864. *
  14865. * Can be used to compute texture coordinates for projecting an
  14866. * equirectangular texture onto a mesh for using it as the scene's
  14867. * background.
  14868. *
  14869. * ```js
  14870. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  14871. * ```
  14872. *
  14873. * @tsl
  14874. * @function
  14875. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14876. * @returns {Node<vec2>}
  14877. */
  14878. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  14879. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  14880. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  14881. return vec2( u, v );
  14882. } );
  14883. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  14884. /**
  14885. * This class represents a cube render target. It is a special version
  14886. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  14887. *
  14888. * @augments WebGLCubeRenderTarget
  14889. */
  14890. class CubeRenderTarget extends WebGLCubeRenderTarget {
  14891. /**
  14892. * Constructs a new cube render target.
  14893. *
  14894. * @param {number} [size=1] - The size of the render target.
  14895. * @param {RenderTarget~Options} [options] - The configuration object.
  14896. */
  14897. constructor( size = 1, options = {} ) {
  14898. super( size, options );
  14899. /**
  14900. * This flag can be used for type testing.
  14901. *
  14902. * @type {boolean}
  14903. * @readonly
  14904. * @default true
  14905. */
  14906. this.isCubeRenderTarget = true;
  14907. }
  14908. /**
  14909. * Converts the given equirectangular texture to a cube map.
  14910. *
  14911. * @param {Renderer} renderer - The renderer.
  14912. * @param {Texture} texture - The equirectangular texture.
  14913. * @return {CubeRenderTarget} A reference to this cube render target.
  14914. */
  14915. fromEquirectangularTexture( renderer, texture$1 ) {
  14916. const currentMinFilter = texture$1.minFilter;
  14917. const currentGenerateMipmaps = texture$1.generateMipmaps;
  14918. texture$1.generateMipmaps = true;
  14919. this.texture.type = texture$1.type;
  14920. this.texture.colorSpace = texture$1.colorSpace;
  14921. this.texture.generateMipmaps = texture$1.generateMipmaps;
  14922. this.texture.minFilter = texture$1.minFilter;
  14923. this.texture.magFilter = texture$1.magFilter;
  14924. const geometry = new BoxGeometry( 5, 5, 5 );
  14925. const uvNode = equirectUV( positionWorldDirection );
  14926. const material = new NodeMaterial();
  14927. material.colorNode = texture( texture$1, uvNode, 0 );
  14928. material.side = BackSide;
  14929. material.blending = NoBlending;
  14930. const mesh = new Mesh( geometry, material );
  14931. const scene = new Scene();
  14932. scene.add( mesh );
  14933. // Avoid blurred poles
  14934. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  14935. const camera = new CubeCamera( 1, 10, this );
  14936. const currentMRT = renderer.getMRT();
  14937. renderer.setMRT( null );
  14938. camera.update( renderer, scene );
  14939. renderer.setMRT( currentMRT );
  14940. texture$1.minFilter = currentMinFilter;
  14941. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  14942. mesh.geometry.dispose();
  14943. mesh.material.dispose();
  14944. return this;
  14945. }
  14946. }
  14947. const _cache$1 = new WeakMap();
  14948. /**
  14949. * This node can be used to automatically convert environment maps in the
  14950. * equirectangular format into the cube map format.
  14951. *
  14952. * @augments TempNode
  14953. */
  14954. class CubeMapNode extends TempNode {
  14955. static get type() {
  14956. return 'CubeMapNode';
  14957. }
  14958. /**
  14959. * Constructs a new cube map node.
  14960. *
  14961. * @param {Node} envNode - The node representing the environment map.
  14962. */
  14963. constructor( envNode ) {
  14964. super( 'vec3' );
  14965. /**
  14966. * The node representing the environment map.
  14967. *
  14968. * @type {Node}
  14969. */
  14970. this.envNode = envNode;
  14971. /**
  14972. * A reference to the internal cube texture.
  14973. *
  14974. * @private
  14975. * @type {?CubeTexture}
  14976. * @default null
  14977. */
  14978. this._cubeTexture = null;
  14979. /**
  14980. * A reference to the internal cube texture node.
  14981. *
  14982. * @private
  14983. * @type {CubeTextureNode}
  14984. */
  14985. this._cubeTextureNode = cubeTexture( null );
  14986. const defaultTexture = new CubeTexture();
  14987. defaultTexture.isRenderTargetTexture = true;
  14988. /**
  14989. * A default cube texture that acts as a placeholder.
  14990. * It is used when the conversion from equirectangular to cube
  14991. * map has not finished yet for a given texture.
  14992. *
  14993. * @private
  14994. * @type {CubeTexture}
  14995. */
  14996. this._defaultTexture = defaultTexture;
  14997. /**
  14998. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14999. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15000. *
  15001. * @type {string}
  15002. * @default 'render'
  15003. */
  15004. this.updateBeforeType = NodeUpdateType.RENDER;
  15005. }
  15006. updateBefore( frame ) {
  15007. const { renderer, material } = frame;
  15008. const envNode = this.envNode;
  15009. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15010. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15011. if ( texture && texture.isTexture ) {
  15012. const mapping = texture.mapping;
  15013. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15014. // check for converted cubemap map
  15015. if ( _cache$1.has( texture ) ) {
  15016. const cubeMap = _cache$1.get( texture );
  15017. mapTextureMapping( cubeMap, texture.mapping );
  15018. this._cubeTexture = cubeMap;
  15019. } else {
  15020. // create cube map from equirectangular map
  15021. const image = texture.image;
  15022. if ( isEquirectangularMapReady$1( image ) ) {
  15023. const renderTarget = new CubeRenderTarget( image.height );
  15024. renderTarget.fromEquirectangularTexture( renderer, texture );
  15025. mapTextureMapping( renderTarget.texture, texture.mapping );
  15026. this._cubeTexture = renderTarget.texture;
  15027. _cache$1.set( texture, renderTarget.texture );
  15028. texture.addEventListener( 'dispose', onTextureDispose );
  15029. } else {
  15030. // default cube texture as fallback when equirectangular texture is not yet loaded
  15031. this._cubeTexture = this._defaultTexture;
  15032. }
  15033. }
  15034. //
  15035. this._cubeTextureNode.value = this._cubeTexture;
  15036. } else {
  15037. // envNode already refers to a cube map
  15038. this._cubeTextureNode = this.envNode;
  15039. }
  15040. }
  15041. }
  15042. }
  15043. setup( builder ) {
  15044. this.updateBefore( builder );
  15045. return this._cubeTextureNode;
  15046. }
  15047. }
  15048. /**
  15049. * Returns true if the given equirectangular image has been fully loaded
  15050. * and is ready for further processing.
  15051. *
  15052. * @private
  15053. * @param {Image} image - The equirectangular image to check.
  15054. * @return {boolean} Whether the image is ready or not.
  15055. */
  15056. function isEquirectangularMapReady$1( image ) {
  15057. if ( image === null || image === undefined ) return false;
  15058. return image.height > 0;
  15059. }
  15060. /**
  15061. * This function is executed when `dispose()` is called on the equirectangular
  15062. * texture. In this case, the generated cube map with its render target
  15063. * is deleted as well.
  15064. *
  15065. * @private
  15066. * @param {Object} event - The event object.
  15067. */
  15068. function onTextureDispose( event ) {
  15069. const texture = event.target;
  15070. texture.removeEventListener( 'dispose', onTextureDispose );
  15071. const renderTarget = _cache$1.get( texture );
  15072. if ( renderTarget !== undefined ) {
  15073. _cache$1.delete( texture );
  15074. renderTarget.dispose();
  15075. }
  15076. }
  15077. /**
  15078. * This function makes sure the generated cube map uses the correct
  15079. * texture mapping that corresponds to the equirectangular original.
  15080. *
  15081. * @private
  15082. * @param {Texture} texture - The cube texture.
  15083. * @param {number} mapping - The original texture mapping.
  15084. */
  15085. function mapTextureMapping( texture, mapping ) {
  15086. if ( mapping === EquirectangularReflectionMapping ) {
  15087. texture.mapping = CubeReflectionMapping;
  15088. } else if ( mapping === EquirectangularRefractionMapping ) {
  15089. texture.mapping = CubeRefractionMapping;
  15090. }
  15091. }
  15092. /**
  15093. * TSL function for creating a cube map node.
  15094. *
  15095. * @tsl
  15096. * @function
  15097. * @param {Node} envNode - The node representing the environment map.
  15098. * @returns {CubeMapNode}
  15099. */
  15100. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15101. /**
  15102. * Represents a basic model for Image-based lighting (IBL). The environment
  15103. * is defined via environment maps in the equirectangular or cube map format.
  15104. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15105. * or {@link MeshPhongNodeMaterial}.
  15106. *
  15107. * @augments LightingNode
  15108. */
  15109. class BasicEnvironmentNode extends LightingNode {
  15110. static get type() {
  15111. return 'BasicEnvironmentNode';
  15112. }
  15113. /**
  15114. * Constructs a new basic environment node.
  15115. *
  15116. * @param {Node} [envNode=null] - A node representing the environment.
  15117. */
  15118. constructor( envNode = null ) {
  15119. super();
  15120. /**
  15121. * A node representing the environment.
  15122. *
  15123. * @type {Node}
  15124. * @default null
  15125. */
  15126. this.envNode = envNode;
  15127. }
  15128. setup( builder ) {
  15129. // environment property is used in the finish() method of BasicLightingModel
  15130. builder.context.environment = cubeMapNode( this.envNode );
  15131. }
  15132. }
  15133. /**
  15134. * A specific version of {@link IrradianceNode} that is only relevant
  15135. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15136. * requires a special scaling factor for the light map.
  15137. *
  15138. * @augments LightingNode
  15139. */
  15140. class BasicLightMapNode extends LightingNode {
  15141. static get type() {
  15142. return 'BasicLightMapNode';
  15143. }
  15144. /**
  15145. * Constructs a new basic light map node.
  15146. *
  15147. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15148. */
  15149. constructor( lightMapNode = null ) {
  15150. super();
  15151. /**
  15152. * The light map node.
  15153. *
  15154. * @type {?Node<vec3>}
  15155. */
  15156. this.lightMapNode = lightMapNode;
  15157. }
  15158. setup( builder ) {
  15159. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15160. const RECIPROCAL_PI = float( 1 / Math.PI );
  15161. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15162. }
  15163. }
  15164. /**
  15165. * Abstract class for implementing lighting models. The module defines
  15166. * multiple methods that concrete lighting models can implement. These
  15167. * methods are executed at different points during the light evaluation
  15168. * process.
  15169. */
  15170. class LightingModel {
  15171. /**
  15172. * This method is intended for setting up lighting model and context data
  15173. * which are later used in the evaluation process.
  15174. *
  15175. * @abstract
  15176. * @param {NodeBuilder} builder - The current node builder.
  15177. */
  15178. start( builder ) {
  15179. // lights ( direct )
  15180. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15181. // indirect
  15182. this.indirect( builder );
  15183. }
  15184. /**
  15185. * This method is intended for executing final tasks like final updates
  15186. * to the outgoing light.
  15187. *
  15188. * @abstract
  15189. * @param {NodeBuilder} builder - The current node builder.
  15190. */
  15191. finish( /*builder*/ ) { }
  15192. /**
  15193. * This method is intended for implementing the direct light term and
  15194. * executed during the build process of directional, point and spot light nodes.
  15195. *
  15196. * @abstract
  15197. * @param {Object} lightData - The light data.
  15198. * @param {NodeBuilder} builder - The current node builder.
  15199. */
  15200. direct( /*lightData, builder*/ ) { }
  15201. /**
  15202. * This method is intended for implementing the direct light term for
  15203. * rect area light nodes.
  15204. *
  15205. * @abstract
  15206. * @param {Object} lightData - The light data.
  15207. * @param {NodeBuilder} builder - The current node builder.
  15208. */
  15209. directRectArea( /*lightData, builder*/ ) {}
  15210. /**
  15211. * This method is intended for implementing the indirect light term.
  15212. *
  15213. * @abstract
  15214. * @param {NodeBuilder} builder - The current node builder.
  15215. */
  15216. indirect( /*builder*/ ) { }
  15217. /**
  15218. * This method is intended for implementing the ambient occlusion term.
  15219. * Unlike other methods, this method must be called manually by the lighting
  15220. * model in its indirect term.
  15221. *
  15222. * @abstract
  15223. * @param {NodeBuilder} builder - The current node builder.
  15224. */
  15225. ambientOcclusion( /*input, stack, builder*/ ) { }
  15226. }
  15227. /**
  15228. * Represents the lighting model for unlit materials. The only light contribution
  15229. * is baked indirect lighting modulated with ambient occlusion and the material's
  15230. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15231. *
  15232. * @augments LightingModel
  15233. */
  15234. class BasicLightingModel extends LightingModel {
  15235. /**
  15236. * Constructs a new basic lighting model.
  15237. */
  15238. constructor() {
  15239. super();
  15240. }
  15241. /**
  15242. * Implements the baked indirect lighting with its modulation.
  15243. *
  15244. * @param {NodeBuilder} builder - The current node builder.
  15245. */
  15246. indirect( { context } ) {
  15247. const ambientOcclusion = context.ambientOcclusion;
  15248. const reflectedLight = context.reflectedLight;
  15249. const irradianceLightMap = context.irradianceLightMap;
  15250. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15251. // accumulation (baked indirect lighting only)
  15252. if ( irradianceLightMap ) {
  15253. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15254. } else {
  15255. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15256. }
  15257. // modulation
  15258. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15259. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15260. }
  15261. /**
  15262. * Implements the environment mapping.
  15263. *
  15264. * @param {NodeBuilder} builder - The current node builder.
  15265. */
  15266. finish( builder ) {
  15267. const { material, context } = builder;
  15268. const outgoingLight = context.outgoingLight;
  15269. const envNode = builder.context.environment;
  15270. if ( envNode ) {
  15271. switch ( material.combine ) {
  15272. case MultiplyOperation:
  15273. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15274. break;
  15275. case MixOperation:
  15276. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15277. break;
  15278. case AddOperation:
  15279. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15280. break;
  15281. default:
  15282. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  15283. break;
  15284. }
  15285. }
  15286. }
  15287. }
  15288. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15289. /**
  15290. * Node material version of {@link MeshBasicMaterial}.
  15291. *
  15292. * @augments NodeMaterial
  15293. */
  15294. class MeshBasicNodeMaterial extends NodeMaterial {
  15295. static get type() {
  15296. return 'MeshBasicNodeMaterial';
  15297. }
  15298. /**
  15299. * Constructs a new mesh basic node material.
  15300. *
  15301. * @param {Object} [parameters] - The configuration parameter.
  15302. */
  15303. constructor( parameters ) {
  15304. super();
  15305. /**
  15306. * This flag can be used for type testing.
  15307. *
  15308. * @type {boolean}
  15309. * @readonly
  15310. * @default true
  15311. */
  15312. this.isMeshBasicNodeMaterial = true;
  15313. /**
  15314. * Although the basic material is by definition unlit, we set
  15315. * this property to `true` since we use a lighting model to compute
  15316. * the outgoing light of the fragment shader.
  15317. *
  15318. * @type {boolean}
  15319. * @default true
  15320. */
  15321. this.lights = true;
  15322. this.setDefaultValues( _defaultValues$9 );
  15323. this.setValues( parameters );
  15324. }
  15325. /**
  15326. * Basic materials are not affected by normal and bump maps so we
  15327. * return by default {@link normalViewGeometry}.
  15328. *
  15329. * @return {Node<vec3>} The normal node.
  15330. */
  15331. setupNormal() {
  15332. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15333. }
  15334. /**
  15335. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15336. * to implement the default environment mapping.
  15337. *
  15338. * @param {NodeBuilder} builder - The current node builder.
  15339. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15340. */
  15341. setupEnvironment( builder ) {
  15342. const envNode = super.setupEnvironment( builder );
  15343. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15344. }
  15345. /**
  15346. * This method must be overwritten since light maps are evaluated
  15347. * with a special scaling factor for basic materials.
  15348. *
  15349. * @param {NodeBuilder} builder - The current node builder.
  15350. * @return {?BasicLightMapNode<vec3>} The light map node.
  15351. */
  15352. setupLightMap( builder ) {
  15353. let node = null;
  15354. if ( builder.material.lightMap ) {
  15355. node = new BasicLightMapNode( materialLightMap );
  15356. }
  15357. return node;
  15358. }
  15359. /**
  15360. * The material overwrites this method because `lights` is set to `true` but
  15361. * we still want to return the diffuse color as the outgoing light.
  15362. *
  15363. * @return {Node<vec3>} The outgoing light node.
  15364. */
  15365. setupOutgoingLight() {
  15366. return diffuseColor.rgb;
  15367. }
  15368. /**
  15369. * Setups the lighting model.
  15370. *
  15371. * @return {BasicLightingModel} The lighting model.
  15372. */
  15373. setupLightingModel() {
  15374. return new BasicLightingModel();
  15375. }
  15376. }
  15377. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15378. // Original approximation by Christophe Schlick '94
  15379. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15380. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15381. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15382. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15383. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15384. } ); // validated
  15385. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15386. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15387. } ); // validated
  15388. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15389. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15390. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15391. } );
  15392. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15393. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15394. const dotNH = normalView.dot( halfDir ).clamp();
  15395. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15396. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15397. const G = G_BlinnPhong_Implicit();
  15398. const D = D_BlinnPhong( { dotNH } );
  15399. return F.mul( G ).mul( D );
  15400. } );
  15401. /**
  15402. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15403. *
  15404. * @augments BasicLightingModel
  15405. */
  15406. class PhongLightingModel extends BasicLightingModel {
  15407. /**
  15408. * Constructs a new phong lighting model.
  15409. *
  15410. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15411. */
  15412. constructor( specular = true ) {
  15413. super();
  15414. /**
  15415. * Whether specular is supported or not. Set this to `false` if you are
  15416. * looking for a Lambert-like material meaning a material for non-shiny
  15417. * surfaces, without specular highlights.
  15418. *
  15419. * @type {boolean}
  15420. * @default true
  15421. */
  15422. this.specular = specular;
  15423. }
  15424. /**
  15425. * Implements the direct lighting. The specular portion is optional an can be controlled
  15426. * with the {@link PhongLightingModel#specular} flag.
  15427. *
  15428. * @param {Object} lightData - The light data.
  15429. */
  15430. direct( { lightDirection, lightColor, reflectedLight } ) {
  15431. const dotNL = normalView.dot( lightDirection ).clamp();
  15432. const irradiance = dotNL.mul( lightColor );
  15433. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15434. if ( this.specular === true ) {
  15435. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15436. }
  15437. }
  15438. /**
  15439. * Implements the indirect lighting.
  15440. *
  15441. * @param {NodeBuilder} builder - The current node builder.
  15442. */
  15443. indirect( builder ) {
  15444. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15445. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15446. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15447. }
  15448. }
  15449. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15450. /**
  15451. * Node material version of {@link MeshLambertMaterial}.
  15452. *
  15453. * @augments NodeMaterial
  15454. */
  15455. class MeshLambertNodeMaterial extends NodeMaterial {
  15456. static get type() {
  15457. return 'MeshLambertNodeMaterial';
  15458. }
  15459. /**
  15460. * Constructs a new mesh lambert node material.
  15461. *
  15462. * @param {Object} [parameters] - The configuration parameter.
  15463. */
  15464. constructor( parameters ) {
  15465. super();
  15466. /**
  15467. * This flag can be used for type testing.
  15468. *
  15469. * @type {boolean}
  15470. * @readonly
  15471. * @default true
  15472. */
  15473. this.isMeshLambertNodeMaterial = true;
  15474. /**
  15475. * Set to `true` because lambert materials react on lights.
  15476. *
  15477. * @type {boolean}
  15478. * @default true
  15479. */
  15480. this.lights = true;
  15481. this.setDefaultValues( _defaultValues$8 );
  15482. this.setValues( parameters );
  15483. }
  15484. /**
  15485. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15486. * to implement the default environment mapping.
  15487. *
  15488. * @param {NodeBuilder} builder - The current node builder.
  15489. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15490. */
  15491. setupEnvironment( builder ) {
  15492. const envNode = super.setupEnvironment( builder );
  15493. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15494. }
  15495. /**
  15496. * Setups the lighting model.
  15497. *
  15498. * @return {PhongLightingModel} The lighting model.
  15499. */
  15500. setupLightingModel( /*builder*/ ) {
  15501. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15502. }
  15503. }
  15504. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15505. /**
  15506. * Node material version of {@link MeshPhongMaterial}.
  15507. *
  15508. * @augments NodeMaterial
  15509. */
  15510. class MeshPhongNodeMaterial extends NodeMaterial {
  15511. static get type() {
  15512. return 'MeshPhongNodeMaterial';
  15513. }
  15514. /**
  15515. * Constructs a new mesh lambert node material.
  15516. *
  15517. * @param {Object} [parameters] - The configuration parameter.
  15518. */
  15519. constructor( parameters ) {
  15520. super();
  15521. /**
  15522. * This flag can be used for type testing.
  15523. *
  15524. * @type {boolean}
  15525. * @readonly
  15526. * @default true
  15527. */
  15528. this.isMeshPhongNodeMaterial = true;
  15529. /**
  15530. * Set to `true` because phong materials react on lights.
  15531. *
  15532. * @type {boolean}
  15533. * @default true
  15534. */
  15535. this.lights = true;
  15536. /**
  15537. * The shininess of phong materials is by default inferred from the `shininess`
  15538. * property. This node property allows to overwrite the default
  15539. * and define the shininess with a node instead.
  15540. *
  15541. * If you don't want to overwrite the shininess but modify the existing
  15542. * value instead, use {@link materialShininess}.
  15543. *
  15544. * @type {?Node<float>}
  15545. * @default null
  15546. */
  15547. this.shininessNode = null;
  15548. /**
  15549. * The specular color of phong materials is by default inferred from the
  15550. * `specular` property. This node property allows to overwrite the default
  15551. * and define the specular color with a node instead.
  15552. *
  15553. * If you don't want to overwrite the specular color but modify the existing
  15554. * value instead, use {@link materialSpecular}.
  15555. *
  15556. * @type {?Node<vec3>}
  15557. * @default null
  15558. */
  15559. this.specularNode = null;
  15560. this.setDefaultValues( _defaultValues$7 );
  15561. this.setValues( parameters );
  15562. }
  15563. /**
  15564. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15565. * to implement the default environment mapping.
  15566. *
  15567. * @param {NodeBuilder} builder - The current node builder.
  15568. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15569. */
  15570. setupEnvironment( builder ) {
  15571. const envNode = super.setupEnvironment( builder );
  15572. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15573. }
  15574. /**
  15575. * Setups the lighting model.
  15576. *
  15577. * @return {PhongLightingModel} The lighting model.
  15578. */
  15579. setupLightingModel( /*builder*/ ) {
  15580. return new PhongLightingModel();
  15581. }
  15582. /**
  15583. * Setups the phong specific node variables.
  15584. *
  15585. * @param {NodeBuilder} builder - The current node builder.
  15586. */
  15587. setupVariants( /*builder*/ ) {
  15588. // SHININESS
  15589. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15590. shininess.assign( shininessNode );
  15591. // SPECULAR COLOR
  15592. const specularNode = this.specularNode || materialSpecular;
  15593. specularColor.assign( specularNode );
  15594. }
  15595. copy( source ) {
  15596. this.shininessNode = source.shininessNode;
  15597. this.specularNode = source.specularNode;
  15598. return super.copy( source );
  15599. }
  15600. }
  15601. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  15602. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  15603. return float( 0 );
  15604. }
  15605. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  15606. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  15607. return geometryRoughness;
  15608. } );
  15609. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  15610. const { roughness } = inputs;
  15611. const geometryRoughness = getGeometryRoughness();
  15612. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  15613. roughnessFactor = roughnessFactor.add( geometryRoughness );
  15614. roughnessFactor = roughnessFactor.min( 1.0 );
  15615. return roughnessFactor;
  15616. } );
  15617. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  15618. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15619. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  15620. const a2 = alpha.pow2();
  15621. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  15622. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  15623. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  15624. } ).setLayout( {
  15625. name: 'V_GGX_SmithCorrelated',
  15626. type: 'float',
  15627. inputs: [
  15628. { name: 'alpha', type: 'float' },
  15629. { name: 'dotNL', type: 'float' },
  15630. { name: 'dotNV', type: 'float' }
  15631. ]
  15632. } ); // validated
  15633. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15634. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  15635. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  15636. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  15637. const v = div( 0.5, gv.add( gl ) );
  15638. return v.saturate();
  15639. } ).setLayout( {
  15640. name: 'V_GGX_SmithCorrelated_Anisotropic',
  15641. type: 'float',
  15642. inputs: [
  15643. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15644. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15645. { name: 'dotTV', type: 'float', qualifier: 'in' },
  15646. { name: 'dotBV', type: 'float', qualifier: 'in' },
  15647. { name: 'dotTL', type: 'float', qualifier: 'in' },
  15648. { name: 'dotBL', type: 'float', qualifier: 'in' },
  15649. { name: 'dotNV', type: 'float', qualifier: 'in' },
  15650. { name: 'dotNL', type: 'float', qualifier: 'in' }
  15651. ]
  15652. } );
  15653. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  15654. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  15655. // alpha is "roughness squared" in Disney’s reparameterization
  15656. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  15657. const a2 = alpha.pow2();
  15658. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  15659. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  15660. } ).setLayout( {
  15661. name: 'D_GGX',
  15662. type: 'float',
  15663. inputs: [
  15664. { name: 'alpha', type: 'float' },
  15665. { name: 'dotNH', type: 'float' }
  15666. ]
  15667. } ); // validated
  15668. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  15669. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15670. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  15671. const a2 = alphaT.mul( alphaB );
  15672. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  15673. const v2 = v.dot( v );
  15674. const w2 = a2.div( v2 );
  15675. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  15676. } ).setLayout( {
  15677. name: 'D_GGX_Anisotropic',
  15678. type: 'float',
  15679. inputs: [
  15680. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15681. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15682. { name: 'dotNH', type: 'float', qualifier: 'in' },
  15683. { name: 'dotTH', type: 'float', qualifier: 'in' },
  15684. { name: 'dotBH', type: 'float', qualifier: 'in' }
  15685. ]
  15686. } );
  15687. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  15688. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  15689. const alpha = roughness.pow2(); // UE4's roughness
  15690. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15691. const dotNL = normalView$1.dot( lightDirection ).clamp();
  15692. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15693. const dotNH = normalView$1.dot( halfDir ).clamp();
  15694. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15695. let F = F_Schlick( { f0, f90, dotVH } );
  15696. let V, D;
  15697. if ( defined( USE_IRIDESCENCE ) ) {
  15698. F = iridescence.mix( F, f );
  15699. }
  15700. if ( defined( USE_ANISOTROPY ) ) {
  15701. const dotTL = anisotropyT.dot( lightDirection );
  15702. const dotTV = anisotropyT.dot( positionViewDirection );
  15703. const dotTH = anisotropyT.dot( halfDir );
  15704. const dotBL = anisotropyB.dot( lightDirection );
  15705. const dotBV = anisotropyB.dot( positionViewDirection );
  15706. const dotBH = anisotropyB.dot( halfDir );
  15707. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  15708. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  15709. } else {
  15710. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  15711. D = D_GGX( { alpha, dotNH } );
  15712. }
  15713. return F.mul( V ).mul( D );
  15714. } ); // validated
  15715. // Analytical approximation of the DFG LUT, one half of the
  15716. // split-sum approximation used in indirect specular lighting.
  15717. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  15718. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  15719. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  15720. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  15721. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  15722. const r = roughness.mul( c0 ).add( c1 );
  15723. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  15724. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  15725. return fab;
  15726. } ).setLayout( {
  15727. name: 'DFGApprox',
  15728. type: 'vec2',
  15729. inputs: [
  15730. { name: 'roughness', type: 'float' },
  15731. { name: 'dotNV', type: 'vec3' }
  15732. ]
  15733. } );
  15734. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  15735. const { dotNV, specularColor, specularF90, roughness } = inputs;
  15736. const fab = DFGApprox( { dotNV, roughness } );
  15737. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15738. } );
  15739. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  15740. const x = dotVH.oneMinus().saturate();
  15741. const x2 = x.mul( x );
  15742. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  15743. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  15744. } ).setLayout( {
  15745. name: 'Schlick_to_F0',
  15746. type: 'vec3',
  15747. inputs: [
  15748. { name: 'f', type: 'vec3' },
  15749. { name: 'f90', type: 'float' },
  15750. { name: 'dotVH', type: 'float' }
  15751. ]
  15752. } );
  15753. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15754. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  15755. const alpha = roughness.pow2();
  15756. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  15757. const invAlpha = float( 1.0 ).div( alpha );
  15758. const cos2h = dotNH.pow2();
  15759. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  15760. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  15761. } ).setLayout( {
  15762. name: 'D_Charlie',
  15763. type: 'float',
  15764. inputs: [
  15765. { name: 'roughness', type: 'float' },
  15766. { name: 'dotNH', type: 'float' }
  15767. ]
  15768. } );
  15769. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15770. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  15771. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  15772. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  15773. } ).setLayout( {
  15774. name: 'V_Neubelt',
  15775. type: 'float',
  15776. inputs: [
  15777. { name: 'dotNV', type: 'float' },
  15778. { name: 'dotNL', type: 'float' }
  15779. ]
  15780. } );
  15781. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15782. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15783. const dotNL = normalView.dot( lightDirection ).clamp();
  15784. const dotNV = normalView.dot( positionViewDirection ).clamp();
  15785. const dotNH = normalView.dot( halfDir ).clamp();
  15786. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  15787. const V = V_Neubelt( { dotNV, dotNL } );
  15788. return sheen.mul( D ).mul( V );
  15789. } );
  15790. // Rect Area Light
  15791. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  15792. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  15793. // code: https://github.com/selfshadow/ltc_code/
  15794. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  15795. const LUT_SIZE = 64.0;
  15796. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  15797. const LUT_BIAS = 0.5 / LUT_SIZE;
  15798. const dotNV = N.dot( V ).saturate();
  15799. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  15800. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  15801. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  15802. return uv;
  15803. } ).setLayout( {
  15804. name: 'LTC_Uv',
  15805. type: 'vec2',
  15806. inputs: [
  15807. { name: 'N', type: 'vec3' },
  15808. { name: 'V', type: 'vec3' },
  15809. { name: 'roughness', type: 'float' }
  15810. ]
  15811. } );
  15812. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  15813. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  15814. // An approximation of the form factor of a horizon-clipped rectangle.
  15815. const l = f.length();
  15816. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  15817. } ).setLayout( {
  15818. name: 'LTC_ClippedSphereFormFactor',
  15819. type: 'float',
  15820. inputs: [
  15821. { name: 'f', type: 'vec3' }
  15822. ]
  15823. } );
  15824. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  15825. const x = v1.dot( v2 );
  15826. const y = x.abs().toVar();
  15827. // rational polynomial approximation to theta / sin( theta ) / 2PI
  15828. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  15829. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  15830. const v = a.div( b );
  15831. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  15832. return v1.cross( v2 ).mul( theta_sintheta );
  15833. } ).setLayout( {
  15834. name: 'LTC_EdgeVectorFormFactor',
  15835. type: 'vec3',
  15836. inputs: [
  15837. { name: 'v1', type: 'vec3' },
  15838. { name: 'v2', type: 'vec3' }
  15839. ]
  15840. } );
  15841. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  15842. // bail if point is on back side of plane of light
  15843. // assumes ccw winding order of light vertices
  15844. const v1 = p1.sub( p0 ).toVar();
  15845. const v2 = p3.sub( p0 ).toVar();
  15846. const lightNormal = v1.cross( v2 );
  15847. const result = vec3().toVar();
  15848. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15849. // construct orthonormal basis around N
  15850. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  15851. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  15852. // compute transform
  15853. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  15854. // transform rect
  15855. // & project rect onto sphere
  15856. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  15857. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  15858. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  15859. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  15860. // calculate vector form factor
  15861. const vectorFormFactor = vec3( 0 ).toVar();
  15862. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15863. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15864. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15865. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15866. // adjust for horizon clipping
  15867. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  15868. } );
  15869. return result;
  15870. } ).setLayout( {
  15871. name: 'LTC_Evaluate',
  15872. type: 'vec3',
  15873. inputs: [
  15874. { name: 'N', type: 'vec3' },
  15875. { name: 'V', type: 'vec3' },
  15876. { name: 'P', type: 'vec3' },
  15877. { name: 'mInv', type: 'mat3' },
  15878. { name: 'p0', type: 'vec3' },
  15879. { name: 'p1', type: 'vec3' },
  15880. { name: 'p2', type: 'vec3' },
  15881. { name: 'p3', type: 'vec3' }
  15882. ]
  15883. } );
  15884. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  15885. // bail if point is on back side of plane of light
  15886. // assumes ccw winding order of light vertices
  15887. const v1 = p1.sub( p0 ).toVar();
  15888. const v2 = p3.sub( p0 ).toVar();
  15889. const lightNormal = v1.cross( v2 );
  15890. const result = vec3().toVar();
  15891. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15892. // transform rect
  15893. // & project rect onto sphere
  15894. const coords0 = p0.sub( P ).normalize().toVar();
  15895. const coords1 = p1.sub( P ).normalize().toVar();
  15896. const coords2 = p2.sub( P ).normalize().toVar();
  15897. const coords3 = p3.sub( P ).normalize().toVar();
  15898. // calculate vector form factor
  15899. const vectorFormFactor = vec3( 0 ).toVar();
  15900. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15901. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15902. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15903. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15904. // adjust for horizon clipping
  15905. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  15906. } );
  15907. return result;
  15908. } ).setLayout( {
  15909. name: 'LTC_Evaluate',
  15910. type: 'vec3',
  15911. inputs: [
  15912. { name: 'P', type: 'vec3' },
  15913. { name: 'p0', type: 'vec3' },
  15914. { name: 'p1', type: 'vec3' },
  15915. { name: 'p2', type: 'vec3' },
  15916. { name: 'p3', type: 'vec3' }
  15917. ]
  15918. } );
  15919. // Mipped Bicubic Texture Filtering by N8
  15920. // https://www.shadertoy.com/view/Dl2SDW
  15921. const bC = 1.0 / 6.0;
  15922. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  15923. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  15924. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  15925. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  15926. const g0 = ( a ) => w0( a ).add( w1( a ) );
  15927. const g1 = ( a ) => w2( a ).add( w3( a ) );
  15928. // h0 and h1 are the two offset functions
  15929. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  15930. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  15931. const bicubic = ( textureNode, texelSize, lod ) => {
  15932. const uv = textureNode.uvNode;
  15933. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  15934. const iuv = floor( uvScaled );
  15935. const fuv = fract( uvScaled );
  15936. const g0x = g0( fuv.x );
  15937. const g1x = g1( fuv.x );
  15938. const h0x = h0( fuv.x );
  15939. const h1x = h1( fuv.x );
  15940. const h0y = h0( fuv.y );
  15941. const h1y = h1( fuv.y );
  15942. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15943. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15944. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15945. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15946. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  15947. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  15948. return a.add( b );
  15949. };
  15950. /**
  15951. * Applies mipped bicubic texture filtering to the given texture node.
  15952. *
  15953. * @tsl
  15954. * @function
  15955. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15956. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  15957. * @return {Node} The filtered texture sample.
  15958. */
  15959. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  15960. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  15961. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  15962. const fLodSizeInv = div( 1.0, fLodSize );
  15963. const cLodSizeInv = div( 1.0, cLodSize );
  15964. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  15965. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  15966. return fract( lodNode ).mix( fSample, cSample );
  15967. } );
  15968. /**
  15969. * Applies mipped bicubic texture filtering to the given texture node.
  15970. *
  15971. * @tsl
  15972. * @function
  15973. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15974. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  15975. * @return {Node} The filtered texture sample.
  15976. */
  15977. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  15978. const lod = strength.mul( maxMipLevel( textureNode ) );
  15979. return textureBicubicLevel( textureNode, lod );
  15980. } );
  15981. //
  15982. // Transmission
  15983. //
  15984. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  15985. // Direction of refracted light.
  15986. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  15987. // Compute rotation-independent scaling of the model matrix.
  15988. const modelScale = vec3(
  15989. length( modelMatrix[ 0 ].xyz ),
  15990. length( modelMatrix[ 1 ].xyz ),
  15991. length( modelMatrix[ 2 ].xyz )
  15992. );
  15993. // The thickness is specified in local space.
  15994. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  15995. } ).setLayout( {
  15996. name: 'getVolumeTransmissionRay',
  15997. type: 'vec3',
  15998. inputs: [
  15999. { name: 'n', type: 'vec3' },
  16000. { name: 'v', type: 'vec3' },
  16001. { name: 'thickness', type: 'float' },
  16002. { name: 'ior', type: 'float' },
  16003. { name: 'modelMatrix', type: 'mat4' }
  16004. ]
  16005. } );
  16006. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16007. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16008. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16009. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16010. } ).setLayout( {
  16011. name: 'applyIorToRoughness',
  16012. type: 'float',
  16013. inputs: [
  16014. { name: 'roughness', type: 'float' },
  16015. { name: 'ior', type: 'float' }
  16016. ]
  16017. } );
  16018. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16019. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16020. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16021. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16022. const transmissionSample = vTexture.sample( fragCoord );
  16023. //const transmissionSample = viewportMipTexture( fragCoord );
  16024. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16025. return textureBicubicLevel( transmissionSample, lod );
  16026. } );
  16027. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16028. If( attenuationDistance.notEqual( 0 ), () => {
  16029. // Compute light attenuation using Beer's law.
  16030. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16031. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16032. return transmittance;
  16033. } );
  16034. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16035. return vec3( 1.0 );
  16036. } ).setLayout( {
  16037. name: 'volumeAttenuation',
  16038. type: 'vec3',
  16039. inputs: [
  16040. { name: 'transmissionDistance', type: 'float' },
  16041. { name: 'attenuationColor', type: 'vec3' },
  16042. { name: 'attenuationDistance', type: 'float' }
  16043. ]
  16044. } );
  16045. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16046. let transmittedLight, transmittance;
  16047. if ( dispersion ) {
  16048. transmittedLight = vec4().toVar();
  16049. transmittance = vec3().toVar();
  16050. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16051. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16052. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16053. const ior = iors.element( i );
  16054. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16055. const refractedRayExit = position.add( transmissionRay );
  16056. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16057. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16058. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16059. refractionCoords.addAssign( 1.0 );
  16060. refractionCoords.divAssign( 2.0 );
  16061. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16062. // Sample framebuffer to get pixel the refracted ray hits.
  16063. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16064. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16065. transmittedLight.a.addAssign( transmissionSample.a );
  16066. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16067. } );
  16068. transmittedLight.a.divAssign( 3.0 );
  16069. } else {
  16070. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16071. const refractedRayExit = position.add( transmissionRay );
  16072. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16073. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16074. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16075. refractionCoords.addAssign( 1.0 );
  16076. refractionCoords.divAssign( 2.0 );
  16077. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16078. // Sample framebuffer to get pixel the refracted ray hits.
  16079. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16080. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16081. }
  16082. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16083. const dotNV = n.dot( v ).clamp();
  16084. // Get the specular component.
  16085. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16086. dotNV,
  16087. specularColor,
  16088. specularF90,
  16089. roughness
  16090. } ) );
  16091. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16092. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16093. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16094. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16095. } );
  16096. //
  16097. // Iridescence
  16098. //
  16099. // XYZ to linear-sRGB color space
  16100. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16101. 3.2404542, -0.969266, 0.0556434,
  16102. -1.5371385, 1.8760108, -0.2040259,
  16103. -0.4985314, 0.0415560, 1.0572252
  16104. );
  16105. // Assume air interface for top
  16106. // Note: We don't handle the case fresnel0 == 1
  16107. const Fresnel0ToIor = ( fresnel0 ) => {
  16108. const sqrtF0 = fresnel0.sqrt();
  16109. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16110. };
  16111. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16112. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16113. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16114. };
  16115. // Fresnel equations for dielectric/dielectric interfaces.
  16116. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16117. // Evaluation XYZ sensitivity curves in Fourier space
  16118. const evalSensitivity = ( OPD, shift ) => {
  16119. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16120. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16121. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16122. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16123. 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() );
  16124. 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() );
  16125. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16126. const rgb = XYZ_TO_REC709.mul( xyz );
  16127. return rgb;
  16128. };
  16129. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16130. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16131. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16132. // Evaluate the cosTheta on the base layer (Snell law)
  16133. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16134. // Handle TIR:
  16135. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16136. If( cosTheta2Sq.lessThan( 0 ), () => {
  16137. return vec3( 1.0 );
  16138. } );
  16139. const cosTheta2 = cosTheta2Sq.sqrt();
  16140. // First interface
  16141. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16142. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16143. //const R21 = R12;
  16144. const T121 = R12.oneMinus();
  16145. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16146. const phi21 = float( Math.PI ).sub( phi12 );
  16147. // Second interface
  16148. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16149. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16150. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16151. const phi23 = vec3(
  16152. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16153. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16154. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16155. );
  16156. // Phase shift
  16157. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16158. const phi = vec3( phi21 ).add( phi23 );
  16159. // Compound terms
  16160. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16161. const r123 = R123.sqrt();
  16162. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16163. // Reflectance term for m = 0 (DC term amplitude)
  16164. const C0 = R12.add( Rs );
  16165. const I = C0.toVar();
  16166. // Reflectance term for m > 0 (pairs of diracs)
  16167. const Cm = Rs.sub( T121 ).toVar();
  16168. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16169. Cm.mulAssign( r123 );
  16170. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16171. I.addAssign( Cm.mul( Sm ) );
  16172. } );
  16173. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16174. return I.max( vec3( 0.0 ) );
  16175. } ).setLayout( {
  16176. name: 'evalIridescence',
  16177. type: 'vec3',
  16178. inputs: [
  16179. { name: 'outsideIOR', type: 'float' },
  16180. { name: 'eta2', type: 'float' },
  16181. { name: 'cosTheta1', type: 'float' },
  16182. { name: 'thinFilmThickness', type: 'float' },
  16183. { name: 'baseF0', type: 'vec3' }
  16184. ]
  16185. } );
  16186. //
  16187. // Sheen
  16188. //
  16189. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16190. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16191. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16192. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16193. const dotNV = normal.dot( viewDir ).saturate();
  16194. const r2 = roughness.pow2();
  16195. const a = select(
  16196. roughness.lessThan( 0.25 ),
  16197. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16198. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16199. );
  16200. const b = select(
  16201. roughness.lessThan( 0.25 ),
  16202. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16203. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16204. );
  16205. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16206. return DG.mul( 1.0 / Math.PI ).saturate();
  16207. } );
  16208. const clearcoatF0 = vec3( 0.04 );
  16209. const clearcoatF90 = float( 1 );
  16210. /**
  16211. * Represents the lighting model for a PBR material.
  16212. *
  16213. * @augments LightingModel
  16214. */
  16215. class PhysicalLightingModel extends LightingModel {
  16216. /**
  16217. * Constructs a new physical lighting model.
  16218. *
  16219. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16220. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16221. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16222. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16223. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16224. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16225. */
  16226. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16227. super();
  16228. /**
  16229. * Whether clearcoat is supported or not.
  16230. *
  16231. * @type {boolean}
  16232. * @default false
  16233. */
  16234. this.clearcoat = clearcoat;
  16235. /**
  16236. * Whether sheen is supported or not.
  16237. *
  16238. * @type {boolean}
  16239. * @default false
  16240. */
  16241. this.sheen = sheen;
  16242. /**
  16243. * Whether iridescence is supported or not.
  16244. *
  16245. * @type {boolean}
  16246. * @default false
  16247. */
  16248. this.iridescence = iridescence;
  16249. /**
  16250. * Whether anisotropy is supported or not.
  16251. *
  16252. * @type {boolean}
  16253. * @default false
  16254. */
  16255. this.anisotropy = anisotropy;
  16256. /**
  16257. * Whether transmission is supported or not.
  16258. *
  16259. * @type {boolean}
  16260. * @default false
  16261. */
  16262. this.transmission = transmission;
  16263. /**
  16264. * Whether dispersion is supported or not.
  16265. *
  16266. * @type {boolean}
  16267. * @default false
  16268. */
  16269. this.dispersion = dispersion;
  16270. /**
  16271. * The clear coat radiance.
  16272. *
  16273. * @type {?Node}
  16274. * @default null
  16275. */
  16276. this.clearcoatRadiance = null;
  16277. /**
  16278. * The clear coat specular direct.
  16279. *
  16280. * @type {?Node}
  16281. * @default null
  16282. */
  16283. this.clearcoatSpecularDirect = null;
  16284. /**
  16285. * The clear coat specular indirect.
  16286. *
  16287. * @type {?Node}
  16288. * @default null
  16289. */
  16290. this.clearcoatSpecularIndirect = null;
  16291. /**
  16292. * The sheen specular direct.
  16293. *
  16294. * @type {?Node}
  16295. * @default null
  16296. */
  16297. this.sheenSpecularDirect = null;
  16298. /**
  16299. * The sheen specular indirect.
  16300. *
  16301. * @type {?Node}
  16302. * @default null
  16303. */
  16304. this.sheenSpecularIndirect = null;
  16305. /**
  16306. * The iridescence Fresnel.
  16307. *
  16308. * @type {?Node}
  16309. * @default null
  16310. */
  16311. this.iridescenceFresnel = null;
  16312. /**
  16313. * The iridescence F0.
  16314. *
  16315. * @type {?Node}
  16316. * @default null
  16317. */
  16318. this.iridescenceF0 = null;
  16319. }
  16320. /**
  16321. * Depending on what features are requested, the method prepares certain node variables
  16322. * which are later used for lighting computations.
  16323. *
  16324. * @param {NodeBuilder} builder - The current node builder.
  16325. */
  16326. start( builder ) {
  16327. if ( this.clearcoat === true ) {
  16328. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16329. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16330. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16331. }
  16332. if ( this.sheen === true ) {
  16333. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16334. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16335. }
  16336. if ( this.iridescence === true ) {
  16337. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16338. this.iridescenceFresnel = evalIridescence( {
  16339. outsideIOR: float( 1.0 ),
  16340. eta2: iridescenceIOR,
  16341. cosTheta1: dotNVi,
  16342. thinFilmThickness: iridescenceThickness,
  16343. baseF0: specularColor
  16344. } );
  16345. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16346. }
  16347. if ( this.transmission === true ) {
  16348. const position = positionWorld;
  16349. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16350. const n = normalWorld;
  16351. const context = builder.context;
  16352. context.backdrop = getIBLVolumeRefraction(
  16353. n,
  16354. v,
  16355. roughness,
  16356. diffuseColor,
  16357. specularColor,
  16358. specularF90, // specularF90
  16359. position, // positionWorld
  16360. modelWorldMatrix, // modelMatrix
  16361. cameraViewMatrix, // viewMatrix
  16362. cameraProjectionMatrix, // projMatrix
  16363. ior,
  16364. thickness,
  16365. attenuationColor,
  16366. attenuationDistance,
  16367. this.dispersion ? dispersion : null
  16368. );
  16369. context.backdropAlpha = transmission;
  16370. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16371. }
  16372. super.start( builder );
  16373. }
  16374. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16375. // Approximates multi-scattering in order to preserve energy.
  16376. // http://www.jcgt.org/published/0008/01/03/
  16377. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16378. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16379. const fab = DFGApprox( { roughness, dotNV } );
  16380. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16381. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16382. const Ess = fab.x.add( fab.y );
  16383. const Ems = Ess.oneMinus();
  16384. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16385. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16386. singleScatter.addAssign( FssEss );
  16387. multiScatter.addAssign( Fms.mul( Ems ) );
  16388. }
  16389. /**
  16390. * Implements the direct light.
  16391. *
  16392. * @param {Object} lightData - The light data.
  16393. * @param {NodeBuilder} builder - The current node builder.
  16394. */
  16395. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16396. const dotNL = normalView.dot( lightDirection ).clamp();
  16397. const irradiance = dotNL.mul( lightColor );
  16398. if ( this.sheen === true ) {
  16399. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16400. }
  16401. if ( this.clearcoat === true ) {
  16402. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16403. const ccIrradiance = dotNLcc.mul( lightColor );
  16404. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16405. }
  16406. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16407. 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 } ) ) );
  16408. }
  16409. /**
  16410. * This method is intended for implementing the direct light term for
  16411. * rect area light nodes.
  16412. *
  16413. * @param {Object} input - The input data.
  16414. * @param {NodeBuilder} builder - The current node builder.
  16415. */
  16416. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16417. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16418. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16419. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16420. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16421. const N = normalView;
  16422. const V = positionViewDirection;
  16423. const P = positionView.toVar();
  16424. const uv = LTC_Uv( { N, V, roughness } );
  16425. const t1 = ltc_1.sample( uv ).toVar();
  16426. const t2 = ltc_2.sample( uv ).toVar();
  16427. const mInv = mat3(
  16428. vec3( t1.x, 0, t1.y ),
  16429. vec3( 0, 1, 0 ),
  16430. vec3( t1.z, 0, t1.w )
  16431. ).toVar();
  16432. // LTC Fresnel Approximation by Stephen Hill
  16433. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16434. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16435. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16436. 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 } ) ) );
  16437. }
  16438. /**
  16439. * Implements the indirect lighting.
  16440. *
  16441. * @param {NodeBuilder} builder - The current node builder.
  16442. */
  16443. indirect( builder ) {
  16444. this.indirectDiffuse( builder );
  16445. this.indirectSpecular( builder );
  16446. this.ambientOcclusion( builder );
  16447. }
  16448. /**
  16449. * Implements the indirect diffuse term.
  16450. *
  16451. * @param {NodeBuilder} builder - The current node builder.
  16452. */
  16453. indirectDiffuse( builder ) {
  16454. const { irradiance, reflectedLight } = builder.context;
  16455. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16456. }
  16457. /**
  16458. * Implements the indirect specular term.
  16459. *
  16460. * @param {NodeBuilder} builder - The current node builder.
  16461. */
  16462. indirectSpecular( builder ) {
  16463. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16464. if ( this.sheen === true ) {
  16465. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16466. sheen,
  16467. IBLSheenBRDF( {
  16468. normal: normalView,
  16469. viewDir: positionViewDirection,
  16470. roughness: sheenRoughness
  16471. } )
  16472. ) );
  16473. }
  16474. if ( this.clearcoat === true ) {
  16475. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16476. const clearcoatEnv = EnvironmentBRDF( {
  16477. dotNV: dotNVcc,
  16478. specularColor: clearcoatF0,
  16479. specularF90: clearcoatF90,
  16480. roughness: clearcoatRoughness
  16481. } );
  16482. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16483. }
  16484. // Both indirect specular and indirect diffuse light accumulate here
  16485. const singleScattering = vec3().toVar( 'singleScattering' );
  16486. const multiScattering = vec3().toVar( 'multiScattering' );
  16487. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16488. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16489. const totalScattering = singleScattering.add( multiScattering );
  16490. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16491. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16492. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16493. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16494. }
  16495. /**
  16496. * Implements the ambient occlusion term.
  16497. *
  16498. * @param {NodeBuilder} builder - The current node builder.
  16499. */
  16500. ambientOcclusion( builder ) {
  16501. const { ambientOcclusion, reflectedLight } = builder.context;
  16502. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16503. const aoNV = dotNV.add( ambientOcclusion );
  16504. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16505. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16506. if ( this.clearcoat === true ) {
  16507. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16508. }
  16509. if ( this.sheen === true ) {
  16510. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16511. }
  16512. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16513. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16514. }
  16515. /**
  16516. * Used for final lighting accumulations depending on the requested features.
  16517. *
  16518. * @param {NodeBuilder} builder - The current node builder.
  16519. */
  16520. finish( { context } ) {
  16521. const { outgoingLight } = context;
  16522. if ( this.clearcoat === true ) {
  16523. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16524. const Fcc = F_Schlick( {
  16525. dotVH: dotNVcc,
  16526. f0: clearcoatF0,
  16527. f90: clearcoatF90
  16528. } );
  16529. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  16530. outgoingLight.assign( clearcoatLight );
  16531. }
  16532. if ( this.sheen === true ) {
  16533. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  16534. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  16535. outgoingLight.assign( sheenLight );
  16536. }
  16537. }
  16538. }
  16539. // These defines must match with PMREMGenerator
  16540. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  16541. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  16542. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  16543. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  16544. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  16545. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  16546. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  16547. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  16548. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  16549. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  16550. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  16551. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  16552. // These shader functions convert between the UV coordinates of a single face of
  16553. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  16554. // sampling a textureCube (not generally normalized ).
  16555. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  16556. const absDirection = vec3( abs( direction ) ).toVar();
  16557. const face = float( -1 ).toVar();
  16558. If( absDirection.x.greaterThan( absDirection.z ), () => {
  16559. If( absDirection.x.greaterThan( absDirection.y ), () => {
  16560. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  16561. } ).Else( () => {
  16562. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16563. } );
  16564. } ).Else( () => {
  16565. If( absDirection.z.greaterThan( absDirection.y ), () => {
  16566. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  16567. } ).Else( () => {
  16568. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16569. } );
  16570. } );
  16571. return face;
  16572. } ).setLayout( {
  16573. name: 'getFace',
  16574. type: 'float',
  16575. inputs: [
  16576. { name: 'direction', type: 'vec3' }
  16577. ]
  16578. } );
  16579. // RH coordinate system; PMREM face-indexing convention
  16580. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  16581. const uv = vec2().toVar();
  16582. If( face.equal( 0.0 ), () => {
  16583. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  16584. } ).ElseIf( face.equal( 1.0 ), () => {
  16585. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  16586. } ).ElseIf( face.equal( 2.0 ), () => {
  16587. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  16588. } ).ElseIf( face.equal( 3.0 ), () => {
  16589. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  16590. } ).ElseIf( face.equal( 4.0 ), () => {
  16591. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  16592. } ).Else( () => {
  16593. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  16594. } );
  16595. return mul( 0.5, uv.add( 1.0 ) );
  16596. } ).setLayout( {
  16597. name: 'getUV',
  16598. type: 'vec2',
  16599. inputs: [
  16600. { name: 'direction', type: 'vec3' },
  16601. { name: 'face', type: 'float' }
  16602. ]
  16603. } );
  16604. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  16605. const mip = float( 0.0 ).toVar();
  16606. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  16607. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  16608. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  16609. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  16610. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  16611. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  16612. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  16613. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  16614. } ).Else( () => {
  16615. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  16616. } );
  16617. return mip;
  16618. } ).setLayout( {
  16619. name: 'roughnessToMip',
  16620. type: 'float',
  16621. inputs: [
  16622. { name: 'roughness', type: 'float' }
  16623. ]
  16624. } );
  16625. // RH coordinate system; PMREM face-indexing convention
  16626. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  16627. const uv = uv_immutable.toVar();
  16628. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  16629. const direction = vec3( uv, 1.0 ).toVar();
  16630. If( face.equal( 0.0 ), () => {
  16631. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  16632. } ).ElseIf( face.equal( 1.0 ), () => {
  16633. direction.assign( direction.xzy );
  16634. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  16635. } ).ElseIf( face.equal( 2.0 ), () => {
  16636. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  16637. } ).ElseIf( face.equal( 3.0 ), () => {
  16638. direction.assign( direction.zyx );
  16639. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  16640. } ).ElseIf( face.equal( 4.0 ), () => {
  16641. direction.assign( direction.xzy );
  16642. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  16643. } ).ElseIf( face.equal( 5.0 ), () => {
  16644. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  16645. } );
  16646. return direction;
  16647. } ).setLayout( {
  16648. name: 'getDirection',
  16649. type: 'vec3',
  16650. inputs: [
  16651. { name: 'uv', type: 'vec2' },
  16652. { name: 'face', type: 'float' }
  16653. ]
  16654. } );
  16655. //
  16656. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16657. const roughness = float( roughness_immutable );
  16658. const sampleDir = vec3( sampleDir_immutable );
  16659. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  16660. const mipF = fract( mip );
  16661. const mipInt = floor( mip );
  16662. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16663. If( mipF.notEqual( 0.0 ), () => {
  16664. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16665. color0.assign( mix( color0, color1, mipF ) );
  16666. } );
  16667. return color0;
  16668. } );
  16669. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16670. const mipInt = float( mipInt_immutable ).toVar();
  16671. const direction = vec3( direction_immutable );
  16672. const face = float( getFace( direction ) ).toVar();
  16673. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  16674. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  16675. const faceSize = float( exp2( mipInt ) ).toVar();
  16676. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  16677. If( face.greaterThan( 2.0 ), () => {
  16678. uv.y.addAssign( faceSize );
  16679. face.subAssign( 3.0 );
  16680. } );
  16681. uv.x.addAssign( face.mul( faceSize ) );
  16682. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  16683. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  16684. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  16685. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  16686. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  16687. } );
  16688. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16689. const cosTheta = cos( theta );
  16690. // Rodrigues' axis-angle rotation
  16691. const sampleDirection = outputDirection.mul( cosTheta )
  16692. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  16693. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  16694. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  16695. } );
  16696. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16697. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  16698. If( axis.equal( vec3( 0.0 ) ), () => {
  16699. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  16700. } );
  16701. axis.assign( normalize( axis ) );
  16702. const gl_FragColor = vec3().toVar();
  16703. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16704. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  16705. If( i.greaterThanEqual( samples ), () => {
  16706. Break();
  16707. } );
  16708. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  16709. 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 } ) ) );
  16710. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16711. } );
  16712. return vec4( gl_FragColor, 1 );
  16713. } );
  16714. const LOD_MIN = 4;
  16715. // The standard deviations (radians) associated with the extra mips. These are
  16716. // chosen to approximate a Trowbridge-Reitz distribution function times the
  16717. // geometric shadowing function. These sigma values squared must match the
  16718. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  16719. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  16720. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  16721. // samples and exit early, but not recompile the shader.
  16722. const MAX_SAMPLES = 20;
  16723. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  16724. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  16725. const _clearColor$2 = /*@__PURE__*/ new Color();
  16726. let _oldTarget = null;
  16727. let _oldActiveCubeFace = 0;
  16728. let _oldActiveMipmapLevel = 0;
  16729. // Golden Ratio
  16730. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  16731. const INV_PHI = 1 / PHI;
  16732. // Vertices of a dodecahedron (except the opposites, which represent the
  16733. // same axis), used as axis directions evenly spread on a sphere.
  16734. const _axisDirections = [
  16735. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  16736. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  16737. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  16738. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  16739. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  16740. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  16741. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  16742. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  16743. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  16744. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  16745. ];
  16746. const _origin = /*@__PURE__*/ new Vector3();
  16747. // maps blur materials to their uniforms dictionary
  16748. const _uniformsMap = new WeakMap();
  16749. // WebGPU Face indices
  16750. const _faceLib = [
  16751. 3, 1, 5,
  16752. 0, 4, 2
  16753. ];
  16754. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  16755. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  16756. /**
  16757. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  16758. * (PMREM) from a cubeMap environment texture. This allows different levels of
  16759. * blur to be quickly accessed based on material roughness. It is packed into a
  16760. * special CubeUV format that allows us to perform custom interpolation so that
  16761. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  16762. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  16763. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  16764. * higher roughness levels. In this way we maintain resolution to smoothly
  16765. * interpolate diffuse lighting while limiting sampling computation.
  16766. *
  16767. * Paper: Fast, Accurate Image-Based Lighting:
  16768. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  16769. */
  16770. class PMREMGenerator {
  16771. /**
  16772. * Constructs a new PMREM generator.
  16773. *
  16774. * @param {Renderer} renderer - The renderer.
  16775. */
  16776. constructor( renderer ) {
  16777. this._renderer = renderer;
  16778. this._pingPongRenderTarget = null;
  16779. this._lodMax = 0;
  16780. this._cubeSize = 0;
  16781. this._lodPlanes = [];
  16782. this._sizeLods = [];
  16783. this._sigmas = [];
  16784. this._lodMeshes = [];
  16785. this._blurMaterial = null;
  16786. this._cubemapMaterial = null;
  16787. this._equirectMaterial = null;
  16788. this._backgroundBox = null;
  16789. }
  16790. get _hasInitialized() {
  16791. return this._renderer.hasInitialized();
  16792. }
  16793. /**
  16794. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16795. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16796. * in radians to be applied to the scene before PMREM generation. Optional near
  16797. * and far planes ensure the scene is rendered in its entirety.
  16798. *
  16799. * @param {Scene} scene - The scene to be captured.
  16800. * @param {number} [sigma=0] - The blur radius in radians.
  16801. * @param {number} [near=0.1] - The near plane distance.
  16802. * @param {number} [far=100] - The far plane distance.
  16803. * @param {Object} [options={}] - The configuration options.
  16804. * @param {number} [options.size=256] - The texture size of the PMREM.
  16805. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  16806. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16807. * @return {RenderTarget} The resulting PMREM.
  16808. * @see {@link PMREMGenerator#fromSceneAsync}
  16809. */
  16810. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16811. const {
  16812. size = 256,
  16813. position = _origin,
  16814. renderTarget = null,
  16815. } = options;
  16816. this._setSize( size );
  16817. if ( this._hasInitialized === false ) {
  16818. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  16819. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16820. options.renderTarget = cubeUVRenderTarget;
  16821. this.fromSceneAsync( scene, sigma, near, far, options );
  16822. return cubeUVRenderTarget;
  16823. }
  16824. _oldTarget = this._renderer.getRenderTarget();
  16825. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16826. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16827. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16828. cubeUVRenderTarget.depthBuffer = true;
  16829. this._init( cubeUVRenderTarget );
  16830. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  16831. if ( sigma > 0 ) {
  16832. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  16833. }
  16834. this._applyPMREM( cubeUVRenderTarget );
  16835. this._cleanup( cubeUVRenderTarget );
  16836. return cubeUVRenderTarget;
  16837. }
  16838. /**
  16839. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16840. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16841. * in radians to be applied to the scene before PMREM generation. Optional near
  16842. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  16843. * is placed at the origin).
  16844. *
  16845. * @param {Scene} scene - The scene to be captured.
  16846. * @param {number} [sigma=0] - The blur radius in radians.
  16847. * @param {number} [near=0.1] - The near plane distance.
  16848. * @param {number} [far=100] - The far plane distance.
  16849. * @param {Object} [options={}] - The configuration options.
  16850. * @param {number} [options.size=256] - The texture size of the PMREM.
  16851. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  16852. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16853. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  16854. * @see {@link PMREMGenerator#fromScene}
  16855. */
  16856. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16857. if ( this._hasInitialized === false ) await this._renderer.init();
  16858. return this.fromScene( scene, sigma, near, far, options );
  16859. }
  16860. /**
  16861. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16862. * or HDR. The ideal input image size is 1k (1024 x 512),
  16863. * as this matches best with the 256 x 256 cubemap output.
  16864. *
  16865. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16866. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16867. * @return {RenderTarget} The resulting PMREM.
  16868. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  16869. */
  16870. fromEquirectangular( equirectangular, renderTarget = null ) {
  16871. if ( this._hasInitialized === false ) {
  16872. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16873. this._setSizeFromTexture( equirectangular );
  16874. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16875. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16876. return cubeUVRenderTarget;
  16877. }
  16878. return this._fromTexture( equirectangular, renderTarget );
  16879. }
  16880. /**
  16881. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16882. * or HDR. The ideal input image size is 1k (1024 x 512),
  16883. * as this matches best with the 256 x 256 cubemap output.
  16884. *
  16885. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16886. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16887. * @return {Promise<RenderTarget>} The resulting PMREM.
  16888. * @see {@link PMREMGenerator#fromEquirectangular}
  16889. */
  16890. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16891. if ( this._hasInitialized === false ) await this._renderer.init();
  16892. return this._fromTexture( equirectangular, renderTarget );
  16893. }
  16894. /**
  16895. * Generates a PMREM from an cubemap texture, which can be either LDR
  16896. * or HDR. The ideal input cube size is 256 x 256,
  16897. * as this matches best with the 256 x 256 cubemap output.
  16898. *
  16899. * @param {Texture} cubemap - The cubemap texture to be converted.
  16900. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16901. * @return {RenderTarget} The resulting PMREM.
  16902. * @see {@link PMREMGenerator#fromCubemapAsync}
  16903. */
  16904. fromCubemap( cubemap, renderTarget = null ) {
  16905. if ( this._hasInitialized === false ) {
  16906. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16907. this._setSizeFromTexture( cubemap );
  16908. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16909. this.fromCubemapAsync( cubemap, renderTarget );
  16910. return cubeUVRenderTarget;
  16911. }
  16912. return this._fromTexture( cubemap, renderTarget );
  16913. }
  16914. /**
  16915. * Generates a PMREM from an cubemap texture, which can be either LDR
  16916. * or HDR. The ideal input cube size is 256 x 256,
  16917. * with the 256 x 256 cubemap output.
  16918. *
  16919. * @param {Texture} cubemap - The cubemap texture to be converted.
  16920. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16921. * @return {Promise<RenderTarget>} The resulting PMREM.
  16922. * @see {@link PMREMGenerator#fromCubemap}
  16923. */
  16924. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16925. if ( this._hasInitialized === false ) await this._renderer.init();
  16926. return this._fromTexture( cubemap, renderTarget );
  16927. }
  16928. /**
  16929. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16930. * your texture's network fetch for increased concurrency.
  16931. *
  16932. * @returns {Promise}
  16933. */
  16934. async compileCubemapShader() {
  16935. if ( this._cubemapMaterial === null ) {
  16936. this._cubemapMaterial = _getCubemapMaterial();
  16937. await this._compileMaterial( this._cubemapMaterial );
  16938. }
  16939. }
  16940. /**
  16941. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16942. * your texture's network fetch for increased concurrency.
  16943. *
  16944. * @returns {Promise}
  16945. */
  16946. async compileEquirectangularShader() {
  16947. if ( this._equirectMaterial === null ) {
  16948. this._equirectMaterial = _getEquirectMaterial();
  16949. await this._compileMaterial( this._equirectMaterial );
  16950. }
  16951. }
  16952. /**
  16953. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16954. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16955. * one of them will cause any others to also become unusable.
  16956. */
  16957. dispose() {
  16958. this._dispose();
  16959. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16960. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16961. if ( this._backgroundBox !== null ) {
  16962. this._backgroundBox.geometry.dispose();
  16963. this._backgroundBox.material.dispose();
  16964. }
  16965. }
  16966. // private interface
  16967. _setSizeFromTexture( texture ) {
  16968. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16969. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16970. } else { // Equirectangular
  16971. this._setSize( texture.image.width / 4 );
  16972. }
  16973. }
  16974. _setSize( cubeSize ) {
  16975. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16976. this._cubeSize = Math.pow( 2, this._lodMax );
  16977. }
  16978. _dispose() {
  16979. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16980. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16981. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16982. this._lodPlanes[ i ].dispose();
  16983. }
  16984. }
  16985. _cleanup( outputTarget ) {
  16986. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16987. outputTarget.scissorTest = false;
  16988. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16989. }
  16990. _fromTexture( texture, renderTarget ) {
  16991. this._setSizeFromTexture( texture );
  16992. _oldTarget = this._renderer.getRenderTarget();
  16993. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16994. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16995. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16996. this._init( cubeUVRenderTarget );
  16997. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16998. this._applyPMREM( cubeUVRenderTarget );
  16999. this._cleanup( cubeUVRenderTarget );
  17000. return cubeUVRenderTarget;
  17001. }
  17002. _allocateTarget() {
  17003. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17004. const height = 4 * this._cubeSize;
  17005. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17006. return cubeUVRenderTarget;
  17007. }
  17008. _init( renderTarget ) {
  17009. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17010. if ( this._pingPongRenderTarget !== null ) {
  17011. this._dispose();
  17012. }
  17013. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17014. const { _lodMax } = this;
  17015. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  17016. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17017. }
  17018. }
  17019. async _compileMaterial( material ) {
  17020. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  17021. await this._renderer.compile( tmpMesh, _flatCamera );
  17022. }
  17023. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17024. const cubeCamera = _cubeCamera;
  17025. cubeCamera.near = near;
  17026. cubeCamera.far = far;
  17027. // px, py, pz, nx, ny, nz
  17028. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17029. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17030. const renderer = this._renderer;
  17031. const originalAutoClear = renderer.autoClear;
  17032. renderer.getClearColor( _clearColor$2 );
  17033. renderer.autoClear = false;
  17034. let backgroundBox = this._backgroundBox;
  17035. if ( backgroundBox === null ) {
  17036. const backgroundMaterial = new MeshBasicMaterial( {
  17037. name: 'PMREM.Background',
  17038. side: BackSide,
  17039. depthWrite: false,
  17040. depthTest: false
  17041. } );
  17042. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  17043. }
  17044. let useSolidColor = false;
  17045. const background = scene.background;
  17046. if ( background ) {
  17047. if ( background.isColor ) {
  17048. backgroundBox.material.color.copy( background );
  17049. scene.background = null;
  17050. useSolidColor = true;
  17051. }
  17052. } else {
  17053. backgroundBox.material.color.copy( _clearColor$2 );
  17054. useSolidColor = true;
  17055. }
  17056. renderer.setRenderTarget( cubeUVRenderTarget );
  17057. renderer.clear();
  17058. if ( useSolidColor ) {
  17059. renderer.render( backgroundBox, cubeCamera );
  17060. }
  17061. for ( let i = 0; i < 6; i ++ ) {
  17062. const col = i % 3;
  17063. if ( col === 0 ) {
  17064. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17065. cubeCamera.position.set( position.x, position.y, position.z );
  17066. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17067. } else if ( col === 1 ) {
  17068. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17069. cubeCamera.position.set( position.x, position.y, position.z );
  17070. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17071. } else {
  17072. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17073. cubeCamera.position.set( position.x, position.y, position.z );
  17074. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17075. }
  17076. const size = this._cubeSize;
  17077. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17078. renderer.render( scene, cubeCamera );
  17079. }
  17080. renderer.autoClear = originalAutoClear;
  17081. scene.background = background;
  17082. }
  17083. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17084. const renderer = this._renderer;
  17085. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17086. if ( isCubeTexture ) {
  17087. if ( this._cubemapMaterial === null ) {
  17088. this._cubemapMaterial = _getCubemapMaterial( texture );
  17089. }
  17090. } else {
  17091. if ( this._equirectMaterial === null ) {
  17092. this._equirectMaterial = _getEquirectMaterial( texture );
  17093. }
  17094. }
  17095. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17096. material.fragmentNode.value = texture;
  17097. const mesh = this._lodMeshes[ 0 ];
  17098. mesh.material = material;
  17099. const size = this._cubeSize;
  17100. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17101. renderer.setRenderTarget( cubeUVRenderTarget );
  17102. renderer.render( mesh, _flatCamera );
  17103. }
  17104. _applyPMREM( cubeUVRenderTarget ) {
  17105. const renderer = this._renderer;
  17106. const autoClear = renderer.autoClear;
  17107. renderer.autoClear = false;
  17108. const n = this._lodPlanes.length;
  17109. for ( let i = 1; i < n; i ++ ) {
  17110. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  17111. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  17112. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  17113. }
  17114. renderer.autoClear = autoClear;
  17115. }
  17116. /**
  17117. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17118. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17119. * the blur latitudinally (around the poles), and then longitudinally (towards
  17120. * the poles) to approximate the orthogonally-separable blur. It is least
  17121. * accurate at the poles, but still does a decent job.
  17122. *
  17123. * @private
  17124. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17125. * @param {number} lodIn - The input level-of-detail.
  17126. * @param {number} lodOut - The output level-of-detail.
  17127. * @param {number} sigma - The blur radius in radians.
  17128. * @param {Vector3} [poleAxis] - The pole axis.
  17129. */
  17130. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17131. const pingPongRenderTarget = this._pingPongRenderTarget;
  17132. this._halfBlur(
  17133. cubeUVRenderTarget,
  17134. pingPongRenderTarget,
  17135. lodIn,
  17136. lodOut,
  17137. sigma,
  17138. 'latitudinal',
  17139. poleAxis );
  17140. this._halfBlur(
  17141. pingPongRenderTarget,
  17142. cubeUVRenderTarget,
  17143. lodOut,
  17144. lodOut,
  17145. sigma,
  17146. 'longitudinal',
  17147. poleAxis );
  17148. }
  17149. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17150. const renderer = this._renderer;
  17151. const blurMaterial = this._blurMaterial;
  17152. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17153. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  17154. }
  17155. // Number of standard deviations at which to cut off the discrete approximation.
  17156. const STANDARD_DEVIATIONS = 3;
  17157. const blurMesh = this._lodMeshes[ lodOut ];
  17158. blurMesh.material = blurMaterial;
  17159. const blurUniforms = _uniformsMap.get( blurMaterial );
  17160. const pixels = this._sizeLods[ lodIn ] - 1;
  17161. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17162. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17163. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17164. if ( samples > MAX_SAMPLES ) {
  17165. console.warn( `sigmaRadians, ${
  17166. sigmaRadians}, is too large and will clip, as it requested ${
  17167. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17168. }
  17169. const weights = [];
  17170. let sum = 0;
  17171. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17172. const x = i / sigmaPixels;
  17173. const weight = Math.exp( - x * x / 2 );
  17174. weights.push( weight );
  17175. if ( i === 0 ) {
  17176. sum += weight;
  17177. } else if ( i < samples ) {
  17178. sum += 2 * weight;
  17179. }
  17180. }
  17181. for ( let i = 0; i < weights.length; i ++ ) {
  17182. weights[ i ] = weights[ i ] / sum;
  17183. }
  17184. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17185. blurUniforms.envMap.value = targetIn.texture;
  17186. blurUniforms.samples.value = samples;
  17187. blurUniforms.weights.array = weights;
  17188. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17189. if ( poleAxis ) {
  17190. blurUniforms.poleAxis.value = poleAxis;
  17191. }
  17192. const { _lodMax } = this;
  17193. blurUniforms.dTheta.value = radiansPerPixel;
  17194. blurUniforms.mipInt.value = _lodMax - lodIn;
  17195. const outputSize = this._sizeLods[ lodOut ];
  17196. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17197. const y = 4 * ( this._cubeSize - outputSize );
  17198. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17199. renderer.setRenderTarget( targetOut );
  17200. renderer.render( blurMesh, _flatCamera );
  17201. }
  17202. }
  17203. function _createPlanes( lodMax ) {
  17204. const lodPlanes = [];
  17205. const sizeLods = [];
  17206. const sigmas = [];
  17207. const lodMeshes = [];
  17208. let lod = lodMax;
  17209. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17210. for ( let i = 0; i < totalLods; i ++ ) {
  17211. const sizeLod = Math.pow( 2, lod );
  17212. sizeLods.push( sizeLod );
  17213. let sigma = 1.0 / sizeLod;
  17214. if ( i > lodMax - LOD_MIN ) {
  17215. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17216. } else if ( i === 0 ) {
  17217. sigma = 0;
  17218. }
  17219. sigmas.push( sigma );
  17220. const texelSize = 1.0 / ( sizeLod - 2 );
  17221. const min = - texelSize;
  17222. const max = 1 + texelSize;
  17223. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17224. const cubeFaces = 6;
  17225. const vertices = 6;
  17226. const positionSize = 3;
  17227. const uvSize = 2;
  17228. const faceIndexSize = 1;
  17229. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17230. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17231. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17232. for ( let face = 0; face < cubeFaces; face ++ ) {
  17233. const x = ( face % 3 ) * 2 / 3 - 1;
  17234. const y = face > 2 ? 0 : -1;
  17235. const coordinates = [
  17236. x, y, 0,
  17237. x + 2 / 3, y, 0,
  17238. x + 2 / 3, y + 1, 0,
  17239. x, y, 0,
  17240. x + 2 / 3, y + 1, 0,
  17241. x, y + 1, 0
  17242. ];
  17243. const faceIdx = _faceLib[ face ];
  17244. position.set( coordinates, positionSize * vertices * faceIdx );
  17245. uv.set( uv1, uvSize * vertices * faceIdx );
  17246. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17247. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17248. }
  17249. const planes = new BufferGeometry();
  17250. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17251. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17252. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17253. lodPlanes.push( planes );
  17254. lodMeshes.push( new Mesh( planes, null ) );
  17255. if ( lod > LOD_MIN ) {
  17256. lod --;
  17257. }
  17258. }
  17259. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17260. }
  17261. function _createRenderTarget( width, height ) {
  17262. const params = {
  17263. magFilter: LinearFilter,
  17264. minFilter: LinearFilter,
  17265. generateMipmaps: false,
  17266. type: HalfFloatType,
  17267. format: RGBAFormat,
  17268. colorSpace: LinearSRGBColorSpace,
  17269. //depthBuffer: false
  17270. };
  17271. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17272. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17273. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17274. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17275. cubeUVRenderTarget.scissorTest = true;
  17276. return cubeUVRenderTarget;
  17277. }
  17278. function _setViewport( target, x, y, width, height ) {
  17279. target.viewport.set( x, y, width, height );
  17280. target.scissor.set( x, y, width, height );
  17281. }
  17282. function _getMaterial( type ) {
  17283. const material = new NodeMaterial();
  17284. material.depthTest = false;
  17285. material.depthWrite = false;
  17286. material.blending = NoBlending;
  17287. material.name = `PMREM_${ type }`;
  17288. return material;
  17289. }
  17290. function _getBlurShader( lodMax, width, height ) {
  17291. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17292. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17293. const dTheta = uniform( 0 );
  17294. const n = float( MAX_SAMPLES );
  17295. const latitudinal = uniform( 0 ); // false, bool
  17296. const samples = uniform( 1 ); // int
  17297. const envMap = texture( null );
  17298. const mipInt = uniform( 0 ); // int
  17299. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17300. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17301. const CUBEUV_MAX_MIP = float( lodMax );
  17302. const materialUniforms = {
  17303. n,
  17304. latitudinal,
  17305. weights,
  17306. poleAxis,
  17307. outputDirection: _outputDirection,
  17308. dTheta,
  17309. samples,
  17310. envMap,
  17311. mipInt,
  17312. CUBEUV_TEXEL_WIDTH,
  17313. CUBEUV_TEXEL_HEIGHT,
  17314. CUBEUV_MAX_MIP
  17315. };
  17316. const material = _getMaterial( 'blur' );
  17317. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17318. _uniformsMap.set( material, materialUniforms );
  17319. return material;
  17320. }
  17321. function _getCubemapMaterial( envTexture ) {
  17322. const material = _getMaterial( 'cubemap' );
  17323. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17324. return material;
  17325. }
  17326. function _getEquirectMaterial( envTexture ) {
  17327. const material = _getMaterial( 'equirect' );
  17328. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17329. return material;
  17330. }
  17331. const _cache = new WeakMap();
  17332. /**
  17333. * Generates the cubeUV size based on the given image height.
  17334. *
  17335. * @private
  17336. * @param {number} imageHeight - The image height.
  17337. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17338. */
  17339. function _generateCubeUVSize( imageHeight ) {
  17340. const maxMip = Math.log2( imageHeight ) - 2;
  17341. const texelHeight = 1.0 / imageHeight;
  17342. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17343. return { texelWidth, texelHeight, maxMip };
  17344. }
  17345. /**
  17346. * Generates a PMREM from the given texture.
  17347. *
  17348. * @private
  17349. * @param {Texture} texture - The texture to create the PMREM for.
  17350. * @param {Renderer} renderer - The renderer.
  17351. * @param {PMREMGenerator} generator - The PMREM generator.
  17352. * @return {?Texture} The PMREM.
  17353. */
  17354. function _getPMREMFromTexture( texture, renderer, generator ) {
  17355. const cache = _getCache( renderer );
  17356. let cacheTexture = cache.get( texture );
  17357. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17358. if ( pmremVersion !== texture.pmremVersion ) {
  17359. const image = texture.image;
  17360. if ( texture.isCubeTexture ) {
  17361. if ( isCubeMapReady( image ) ) {
  17362. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17363. } else {
  17364. return null;
  17365. }
  17366. } else {
  17367. if ( isEquirectangularMapReady( image ) ) {
  17368. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17369. } else {
  17370. return null;
  17371. }
  17372. }
  17373. cacheTexture.pmremVersion = texture.pmremVersion;
  17374. cache.set( texture, cacheTexture );
  17375. }
  17376. return cacheTexture.texture;
  17377. }
  17378. /**
  17379. * Returns a cache that stores generated PMREMs for the respective textures.
  17380. * A cache must be maintained per renderer since PMREMs are render target textures
  17381. * which can't be shared across render contexts.
  17382. *
  17383. * @private
  17384. * @param {Renderer} renderer - The renderer.
  17385. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17386. */
  17387. function _getCache( renderer ) {
  17388. let rendererCache = _cache.get( renderer );
  17389. if ( rendererCache === undefined ) {
  17390. rendererCache = new WeakMap();
  17391. _cache.set( renderer, rendererCache );
  17392. }
  17393. return rendererCache;
  17394. }
  17395. /**
  17396. * This node represents a PMREM which is a special type of preprocessed
  17397. * environment map intended for PBR materials.
  17398. *
  17399. * ```js
  17400. * const material = new MeshStandardNodeMaterial();
  17401. * material.envNode = pmremTexture( envMap );
  17402. * ```
  17403. *
  17404. * @augments TempNode
  17405. */
  17406. class PMREMNode extends TempNode {
  17407. static get type() {
  17408. return 'PMREMNode';
  17409. }
  17410. /**
  17411. * Constructs a new function overloading node.
  17412. *
  17413. * @param {Texture} value - The input texture.
  17414. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17415. * @param {Node<float>} [levelNode=null] - The level node.
  17416. */
  17417. constructor( value, uvNode = null, levelNode = null ) {
  17418. super( 'vec3' );
  17419. /**
  17420. * Reference to the input texture.
  17421. *
  17422. * @private
  17423. * @type {Texture}
  17424. */
  17425. this._value = value;
  17426. /**
  17427. * Reference to the generated PMREM.
  17428. *
  17429. * @private
  17430. * @type {Texture | null}
  17431. * @default null
  17432. */
  17433. this._pmrem = null;
  17434. /**
  17435. * The uv node.
  17436. *
  17437. * @type {Node<vec2>}
  17438. */
  17439. this.uvNode = uvNode;
  17440. /**
  17441. * The level node.
  17442. *
  17443. * @type {Node<float>}
  17444. */
  17445. this.levelNode = levelNode;
  17446. /**
  17447. * Reference to a PMREM generator.
  17448. *
  17449. * @private
  17450. * @type {?PMREMGenerator}
  17451. * @default null
  17452. */
  17453. this._generator = null;
  17454. const defaultTexture = new Texture();
  17455. defaultTexture.isRenderTargetTexture = true;
  17456. /**
  17457. * The texture node holding the generated PMREM.
  17458. *
  17459. * @private
  17460. * @type {TextureNode}
  17461. */
  17462. this._texture = texture( defaultTexture );
  17463. /**
  17464. * A uniform representing the PMREM's width.
  17465. *
  17466. * @private
  17467. * @type {UniformNode<float>}
  17468. */
  17469. this._width = uniform( 0 );
  17470. /**
  17471. * A uniform representing the PMREM's height.
  17472. *
  17473. * @private
  17474. * @type {UniformNode<float>}
  17475. */
  17476. this._height = uniform( 0 );
  17477. /**
  17478. * A uniform representing the PMREM's max Mip.
  17479. *
  17480. * @private
  17481. * @type {UniformNode<float>}
  17482. */
  17483. this._maxMip = uniform( 0 );
  17484. /**
  17485. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17486. *
  17487. * @type {string}
  17488. * @default 'render'
  17489. */
  17490. this.updateBeforeType = NodeUpdateType.RENDER;
  17491. }
  17492. set value( value ) {
  17493. this._value = value;
  17494. this._pmrem = null;
  17495. }
  17496. /**
  17497. * The node's texture value.
  17498. *
  17499. * @type {Texture}
  17500. */
  17501. get value() {
  17502. return this._value;
  17503. }
  17504. /**
  17505. * Uses the given PMREM texture to update internal values.
  17506. *
  17507. * @param {Texture} texture - The PMREM texture.
  17508. */
  17509. updateFromTexture( texture ) {
  17510. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17511. this._texture.value = texture;
  17512. this._width.value = cubeUVSize.texelWidth;
  17513. this._height.value = cubeUVSize.texelHeight;
  17514. this._maxMip.value = cubeUVSize.maxMip;
  17515. }
  17516. updateBefore( frame ) {
  17517. let pmrem = this._pmrem;
  17518. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17519. const texture = this._value;
  17520. if ( pmremVersion !== texture.pmremVersion ) {
  17521. if ( texture.isPMREMTexture === true ) {
  17522. pmrem = texture;
  17523. } else {
  17524. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17525. }
  17526. if ( pmrem !== null ) {
  17527. this._pmrem = pmrem;
  17528. this.updateFromTexture( pmrem );
  17529. }
  17530. }
  17531. }
  17532. setup( builder ) {
  17533. if ( this._generator === null ) {
  17534. this._generator = new PMREMGenerator( builder.renderer );
  17535. }
  17536. this.updateBefore( builder );
  17537. //
  17538. let uvNode = this.uvNode;
  17539. if ( uvNode === null && builder.context.getUV ) {
  17540. uvNode = builder.context.getUV( this );
  17541. }
  17542. //
  17543. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  17544. //
  17545. let levelNode = this.levelNode;
  17546. if ( levelNode === null && builder.context.getTextureLevel ) {
  17547. levelNode = builder.context.getTextureLevel( this );
  17548. }
  17549. //
  17550. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  17551. }
  17552. dispose() {
  17553. super.dispose();
  17554. if ( this._generator !== null ) this._generator.dispose();
  17555. }
  17556. }
  17557. /**
  17558. * Returns `true` if the given cube map image has been fully loaded.
  17559. *
  17560. * @private
  17561. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  17562. * @return {boolean} Whether the given cube map is ready or not.
  17563. */
  17564. function isCubeMapReady( image ) {
  17565. if ( image === null || image === undefined ) return false;
  17566. let count = 0;
  17567. const length = 6;
  17568. for ( let i = 0; i < length; i ++ ) {
  17569. if ( image[ i ] !== undefined ) count ++;
  17570. }
  17571. return count === length;
  17572. }
  17573. /**
  17574. * Returns `true` if the given equirectangular image has been fully loaded.
  17575. *
  17576. * @private
  17577. * @param {(Image|Object)} image - The equirectangular image.
  17578. * @return {boolean} Whether the given cube map is ready or not.
  17579. */
  17580. function isEquirectangularMapReady( image ) {
  17581. if ( image === null || image === undefined ) return false;
  17582. return image.height > 0;
  17583. }
  17584. /**
  17585. * TSL function for creating a PMREM node.
  17586. *
  17587. * @tsl
  17588. * @function
  17589. * @param {Texture} value - The input texture.
  17590. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  17591. * @param {?Node<float>} [levelNode=null] - The level node.
  17592. * @returns {PMREMNode}
  17593. */
  17594. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  17595. const _envNodeCache = new WeakMap();
  17596. /**
  17597. * Represents a physical model for Image-based lighting (IBL). The environment
  17598. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  17599. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  17600. *
  17601. * @augments LightingNode
  17602. */
  17603. class EnvironmentNode extends LightingNode {
  17604. static get type() {
  17605. return 'EnvironmentNode';
  17606. }
  17607. /**
  17608. * Constructs a new environment node.
  17609. *
  17610. * @param {Node} [envNode=null] - A node representing the environment.
  17611. */
  17612. constructor( envNode = null ) {
  17613. super();
  17614. /**
  17615. * A node representing the environment.
  17616. *
  17617. * @type {?Node}
  17618. * @default null
  17619. */
  17620. this.envNode = envNode;
  17621. }
  17622. setup( builder ) {
  17623. const { material } = builder;
  17624. let envNode = this.envNode;
  17625. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  17626. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  17627. let cacheEnvNode = _envNodeCache.get( value );
  17628. if ( cacheEnvNode === undefined ) {
  17629. cacheEnvNode = pmremTexture( value );
  17630. _envNodeCache.set( value, cacheEnvNode );
  17631. }
  17632. envNode = cacheEnvNode;
  17633. }
  17634. //
  17635. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  17636. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  17637. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  17638. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  17639. const isolateRadiance = cache( radiance );
  17640. const isolateIrradiance = cache( irradiance );
  17641. //
  17642. builder.context.radiance.addAssign( isolateRadiance );
  17643. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  17644. //
  17645. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  17646. if ( clearcoatRadiance ) {
  17647. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  17648. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  17649. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  17650. }
  17651. }
  17652. }
  17653. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  17654. let reflectVec = null;
  17655. return {
  17656. getUV: () => {
  17657. if ( reflectVec === null ) {
  17658. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  17659. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  17660. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  17661. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  17662. }
  17663. return reflectVec;
  17664. },
  17665. getTextureLevel: () => {
  17666. return roughnessNode;
  17667. }
  17668. };
  17669. };
  17670. const createIrradianceContext = ( normalWorldNode ) => {
  17671. return {
  17672. getUV: () => {
  17673. return normalWorldNode;
  17674. },
  17675. getTextureLevel: () => {
  17676. return float( 1.0 );
  17677. }
  17678. };
  17679. };
  17680. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  17681. /**
  17682. * Node material version of {@link MeshStandardMaterial}.
  17683. *
  17684. * @augments NodeMaterial
  17685. */
  17686. class MeshStandardNodeMaterial extends NodeMaterial {
  17687. static get type() {
  17688. return 'MeshStandardNodeMaterial';
  17689. }
  17690. /**
  17691. * Constructs a new mesh standard node material.
  17692. *
  17693. * @param {Object} [parameters] - The configuration parameter.
  17694. */
  17695. constructor( parameters ) {
  17696. super();
  17697. /**
  17698. * This flag can be used for type testing.
  17699. *
  17700. * @type {boolean}
  17701. * @readonly
  17702. * @default true
  17703. */
  17704. this.isMeshStandardNodeMaterial = true;
  17705. /**
  17706. * Set to `true` because standard materials react on lights.
  17707. *
  17708. * @type {boolean}
  17709. * @default true
  17710. */
  17711. this.lights = true;
  17712. /**
  17713. * The emissive color of standard materials is by default inferred from the `emissive`,
  17714. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  17715. * overwrite the default and define the emissive color with a node instead.
  17716. *
  17717. * If you don't want to overwrite the emissive color but modify the existing
  17718. * value instead, use {@link materialEmissive}.
  17719. *
  17720. * @type {?Node<vec3>}
  17721. * @default null
  17722. */
  17723. this.emissiveNode = null;
  17724. /**
  17725. * The metalness of standard materials is by default inferred from the `metalness`,
  17726. * and `metalnessMap` properties. This node property allows to
  17727. * overwrite the default and define the metalness with a node instead.
  17728. *
  17729. * If you don't want to overwrite the metalness but modify the existing
  17730. * value instead, use {@link materialMetalness}.
  17731. *
  17732. * @type {?Node<float>}
  17733. * @default null
  17734. */
  17735. this.metalnessNode = null;
  17736. /**
  17737. * The roughness of standard materials is by default inferred from the `roughness`,
  17738. * and `roughnessMap` properties. This node property allows to
  17739. * overwrite the default and define the roughness with a node instead.
  17740. *
  17741. * If you don't want to overwrite the roughness but modify the existing
  17742. * value instead, use {@link materialRoughness}.
  17743. *
  17744. * @type {?Node<float>}
  17745. * @default null
  17746. */
  17747. this.roughnessNode = null;
  17748. this.setDefaultValues( _defaultValues$6 );
  17749. this.setValues( parameters );
  17750. }
  17751. /**
  17752. * Overwritten since this type of material uses {@link EnvironmentNode}
  17753. * to implement the PBR (PMREM based) environment mapping. Besides, the
  17754. * method honors `Scene.environment`.
  17755. *
  17756. * @param {NodeBuilder} builder - The current node builder.
  17757. * @return {?EnvironmentNode<vec3>} The environment node.
  17758. */
  17759. setupEnvironment( builder ) {
  17760. let envNode = super.setupEnvironment( builder );
  17761. if ( envNode === null && builder.environmentNode ) {
  17762. envNode = builder.environmentNode;
  17763. }
  17764. return envNode ? new EnvironmentNode( envNode ) : null;
  17765. }
  17766. /**
  17767. * Setups the lighting model.
  17768. *
  17769. * @return {PhysicalLightingModel} The lighting model.
  17770. */
  17771. setupLightingModel( /*builder*/ ) {
  17772. return new PhysicalLightingModel();
  17773. }
  17774. /**
  17775. * Setups the specular related node variables.
  17776. */
  17777. setupSpecular() {
  17778. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  17779. specularColor.assign( specularColorNode );
  17780. specularF90.assign( 1.0 );
  17781. }
  17782. /**
  17783. * Setups the standard specific node variables.
  17784. *
  17785. * @param {NodeBuilder} builder - The current node builder.
  17786. */
  17787. setupVariants() {
  17788. // METALNESS
  17789. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  17790. metalness.assign( metalnessNode );
  17791. // ROUGHNESS
  17792. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  17793. roughnessNode = getRoughness( { roughness: roughnessNode } );
  17794. roughness.assign( roughnessNode );
  17795. // SPECULAR COLOR
  17796. this.setupSpecular();
  17797. // DIFFUSE COLOR
  17798. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  17799. }
  17800. copy( source ) {
  17801. this.emissiveNode = source.emissiveNode;
  17802. this.metalnessNode = source.metalnessNode;
  17803. this.roughnessNode = source.roughnessNode;
  17804. return super.copy( source );
  17805. }
  17806. }
  17807. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  17808. /**
  17809. * Node material version of {@link MeshPhysicalMaterial}.
  17810. *
  17811. * @augments MeshStandardNodeMaterial
  17812. */
  17813. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  17814. static get type() {
  17815. return 'MeshPhysicalNodeMaterial';
  17816. }
  17817. /**
  17818. * Constructs a new mesh physical node material.
  17819. *
  17820. * @param {Object} [parameters] - The configuration parameter.
  17821. */
  17822. constructor( parameters ) {
  17823. super();
  17824. /**
  17825. * This flag can be used for type testing.
  17826. *
  17827. * @type {boolean}
  17828. * @readonly
  17829. * @default true
  17830. */
  17831. this.isMeshPhysicalNodeMaterial = true;
  17832. /**
  17833. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  17834. * and `clearcoatMap` properties. This node property allows to overwrite the default
  17835. * and define the clearcoat with a node instead.
  17836. *
  17837. * If you don't want to overwrite the clearcoat but modify the existing
  17838. * value instead, use {@link materialClearcoat}.
  17839. *
  17840. * @type {?Node<float>}
  17841. * @default null
  17842. */
  17843. this.clearcoatNode = null;
  17844. /**
  17845. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  17846. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  17847. * and define the clearcoat roughness with a node instead.
  17848. *
  17849. * If you don't want to overwrite the clearcoat roughness but modify the existing
  17850. * value instead, use {@link materialClearcoatRoughness}.
  17851. *
  17852. * @type {?Node<float>}
  17853. * @default null
  17854. */
  17855. this.clearcoatRoughnessNode = null;
  17856. /**
  17857. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  17858. * property. This node property allows to overwrite the default
  17859. * and define the clearcoat normal with a node instead.
  17860. *
  17861. * If you don't want to overwrite the clearcoat normal but modify the existing
  17862. * value instead, use {@link materialClearcoatNormal}.
  17863. *
  17864. * @type {?Node<vec3>}
  17865. * @default null
  17866. */
  17867. this.clearcoatNormalNode = null;
  17868. /**
  17869. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  17870. * and `sheenColorMap` properties. This node property allows to overwrite the default
  17871. * and define the sheen with a node instead.
  17872. *
  17873. * If you don't want to overwrite the sheen but modify the existing
  17874. * value instead, use {@link materialSheen}.
  17875. *
  17876. * @type {?Node<vec3>}
  17877. * @default null
  17878. */
  17879. this.sheenNode = null;
  17880. /**
  17881. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  17882. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  17883. * and define the sheen roughness with a node instead.
  17884. *
  17885. * If you don't want to overwrite the sheen roughness but modify the existing
  17886. * value instead, use {@link materialSheenRoughness}.
  17887. *
  17888. * @type {?Node<float>}
  17889. * @default null
  17890. */
  17891. this.sheenRoughnessNode = null;
  17892. /**
  17893. * The iridescence of physical materials is by default inferred from the `iridescence`
  17894. * property. This node property allows to overwrite the default
  17895. * and define the iridescence with a node instead.
  17896. *
  17897. * If you don't want to overwrite the iridescence but modify the existing
  17898. * value instead, use {@link materialIridescence}.
  17899. *
  17900. * @type {?Node<float>}
  17901. * @default null
  17902. */
  17903. this.iridescenceNode = null;
  17904. /**
  17905. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  17906. * property. This node property allows to overwrite the default
  17907. * and define the iridescence IOR with a node instead.
  17908. *
  17909. * If you don't want to overwrite the iridescence IOR but modify the existing
  17910. * value instead, use {@link materialIridescenceIOR}.
  17911. *
  17912. * @type {?Node<float>}
  17913. * @default null
  17914. */
  17915. this.iridescenceIORNode = null;
  17916. /**
  17917. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  17918. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  17919. * and define the iridescence thickness with a node instead.
  17920. *
  17921. * If you don't want to overwrite the iridescence thickness but modify the existing
  17922. * value instead, use {@link materialIridescenceThickness}.
  17923. *
  17924. * @type {?Node<float>}
  17925. * @default null
  17926. */
  17927. this.iridescenceThicknessNode = null;
  17928. /**
  17929. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  17930. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  17931. * and define the specular intensity with a node instead.
  17932. *
  17933. * If you don't want to overwrite the specular intensity but modify the existing
  17934. * value instead, use {@link materialSpecularIntensity}.
  17935. *
  17936. * @type {?Node<float>}
  17937. * @default null
  17938. */
  17939. this.specularIntensityNode = null;
  17940. /**
  17941. * The specular color of physical materials is by default inferred from the `specularColor`
  17942. * and `specularColorMap` properties. This node property allows to overwrite the default
  17943. * and define the specular color with a node instead.
  17944. *
  17945. * If you don't want to overwrite the specular color but modify the existing
  17946. * value instead, use {@link materialSpecularColor}.
  17947. *
  17948. * @type {?Node<vec3>}
  17949. * @default null
  17950. */
  17951. this.specularColorNode = null;
  17952. /**
  17953. * The ior of physical materials is by default inferred from the `ior`
  17954. * property. This node property allows to overwrite the default
  17955. * and define the ior with a node instead.
  17956. *
  17957. * If you don't want to overwrite the ior but modify the existing
  17958. * value instead, use {@link materialIOR}.
  17959. *
  17960. * @type {?Node<float>}
  17961. * @default null
  17962. */
  17963. this.iorNode = null;
  17964. /**
  17965. * The transmission of physical materials is by default inferred from the `transmission` and
  17966. * `transmissionMap` properties. This node property allows to overwrite the default
  17967. * and define the transmission with a node instead.
  17968. *
  17969. * If you don't want to overwrite the transmission but modify the existing
  17970. * value instead, use {@link materialTransmission}.
  17971. *
  17972. * @type {?Node<float>}
  17973. * @default null
  17974. */
  17975. this.transmissionNode = null;
  17976. /**
  17977. * The thickness of physical materials is by default inferred from the `thickness` and
  17978. * `thicknessMap` properties. This node property allows to overwrite the default
  17979. * and define the thickness with a node instead.
  17980. *
  17981. * If you don't want to overwrite the thickness but modify the existing
  17982. * value instead, use {@link materialThickness}.
  17983. *
  17984. * @type {?Node<float>}
  17985. * @default null
  17986. */
  17987. this.thicknessNode = null;
  17988. /**
  17989. * The attenuation distance of physical materials is by default inferred from the
  17990. * `attenuationDistance` property. This node property allows to overwrite the default
  17991. * and define the attenuation distance with a node instead.
  17992. *
  17993. * If you don't want to overwrite the attenuation distance but modify the existing
  17994. * value instead, use {@link materialAttenuationDistance}.
  17995. *
  17996. * @type {?Node<float>}
  17997. * @default null
  17998. */
  17999. this.attenuationDistanceNode = null;
  18000. /**
  18001. * The attenuation color of physical materials is by default inferred from the
  18002. * `attenuationColor` property. This node property allows to overwrite the default
  18003. * and define the attenuation color with a node instead.
  18004. *
  18005. * If you don't want to overwrite the attenuation color but modify the existing
  18006. * value instead, use {@link materialAttenuationColor}.
  18007. *
  18008. * @type {?Node<vec3>}
  18009. * @default null
  18010. */
  18011. this.attenuationColorNode = null;
  18012. /**
  18013. * The dispersion of physical materials is by default inferred from the
  18014. * `dispersion` property. This node property allows to overwrite the default
  18015. * and define the dispersion with a node instead.
  18016. *
  18017. * If you don't want to overwrite the dispersion but modify the existing
  18018. * value instead, use {@link materialDispersion}.
  18019. *
  18020. * @type {?Node<float>}
  18021. * @default null
  18022. */
  18023. this.dispersionNode = null;
  18024. /**
  18025. * The anisotropy of physical materials is by default inferred from the
  18026. * `anisotropy` property. This node property allows to overwrite the default
  18027. * and define the anisotropy with a node instead.
  18028. *
  18029. * If you don't want to overwrite the anisotropy but modify the existing
  18030. * value instead, use {@link materialAnisotropy}.
  18031. *
  18032. * @type {?Node<float>}
  18033. * @default null
  18034. */
  18035. this.anisotropyNode = null;
  18036. this.setDefaultValues( _defaultValues$5 );
  18037. this.setValues( parameters );
  18038. }
  18039. /**
  18040. * Whether the lighting model should use clearcoat or not.
  18041. *
  18042. * @type {boolean}
  18043. * @default true
  18044. */
  18045. get useClearcoat() {
  18046. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18047. }
  18048. /**
  18049. * Whether the lighting model should use iridescence or not.
  18050. *
  18051. * @type {boolean}
  18052. * @default true
  18053. */
  18054. get useIridescence() {
  18055. return this.iridescence > 0 || this.iridescenceNode !== null;
  18056. }
  18057. /**
  18058. * Whether the lighting model should use sheen or not.
  18059. *
  18060. * @type {boolean}
  18061. * @default true
  18062. */
  18063. get useSheen() {
  18064. return this.sheen > 0 || this.sheenNode !== null;
  18065. }
  18066. /**
  18067. * Whether the lighting model should use anisotropy or not.
  18068. *
  18069. * @type {boolean}
  18070. * @default true
  18071. */
  18072. get useAnisotropy() {
  18073. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18074. }
  18075. /**
  18076. * Whether the lighting model should use transmission or not.
  18077. *
  18078. * @type {boolean}
  18079. * @default true
  18080. */
  18081. get useTransmission() {
  18082. return this.transmission > 0 || this.transmissionNode !== null;
  18083. }
  18084. /**
  18085. * Whether the lighting model should use dispersion or not.
  18086. *
  18087. * @type {boolean}
  18088. * @default true
  18089. */
  18090. get useDispersion() {
  18091. return this.dispersion > 0 || this.dispersionNode !== null;
  18092. }
  18093. /**
  18094. * Setups the specular related node variables.
  18095. */
  18096. setupSpecular() {
  18097. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18098. ior.assign( iorNode );
  18099. 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 ) );
  18100. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18101. }
  18102. /**
  18103. * Setups the lighting model.
  18104. *
  18105. * @return {PhysicalLightingModel} The lighting model.
  18106. */
  18107. setupLightingModel( /*builder*/ ) {
  18108. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18109. }
  18110. /**
  18111. * Setups the physical specific node variables.
  18112. *
  18113. * @param {NodeBuilder} builder - The current node builder.
  18114. */
  18115. setupVariants( builder ) {
  18116. super.setupVariants( builder );
  18117. // CLEARCOAT
  18118. if ( this.useClearcoat ) {
  18119. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18120. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18121. clearcoat.assign( clearcoatNode );
  18122. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18123. }
  18124. // SHEEN
  18125. if ( this.useSheen ) {
  18126. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18127. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18128. sheen.assign( sheenNode );
  18129. sheenRoughness.assign( sheenRoughnessNode );
  18130. }
  18131. // IRIDESCENCE
  18132. if ( this.useIridescence ) {
  18133. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18134. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18135. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18136. iridescence.assign( iridescenceNode );
  18137. iridescenceIOR.assign( iridescenceIORNode );
  18138. iridescenceThickness.assign( iridescenceThicknessNode );
  18139. }
  18140. // ANISOTROPY
  18141. if ( this.useAnisotropy ) {
  18142. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18143. anisotropy.assign( anisotropyV.length() );
  18144. If( anisotropy.equal( 0.0 ), () => {
  18145. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18146. } ).Else( () => {
  18147. anisotropyV.divAssign( vec2( anisotropy ) );
  18148. anisotropy.assign( anisotropy.saturate() );
  18149. } );
  18150. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18151. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18152. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18153. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18154. }
  18155. // TRANSMISSION
  18156. if ( this.useTransmission ) {
  18157. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  18158. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  18159. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  18160. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  18161. transmission.assign( transmissionNode );
  18162. thickness.assign( thicknessNode );
  18163. attenuationDistance.assign( attenuationDistanceNode );
  18164. attenuationColor.assign( attenuationColorNode );
  18165. if ( this.useDispersion ) {
  18166. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  18167. dispersion.assign( dispersionNode );
  18168. }
  18169. }
  18170. }
  18171. /**
  18172. * Setups the clearcoat normal node.
  18173. *
  18174. * @return {Node<vec3>} The clearcoat normal.
  18175. */
  18176. setupClearcoatNormal() {
  18177. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  18178. }
  18179. setup( builder ) {
  18180. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18181. super.setup( builder );
  18182. }
  18183. copy( source ) {
  18184. this.clearcoatNode = source.clearcoatNode;
  18185. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18186. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18187. this.sheenNode = source.sheenNode;
  18188. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18189. this.iridescenceNode = source.iridescenceNode;
  18190. this.iridescenceIORNode = source.iridescenceIORNode;
  18191. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18192. this.specularIntensityNode = source.specularIntensityNode;
  18193. this.specularColorNode = source.specularColorNode;
  18194. this.transmissionNode = source.transmissionNode;
  18195. this.thicknessNode = source.thicknessNode;
  18196. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18197. this.attenuationColorNode = source.attenuationColorNode;
  18198. this.dispersionNode = source.dispersionNode;
  18199. this.anisotropyNode = source.anisotropyNode;
  18200. return super.copy( source );
  18201. }
  18202. }
  18203. /**
  18204. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18205. *
  18206. * @augments PhysicalLightingModel
  18207. */
  18208. class SSSLightingModel extends PhysicalLightingModel {
  18209. /**
  18210. * Constructs a new physical lighting model.
  18211. *
  18212. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18213. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18214. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18215. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18216. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18217. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18218. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18219. */
  18220. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18221. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18222. /**
  18223. * Whether the lighting model should use SSS or not.
  18224. *
  18225. * @type {boolean}
  18226. * @default false
  18227. */
  18228. this.useSSS = sss;
  18229. }
  18230. /**
  18231. * Extends the default implementation with a SSS term.
  18232. *
  18233. * 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/}
  18234. *
  18235. * @param {Object} input - The input data.
  18236. * @param {NodeBuilder} builder - The current node builder.
  18237. */
  18238. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18239. if ( this.useSSS === true ) {
  18240. const material = builder.material;
  18241. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18242. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18243. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18244. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18245. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18246. }
  18247. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18248. }
  18249. }
  18250. /**
  18251. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18252. * that implements a Subsurface scattering (SSS) term.
  18253. *
  18254. * @augments MeshPhysicalNodeMaterial
  18255. */
  18256. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18257. static get type() {
  18258. return 'MeshSSSNodeMaterial';
  18259. }
  18260. /**
  18261. * Constructs a new mesh SSS node material.
  18262. *
  18263. * @param {Object} [parameters] - The configuration parameter.
  18264. */
  18265. constructor( parameters ) {
  18266. super( parameters );
  18267. /**
  18268. * Represents the thickness color.
  18269. *
  18270. * @type {?Node<vec3>}
  18271. * @default null
  18272. */
  18273. this.thicknessColorNode = null;
  18274. /**
  18275. * Represents the distortion factor.
  18276. *
  18277. * @type {?Node<float>}
  18278. */
  18279. this.thicknessDistortionNode = float( 0.1 );
  18280. /**
  18281. * Represents the thickness ambient factor.
  18282. *
  18283. * @type {?Node<float>}
  18284. */
  18285. this.thicknessAmbientNode = float( 0.0 );
  18286. /**
  18287. * Represents the thickness attenuation.
  18288. *
  18289. * @type {?Node<float>}
  18290. */
  18291. this.thicknessAttenuationNode = float( .1 );
  18292. /**
  18293. * Represents the thickness power.
  18294. *
  18295. * @type {?Node<float>}
  18296. */
  18297. this.thicknessPowerNode = float( 2.0 );
  18298. /**
  18299. * Represents the thickness scale.
  18300. *
  18301. * @type {?Node<float>}
  18302. */
  18303. this.thicknessScaleNode = float( 10.0 );
  18304. }
  18305. /**
  18306. * Whether the lighting model should use SSS or not.
  18307. *
  18308. * @type {boolean}
  18309. * @default true
  18310. */
  18311. get useSSS() {
  18312. return this.thicknessColorNode !== null;
  18313. }
  18314. /**
  18315. * Setups the lighting model.
  18316. *
  18317. * @return {SSSLightingModel} The lighting model.
  18318. */
  18319. setupLightingModel( /*builder*/ ) {
  18320. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18321. }
  18322. copy( source ) {
  18323. this.thicknessColorNode = source.thicknessColorNode;
  18324. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18325. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18326. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18327. this.thicknessPowerNode = source.thicknessPowerNode;
  18328. this.thicknessScaleNode = source.thicknessScaleNode;
  18329. return super.copy( source );
  18330. }
  18331. }
  18332. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18333. // dotNL will be from -1.0 to 1.0
  18334. const dotNL = normal.dot( lightDirection );
  18335. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18336. if ( builder.material.gradientMap ) {
  18337. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18338. return vec3( gradientMap.r );
  18339. } else {
  18340. const fw = coord.fwidth().mul( 0.5 );
  18341. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18342. }
  18343. } );
  18344. /**
  18345. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18346. *
  18347. * @augments LightingModel
  18348. */
  18349. class ToonLightingModel extends LightingModel {
  18350. /**
  18351. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18352. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18353. *
  18354. * @param {Object} lightData - The light data.
  18355. * @param {NodeBuilder} builder - The current node builder.
  18356. */
  18357. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18358. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18359. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18360. }
  18361. /**
  18362. * Implements the indirect lighting.
  18363. *
  18364. * @param {NodeBuilder} builder - The current node builder.
  18365. */
  18366. indirect( builder ) {
  18367. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18368. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18369. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18370. }
  18371. }
  18372. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18373. /**
  18374. * Node material version of {@link MeshToonMaterial}.
  18375. *
  18376. * @augments NodeMaterial
  18377. */
  18378. class MeshToonNodeMaterial extends NodeMaterial {
  18379. static get type() {
  18380. return 'MeshToonNodeMaterial';
  18381. }
  18382. /**
  18383. * Constructs a new mesh toon node material.
  18384. *
  18385. * @param {Object} [parameters] - The configuration parameter.
  18386. */
  18387. constructor( parameters ) {
  18388. super();
  18389. /**
  18390. * This flag can be used for type testing.
  18391. *
  18392. * @type {boolean}
  18393. * @readonly
  18394. * @default true
  18395. */
  18396. this.isMeshToonNodeMaterial = true;
  18397. /**
  18398. * Set to `true` because toon materials react on lights.
  18399. *
  18400. * @type {boolean}
  18401. * @default true
  18402. */
  18403. this.lights = true;
  18404. this.setDefaultValues( _defaultValues$4 );
  18405. this.setValues( parameters );
  18406. }
  18407. /**
  18408. * Setups the lighting model.
  18409. *
  18410. * @return {ToonLightingModel} The lighting model.
  18411. */
  18412. setupLightingModel( /*builder*/ ) {
  18413. return new ToonLightingModel();
  18414. }
  18415. }
  18416. /**
  18417. * TSL function for creating a matcap uv node.
  18418. *
  18419. * Can be used to compute texture coordinates for projecting a
  18420. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18421. *
  18422. * @tsl
  18423. * @function
  18424. * @returns {Node<vec2>} The matcap UV coordinates.
  18425. */
  18426. const matcapUV = /*@__PURE__*/ Fn( () => {
  18427. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18428. const y = positionViewDirection.cross( x );
  18429. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18430. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18431. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18432. /**
  18433. * Node material version of {@link MeshMatcapMaterial}.
  18434. *
  18435. * @augments NodeMaterial
  18436. */
  18437. class MeshMatcapNodeMaterial extends NodeMaterial {
  18438. static get type() {
  18439. return 'MeshMatcapNodeMaterial';
  18440. }
  18441. /**
  18442. * Constructs a new mesh normal node material.
  18443. *
  18444. * @param {Object} [parameters] - The configuration parameter.
  18445. */
  18446. constructor( parameters ) {
  18447. super();
  18448. /**
  18449. * This flag can be used for type testing.
  18450. *
  18451. * @type {boolean}
  18452. * @readonly
  18453. * @default true
  18454. */
  18455. this.isMeshMatcapNodeMaterial = true;
  18456. this.setDefaultValues( _defaultValues$3 );
  18457. this.setValues( parameters );
  18458. }
  18459. /**
  18460. * Setups the matcap specific node variables.
  18461. *
  18462. * @param {NodeBuilder} builder - The current node builder.
  18463. */
  18464. setupVariants( builder ) {
  18465. const uv = matcapUV;
  18466. let matcapColor;
  18467. if ( builder.material.matcap ) {
  18468. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18469. } else {
  18470. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18471. }
  18472. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18473. }
  18474. }
  18475. /**
  18476. * Applies a rotation to the given position node.
  18477. *
  18478. * @augments TempNode
  18479. */
  18480. class RotateNode extends TempNode {
  18481. static get type() {
  18482. return 'RotateNode';
  18483. }
  18484. /**
  18485. * Constructs a new rotate node.
  18486. *
  18487. * @param {Node} positionNode - The position node.
  18488. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18489. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18490. */
  18491. constructor( positionNode, rotationNode ) {
  18492. super();
  18493. /**
  18494. * The position node.
  18495. *
  18496. * @type {Node}
  18497. */
  18498. this.positionNode = positionNode;
  18499. /**
  18500. * Represents the rotation that is applied to the position node.
  18501. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18502. *
  18503. * @type {Node}
  18504. */
  18505. this.rotationNode = rotationNode;
  18506. }
  18507. /**
  18508. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18509. *
  18510. * @param {NodeBuilder} builder - The current node builder.
  18511. * @return {string} The node's type.
  18512. */
  18513. getNodeType( builder ) {
  18514. return this.positionNode.getNodeType( builder );
  18515. }
  18516. setup( builder ) {
  18517. const { rotationNode, positionNode } = this;
  18518. const nodeType = this.getNodeType( builder );
  18519. if ( nodeType === 'vec2' ) {
  18520. const cosAngle = rotationNode.cos();
  18521. const sinAngle = rotationNode.sin();
  18522. const rotationMatrix = mat2(
  18523. cosAngle, sinAngle,
  18524. sinAngle.negate(), cosAngle
  18525. );
  18526. return rotationMatrix.mul( positionNode );
  18527. } else {
  18528. const rotation = rotationNode;
  18529. 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 ) );
  18530. 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 ) );
  18531. 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 ) );
  18532. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  18533. }
  18534. }
  18535. }
  18536. /**
  18537. * TSL function for creating a rotate node.
  18538. *
  18539. * @tsl
  18540. * @function
  18541. * @param {Node} positionNode - The position node.
  18542. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18543. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18544. * @returns {RotateNode}
  18545. */
  18546. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  18547. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  18548. /**
  18549. * Node material version of {@link SpriteMaterial}.
  18550. *
  18551. * @augments NodeMaterial
  18552. */
  18553. class SpriteNodeMaterial extends NodeMaterial {
  18554. static get type() {
  18555. return 'SpriteNodeMaterial';
  18556. }
  18557. /**
  18558. * Constructs a new sprite node material.
  18559. *
  18560. * @param {Object} [parameters] - The configuration parameter.
  18561. */
  18562. constructor( parameters ) {
  18563. super();
  18564. /**
  18565. * This flag can be used for type testing.
  18566. *
  18567. * @type {boolean}
  18568. * @readonly
  18569. * @default true
  18570. */
  18571. this.isSpriteNodeMaterial = true;
  18572. this._useSizeAttenuation = true;
  18573. /**
  18574. * This property makes it possible to define the position of the sprite with a
  18575. * node. That can be useful when the material is used with instanced rendering
  18576. * and node data are defined with an instanced attribute node:
  18577. * ```js
  18578. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  18579. * material.positionNode = instancedBufferAttribute( positionAttribute );
  18580. * ```
  18581. * Another possibility is to compute the instanced data with a compute shader:
  18582. * ```js
  18583. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  18584. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18585. * ```
  18586. *
  18587. * @type {?Node<vec2>}
  18588. * @default null
  18589. */
  18590. this.positionNode = null;
  18591. /**
  18592. * The rotation of sprite materials is by default inferred from the `rotation`,
  18593. * property. This node property allows to overwrite the default and define
  18594. * the rotation with a node instead.
  18595. *
  18596. * If you don't want to overwrite the rotation but modify the existing
  18597. * value instead, use {@link materialRotation}.
  18598. *
  18599. * @type {?Node<float>}
  18600. * @default null
  18601. */
  18602. this.rotationNode = null;
  18603. /**
  18604. * This node property provides an additional way to scale sprites next to
  18605. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  18606. * is multiplied with the scale value of this node in the vertex shader.
  18607. *
  18608. * @type {?Node<vec2>}
  18609. * @default null
  18610. */
  18611. this.scaleNode = null;
  18612. /**
  18613. * In Sprites, the transparent property is enabled by default.
  18614. *
  18615. * @type {boolean}
  18616. * @default true
  18617. */
  18618. this.transparent = true;
  18619. this.setDefaultValues( _defaultValues$2 );
  18620. this.setValues( parameters );
  18621. }
  18622. /**
  18623. * Setups the position node in view space. This method implements
  18624. * the sprite specific vertex shader.
  18625. *
  18626. * @param {NodeBuilder} builder - The current node builder.
  18627. * @return {Node<vec3>} The position in view space.
  18628. */
  18629. setupPositionView( builder ) {
  18630. const { object, camera } = builder;
  18631. const sizeAttenuation = this.sizeAttenuation;
  18632. const { positionNode, rotationNode, scaleNode } = this;
  18633. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  18634. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  18635. if ( scaleNode !== null ) {
  18636. scale = scale.mul( vec2( scaleNode ) );
  18637. }
  18638. if ( sizeAttenuation === false ) {
  18639. if ( camera.isPerspectiveCamera ) {
  18640. scale = scale.mul( mvPosition.z.negate() );
  18641. } else {
  18642. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  18643. scale = scale.mul( orthoScale.mul( 2 ) );
  18644. }
  18645. }
  18646. let alignedPosition = positionGeometry.xy;
  18647. if ( object.center && object.center.isVector2 === true ) {
  18648. const center = reference$1( 'center', 'vec2', object );
  18649. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  18650. }
  18651. alignedPosition = alignedPosition.mul( scale );
  18652. const rotation = float( rotationNode || materialRotation );
  18653. const rotatedPosition = rotate( alignedPosition, rotation );
  18654. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  18655. }
  18656. copy( source ) {
  18657. this.positionNode = source.positionNode;
  18658. this.rotationNode = source.rotationNode;
  18659. this.scaleNode = source.scaleNode;
  18660. return super.copy( source );
  18661. }
  18662. /**
  18663. * Whether to use size attenuation or not.
  18664. *
  18665. * @type {boolean}
  18666. * @default true
  18667. */
  18668. get sizeAttenuation() {
  18669. return this._useSizeAttenuation;
  18670. }
  18671. set sizeAttenuation( value ) {
  18672. if ( this._useSizeAttenuation !== value ) {
  18673. this._useSizeAttenuation = value;
  18674. this.needsUpdate = true;
  18675. }
  18676. }
  18677. }
  18678. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  18679. /**
  18680. * Node material version of {@link PointsMaterial}.
  18681. *
  18682. * @augments SpriteNodeMaterial
  18683. */
  18684. class PointsNodeMaterial extends SpriteNodeMaterial {
  18685. static get type() {
  18686. return 'PointsNodeMaterial';
  18687. }
  18688. /**
  18689. * Constructs a new points node material.
  18690. *
  18691. * @param {Object} [parameters] - The configuration parameter.
  18692. */
  18693. constructor( parameters ) {
  18694. super();
  18695. /**
  18696. * This node property provides an additional way to set the point size.
  18697. *
  18698. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  18699. * this node has no effect when the material is used with {@link Points} and a WebGPU
  18700. * backend. If an application wants to render points with a size larger than 1 pixel,
  18701. * the material should be used with {@link Sprite} and instancing.
  18702. *
  18703. * @type {?Node<vec2>}
  18704. * @default null
  18705. */
  18706. this.sizeNode = null;
  18707. /**
  18708. * This flag can be used for type testing.
  18709. *
  18710. * @type {boolean}
  18711. * @readonly
  18712. * @default true
  18713. */
  18714. this.isPointsNodeMaterial = true;
  18715. this.setDefaultValues( _defaultValues$1 );
  18716. this.setValues( parameters );
  18717. }
  18718. setupPositionView() {
  18719. const { positionNode } = this;
  18720. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  18721. }
  18722. setupVertex( builder ) {
  18723. const { material, camera } = builder;
  18724. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  18725. let mvp = super.setupVertex( builder );
  18726. // skip further processing if the material is not a node material
  18727. if ( material.isNodeMaterial !== true ) {
  18728. return mvp;
  18729. }
  18730. // point size
  18731. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  18732. const dpr = builder.renderer.getPixelRatio();
  18733. pointSize = pointSize.mul( dpr );
  18734. // size attenuation
  18735. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  18736. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  18737. const scale = float( 0.5 ).mul( screenSize.y ).div( dpr );
  18738. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  18739. }
  18740. // scale
  18741. if ( scaleNode && scaleNode.isNode ) {
  18742. pointSize = pointSize.mul( vec2( scaleNode ) );
  18743. }
  18744. // compute offset
  18745. let offset = positionGeometry.xy;
  18746. // apply rotation
  18747. if ( rotationNode && rotationNode.isNode ) {
  18748. const rotation = float( rotationNode );
  18749. offset = rotate( offset, rotation );
  18750. }
  18751. // account for point size
  18752. offset = offset.mul( pointSize );
  18753. // scale by viewport size
  18754. offset = offset.div( viewportSize.div( 2 ) );
  18755. // compensate for the perspective divide
  18756. offset = offset.mul( mvp.w );
  18757. // add offset
  18758. mvp = mvp.add( vec4( offset, 0, 0 ) );
  18759. return mvp;
  18760. }
  18761. /**
  18762. * Whether alpha to coverage should be used or not.
  18763. *
  18764. * @type {boolean}
  18765. * @default true
  18766. */
  18767. get alphaToCoverage() {
  18768. return this._useAlphaToCoverage;
  18769. }
  18770. set alphaToCoverage( value ) {
  18771. if ( this._useAlphaToCoverage !== value ) {
  18772. this._useAlphaToCoverage = value;
  18773. this.needsUpdate = true;
  18774. }
  18775. }
  18776. }
  18777. /**
  18778. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  18779. *
  18780. * @augments LightingModel
  18781. */
  18782. class ShadowMaskModel extends LightingModel {
  18783. /**
  18784. * Constructs a new shadow mask model.
  18785. */
  18786. constructor() {
  18787. super();
  18788. /**
  18789. * The shadow mask node.
  18790. *
  18791. * @type {Node}
  18792. */
  18793. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  18794. }
  18795. /**
  18796. * Only used to save the shadow mask.
  18797. *
  18798. * @param {Object} input - The input data.
  18799. */
  18800. direct( { lightNode } ) {
  18801. if ( lightNode.shadowNode !== null ) {
  18802. this.shadowNode.mulAssign( lightNode.shadowNode );
  18803. }
  18804. }
  18805. /**
  18806. * Uses the shadow mask to produce the final color.
  18807. *
  18808. * @param {NodeBuilder} builder - The current node builder.
  18809. */
  18810. finish( { context } ) {
  18811. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  18812. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  18813. }
  18814. }
  18815. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  18816. /**
  18817. * Node material version of {@link ShadowMaterial}.
  18818. *
  18819. * @augments NodeMaterial
  18820. */
  18821. class ShadowNodeMaterial extends NodeMaterial {
  18822. static get type() {
  18823. return 'ShadowNodeMaterial';
  18824. }
  18825. /**
  18826. * Constructs a new shadow node material.
  18827. *
  18828. * @param {Object} [parameters] - The configuration parameter.
  18829. */
  18830. constructor( parameters ) {
  18831. super();
  18832. /**
  18833. * This flag can be used for type testing.
  18834. *
  18835. * @type {boolean}
  18836. * @readonly
  18837. * @default true
  18838. */
  18839. this.isShadowNodeMaterial = true;
  18840. /**
  18841. * Set to `true` because so it's possible to implement
  18842. * the shadow mask effect.
  18843. *
  18844. * @type {boolean}
  18845. * @default true
  18846. */
  18847. this.lights = true;
  18848. /**
  18849. * Overwritten since shadow materials are transparent
  18850. * by default.
  18851. *
  18852. * @type {boolean}
  18853. * @default true
  18854. */
  18855. this.transparent = true;
  18856. this.setDefaultValues( _defaultValues );
  18857. this.setValues( parameters );
  18858. }
  18859. /**
  18860. * Setups the lighting model.
  18861. *
  18862. * @return {ShadowMaskModel} The lighting model.
  18863. */
  18864. setupLightingModel( /*builder*/ ) {
  18865. return new ShadowMaskModel();
  18866. }
  18867. }
  18868. const scatteringDensity = property( 'vec3' );
  18869. const linearDepthRay = property( 'vec3' );
  18870. const outgoingRayLight = property( 'vec3' );
  18871. /**
  18872. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  18873. * This model calculates the scattering and transmittance of light through a volumetric medium.
  18874. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  18875. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  18876. *
  18877. * @augments LightingModel
  18878. */
  18879. class VolumetricLightingModel extends LightingModel {
  18880. constructor() {
  18881. super();
  18882. }
  18883. start( builder ) {
  18884. const { material, context } = builder;
  18885. const startPos = property( 'vec3' );
  18886. const endPos = property( 'vec3' );
  18887. // This approach dynamically changes the direction of the ray,
  18888. // 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.
  18889. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  18890. startPos.assign( cameraPosition );
  18891. endPos.assign( positionWorld );
  18892. } ).Else( () => {
  18893. startPos.assign( positionWorld );
  18894. endPos.assign( cameraPosition );
  18895. } );
  18896. //
  18897. const viewVector = endPos.sub( startPos );
  18898. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  18899. const stepSize = viewVector.length().div( steps ).toVar();
  18900. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  18901. const distTravelled = float( 0.0 ).toVar();
  18902. const transmittance = vec3( 1 ).toVar();
  18903. if ( material.offsetNode ) {
  18904. // reduce banding
  18905. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  18906. }
  18907. Loop( steps, () => {
  18908. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  18909. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  18910. if ( material.depthNode !== null ) {
  18911. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  18912. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  18913. }
  18914. context.positionWorld = positionRay;
  18915. context.shadowPositionWorld = positionRay;
  18916. context.positionView = positionViewRay;
  18917. scatteringDensity.assign( 0 );
  18918. let scatteringNode;
  18919. if ( material.scatteringNode ) {
  18920. scatteringNode = material.scatteringNode( {
  18921. positionRay
  18922. } );
  18923. }
  18924. super.start( builder );
  18925. if ( scatteringNode ) {
  18926. scatteringDensity.mulAssign( scatteringNode );
  18927. }
  18928. // beer's law
  18929. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  18930. transmittance.mulAssign( falloff );
  18931. // move along the ray
  18932. distTravelled.addAssign( stepSize );
  18933. } );
  18934. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  18935. }
  18936. scatteringLight( lightColor, builder ) {
  18937. const sceneDepthNode = builder.context.sceneDepthNode;
  18938. if ( sceneDepthNode ) {
  18939. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  18940. scatteringDensity.addAssign( lightColor );
  18941. } );
  18942. } else {
  18943. scatteringDensity.addAssign( lightColor );
  18944. }
  18945. }
  18946. direct( { lightNode, lightColor }, builder ) {
  18947. // Ignore lights with infinite distance
  18948. if ( lightNode.light.distance === undefined ) return;
  18949. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  18950. const directLight = lightColor.xyz.toVar();
  18951. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  18952. this.scatteringLight( directLight, builder );
  18953. }
  18954. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  18955. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  18956. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  18957. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  18958. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  18959. const P = builder.context.positionView;
  18960. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  18961. this.scatteringLight( directLight, builder );
  18962. }
  18963. finish( builder ) {
  18964. builder.context.outgoingLight.assign( outgoingRayLight );
  18965. }
  18966. }
  18967. /**
  18968. * Volume node material.
  18969. *
  18970. * @augments NodeMaterial
  18971. */
  18972. class VolumeNodeMaterial extends NodeMaterial {
  18973. static get type() {
  18974. return 'VolumeNodeMaterial';
  18975. }
  18976. /**
  18977. * Constructs a new volume node material.
  18978. *
  18979. * @param {Object} [parameters] - The configuration parameter.
  18980. */
  18981. constructor( parameters ) {
  18982. super();
  18983. /**
  18984. * This flag can be used for type testing.
  18985. *
  18986. * @type {boolean}
  18987. * @readonly
  18988. * @default true
  18989. */
  18990. this.isVolumeNodeMaterial = true;
  18991. /**
  18992. * Number of steps used for raymarching.
  18993. *
  18994. * @type {number}
  18995. * @default 25
  18996. */
  18997. this.steps = 25;
  18998. /**
  18999. * Offsets the distance a ray has been traveled through a volume.
  19000. * Can be used to implement dithering to reduce banding.
  19001. *
  19002. * @type {Node<float>}
  19003. * @default null
  19004. */
  19005. this.offsetNode = null;
  19006. /**
  19007. * Node used for scattering calculations.
  19008. *
  19009. * @type {Function|FunctionNode<vec4>}
  19010. * @default null
  19011. */
  19012. this.scatteringNode = null;
  19013. this.lights = true;
  19014. this.transparent = true;
  19015. this.side = BackSide;
  19016. this.depthTest = false;
  19017. this.depthWrite = false;
  19018. this.setValues( parameters );
  19019. }
  19020. setupLightingModel() {
  19021. return new VolumetricLightingModel();
  19022. }
  19023. }
  19024. /**
  19025. * This module manages the internal animation loop of the renderer.
  19026. *
  19027. * @private
  19028. */
  19029. class Animation {
  19030. /**
  19031. * Constructs a new animation loop management component.
  19032. *
  19033. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19034. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19035. */
  19036. constructor( nodes, info ) {
  19037. /**
  19038. * Renderer component for managing nodes related logic.
  19039. *
  19040. * @type {Nodes}
  19041. */
  19042. this.nodes = nodes;
  19043. /**
  19044. * Renderer component for managing metrics and monitoring data.
  19045. *
  19046. * @type {Info}
  19047. */
  19048. this.info = info;
  19049. /**
  19050. * A reference to the context from `requestAnimationFrame()` can
  19051. * be called (usually `window`).
  19052. *
  19053. * @type {?(Window|XRSession)}
  19054. */
  19055. this._context = typeof self !== 'undefined' ? self : null;
  19056. /**
  19057. * The user-defined animation loop.
  19058. *
  19059. * @type {?Function}
  19060. * @default null
  19061. */
  19062. this._animationLoop = null;
  19063. /**
  19064. * The requestId which is returned from the `requestAnimationFrame()` call.
  19065. * Can be used to cancel the stop the animation loop.
  19066. *
  19067. * @type {?number}
  19068. * @default null
  19069. */
  19070. this._requestId = null;
  19071. }
  19072. /**
  19073. * Starts the internal animation loop.
  19074. */
  19075. start() {
  19076. const update = ( time, xrFrame ) => {
  19077. this._requestId = this._context.requestAnimationFrame( update );
  19078. if ( this.info.autoReset === true ) this.info.reset();
  19079. this.nodes.nodeFrame.update();
  19080. this.info.frame = this.nodes.nodeFrame.frameId;
  19081. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19082. };
  19083. update();
  19084. }
  19085. /**
  19086. * Stops the internal animation loop.
  19087. */
  19088. stop() {
  19089. this._context.cancelAnimationFrame( this._requestId );
  19090. this._requestId = null;
  19091. }
  19092. /**
  19093. * Returns the user-level animation loop.
  19094. *
  19095. * @return {?Function} The animation loop.
  19096. */
  19097. getAnimationLoop() {
  19098. return this._animationLoop;
  19099. }
  19100. /**
  19101. * Defines the user-level animation loop.
  19102. *
  19103. * @param {?Function} callback - The animation loop.
  19104. */
  19105. setAnimationLoop( callback ) {
  19106. this._animationLoop = callback;
  19107. }
  19108. /**
  19109. * Returns the animation context.
  19110. *
  19111. * @return {Window|XRSession} The animation context.
  19112. */
  19113. getContext() {
  19114. return this._context;
  19115. }
  19116. /**
  19117. * Defines the context in which `requestAnimationFrame()` is executed.
  19118. *
  19119. * @param {Window|XRSession} context - The context to set.
  19120. */
  19121. setContext( context ) {
  19122. this._context = context;
  19123. }
  19124. /**
  19125. * Frees all internal resources and stops the animation loop.
  19126. */
  19127. dispose() {
  19128. this.stop();
  19129. }
  19130. }
  19131. /**
  19132. * Data structure for the renderer. It allows defining values
  19133. * with chained, hierarchical keys. Keys are meant to be
  19134. * objects since the module internally works with Weak Maps
  19135. * for performance reasons.
  19136. *
  19137. * @private
  19138. */
  19139. class ChainMap {
  19140. /**
  19141. * Constructs a new Chain Map.
  19142. */
  19143. constructor() {
  19144. /**
  19145. * The root Weak Map.
  19146. *
  19147. * @type {WeakMap}
  19148. */
  19149. this.weakMap = new WeakMap();
  19150. }
  19151. /**
  19152. * Returns the value for the given array of keys.
  19153. *
  19154. * @param {Array<Object>} keys - List of keys.
  19155. * @return {any} The value. Returns `undefined` if no value was found.
  19156. */
  19157. get( keys ) {
  19158. let map = this.weakMap;
  19159. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19160. map = map.get( keys[ i ] );
  19161. if ( map === undefined ) return undefined;
  19162. }
  19163. return map.get( keys[ keys.length - 1 ] );
  19164. }
  19165. /**
  19166. * Sets the value for the given keys.
  19167. *
  19168. * @param {Array<Object>} keys - List of keys.
  19169. * @param {any} value - The value to set.
  19170. * @return {ChainMap} A reference to this Chain Map.
  19171. */
  19172. set( keys, value ) {
  19173. let map = this.weakMap;
  19174. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19175. const key = keys[ i ];
  19176. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  19177. map = map.get( key );
  19178. }
  19179. map.set( keys[ keys.length - 1 ], value );
  19180. return this;
  19181. }
  19182. /**
  19183. * Deletes a value for the given keys.
  19184. *
  19185. * @param {Array<Object>} keys - The keys.
  19186. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19187. */
  19188. delete( keys ) {
  19189. let map = this.weakMap;
  19190. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19191. map = map.get( keys[ i ] );
  19192. if ( map === undefined ) return false;
  19193. }
  19194. return map.delete( keys[ keys.length - 1 ] );
  19195. }
  19196. }
  19197. let _id$9 = 0;
  19198. function getKeys( obj ) {
  19199. const keys = Object.keys( obj );
  19200. let proto = Object.getPrototypeOf( obj );
  19201. while ( proto ) {
  19202. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19203. for ( const key in descriptors ) {
  19204. if ( descriptors[ key ] !== undefined ) {
  19205. const descriptor = descriptors[ key ];
  19206. if ( descriptor && typeof descriptor.get === 'function' ) {
  19207. keys.push( key );
  19208. }
  19209. }
  19210. }
  19211. proto = Object.getPrototypeOf( proto );
  19212. }
  19213. return keys;
  19214. }
  19215. /**
  19216. * A render object is the renderer's representation of single entity that gets drawn
  19217. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19218. * scene since render objects also depend from the used material, the current render context
  19219. * and the current scene's lighting.
  19220. *
  19221. * In general, the basic process of the renderer is:
  19222. *
  19223. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19224. * - Process the render lists by calling one or more render commands for each render item.
  19225. * - For each render command, request a render object and perform the draw.
  19226. *
  19227. * The module provides an interface to get data required for the draw command like the actual
  19228. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19229. * creating render objects should only be done when necessary.
  19230. *
  19231. * @private
  19232. */
  19233. class RenderObject {
  19234. /**
  19235. * Constructs a new render object.
  19236. *
  19237. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19238. * @param {Geometries} geometries - Renderer component for managing geometries.
  19239. * @param {Renderer} renderer - The renderer.
  19240. * @param {Object3D} object - The 3D object.
  19241. * @param {Material} material - The 3D object's material.
  19242. * @param {Scene} scene - The scene the 3D object belongs to.
  19243. * @param {Camera} camera - The camera the object should be rendered with.
  19244. * @param {LightsNode} lightsNode - The lights node.
  19245. * @param {RenderContext} renderContext - The render context.
  19246. * @param {ClippingContext} clippingContext - The clipping context.
  19247. */
  19248. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19249. this.id = _id$9 ++;
  19250. /**
  19251. * Renderer component for managing nodes related logic.
  19252. *
  19253. * @type {Nodes}
  19254. * @private
  19255. */
  19256. this._nodes = nodes;
  19257. /**
  19258. * Renderer component for managing geometries.
  19259. *
  19260. * @type {Geometries}
  19261. * @private
  19262. */
  19263. this._geometries = geometries;
  19264. /**
  19265. * The renderer.
  19266. *
  19267. * @type {Renderer}
  19268. */
  19269. this.renderer = renderer;
  19270. /**
  19271. * The 3D object.
  19272. *
  19273. * @type {Object3D}
  19274. */
  19275. this.object = object;
  19276. /**
  19277. * The 3D object's material.
  19278. *
  19279. * @type {Material}
  19280. */
  19281. this.material = material;
  19282. /**
  19283. * The scene the 3D object belongs to.
  19284. *
  19285. * @type {Scene}
  19286. */
  19287. this.scene = scene;
  19288. /**
  19289. * The camera the 3D object should be rendered with.
  19290. *
  19291. * @type {Camera}
  19292. */
  19293. this.camera = camera;
  19294. /**
  19295. * The lights node.
  19296. *
  19297. * @type {LightsNode}
  19298. */
  19299. this.lightsNode = lightsNode;
  19300. /**
  19301. * The render context.
  19302. *
  19303. * @type {RenderContext}
  19304. */
  19305. this.context = renderContext;
  19306. /**
  19307. * The 3D object's geometry.
  19308. *
  19309. * @type {BufferGeometry}
  19310. */
  19311. this.geometry = object.geometry;
  19312. /**
  19313. * The render object's version.
  19314. *
  19315. * @type {number}
  19316. */
  19317. this.version = material.version;
  19318. /**
  19319. * The draw range of the geometry.
  19320. *
  19321. * @type {?Object}
  19322. * @default null
  19323. */
  19324. this.drawRange = null;
  19325. /**
  19326. * An array holding the buffer attributes
  19327. * of the render object. This entails attribute
  19328. * definitions on geometry and node level.
  19329. *
  19330. * @type {?Array<BufferAttribute>}
  19331. * @default null
  19332. */
  19333. this.attributes = null;
  19334. /**
  19335. * An object holding the version of the
  19336. * attributes. The keys are the attribute names
  19337. * and the values are the attribute versions.
  19338. *
  19339. * @type {?Object<string, number>}
  19340. * @default null
  19341. */
  19342. this.attributesId = null;
  19343. /**
  19344. * A reference to a render pipeline the render
  19345. * object is processed with.
  19346. *
  19347. * @type {RenderPipeline}
  19348. * @default null
  19349. */
  19350. this.pipeline = null;
  19351. /**
  19352. * Only relevant for objects using
  19353. * multiple materials. This represents a group entry
  19354. * from the respective `BufferGeometry`.
  19355. *
  19356. * @type {?{start: number, count: number}}
  19357. * @default null
  19358. */
  19359. this.group = null;
  19360. /**
  19361. * An array holding the vertex buffers which can
  19362. * be buffer attributes but also interleaved buffers.
  19363. *
  19364. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19365. * @default null
  19366. */
  19367. this.vertexBuffers = null;
  19368. /**
  19369. * The parameters for the draw command.
  19370. *
  19371. * @type {?Object}
  19372. * @default null
  19373. */
  19374. this.drawParams = null;
  19375. /**
  19376. * If this render object is used inside a render bundle,
  19377. * this property points to the respective bundle group.
  19378. *
  19379. * @type {?BundleGroup}
  19380. * @default null
  19381. */
  19382. this.bundle = null;
  19383. /**
  19384. * The clipping context.
  19385. *
  19386. * @type {ClippingContext}
  19387. */
  19388. this.clippingContext = clippingContext;
  19389. /**
  19390. * The clipping context's cache key.
  19391. *
  19392. * @type {string}
  19393. */
  19394. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19395. /**
  19396. * The initial node cache key.
  19397. *
  19398. * @type {number}
  19399. */
  19400. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19401. /**
  19402. * The initial cache key.
  19403. *
  19404. * @type {number}
  19405. */
  19406. this.initialCacheKey = this.getCacheKey();
  19407. /**
  19408. * The node builder state.
  19409. *
  19410. * @type {?NodeBuilderState}
  19411. * @private
  19412. * @default null
  19413. */
  19414. this._nodeBuilderState = null;
  19415. /**
  19416. * An array of bindings.
  19417. *
  19418. * @type {?Array<BindGroup>}
  19419. * @private
  19420. * @default null
  19421. */
  19422. this._bindings = null;
  19423. /**
  19424. * Reference to the node material observer.
  19425. *
  19426. * @type {?NodeMaterialObserver}
  19427. * @private
  19428. * @default null
  19429. */
  19430. this._monitor = null;
  19431. /**
  19432. * An event listener which is defined by `RenderObjects`. It performs
  19433. * clean up tasks when `dispose()` on this render object.
  19434. *
  19435. * @method
  19436. */
  19437. this.onDispose = null;
  19438. /**
  19439. * This flag can be used for type testing.
  19440. *
  19441. * @type {boolean}
  19442. * @readonly
  19443. * @default true
  19444. */
  19445. this.isRenderObject = true;
  19446. /**
  19447. * An event listener which is executed when `dispose()` is called on
  19448. * the material of this render object.
  19449. *
  19450. * @method
  19451. */
  19452. this.onMaterialDispose = () => {
  19453. this.dispose();
  19454. };
  19455. /**
  19456. * An event listener which is executed when `dispose()` is called on
  19457. * the geometry of this render object.
  19458. *
  19459. * @method
  19460. */
  19461. this.onGeometryDispose = () => {
  19462. // clear geometry cache attributes
  19463. this.attributes = null;
  19464. this.attributesId = null;
  19465. };
  19466. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19467. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19468. }
  19469. /**
  19470. * Updates the clipping context.
  19471. *
  19472. * @param {ClippingContext} context - The clipping context to set.
  19473. */
  19474. updateClipping( context ) {
  19475. this.clippingContext = context;
  19476. }
  19477. /**
  19478. * Whether the clipping requires an update or not.
  19479. *
  19480. * @type {boolean}
  19481. * @readonly
  19482. */
  19483. get clippingNeedsUpdate() {
  19484. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19485. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19486. return true;
  19487. }
  19488. /**
  19489. * The number of clipping planes defined in context of hardware clipping.
  19490. *
  19491. * @type {number}
  19492. * @readonly
  19493. */
  19494. get hardwareClippingPlanes() {
  19495. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19496. }
  19497. /**
  19498. * Returns the node builder state of this render object.
  19499. *
  19500. * @return {NodeBuilderState} The node builder state.
  19501. */
  19502. getNodeBuilderState() {
  19503. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  19504. }
  19505. /**
  19506. * Returns the node material observer of this render object.
  19507. *
  19508. * @return {NodeMaterialObserver} The node material observer.
  19509. */
  19510. getMonitor() {
  19511. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  19512. }
  19513. /**
  19514. * Returns an array of bind groups of this render object.
  19515. *
  19516. * @return {Array<BindGroup>} The bindings.
  19517. */
  19518. getBindings() {
  19519. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  19520. }
  19521. /**
  19522. * Returns a binding group by group name of this render object.
  19523. *
  19524. * @param {string} name - The name of the binding group.
  19525. * @return {?BindGroup} The bindings.
  19526. */
  19527. getBindingGroup( name ) {
  19528. for ( const bindingGroup of this.getBindings() ) {
  19529. if ( bindingGroup.name === name ) {
  19530. return bindingGroup;
  19531. }
  19532. }
  19533. }
  19534. /**
  19535. * Returns the index of the render object's geometry.
  19536. *
  19537. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19538. */
  19539. getIndex() {
  19540. return this._geometries.getIndex( this );
  19541. }
  19542. /**
  19543. * Returns the indirect buffer attribute.
  19544. *
  19545. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19546. */
  19547. getIndirect() {
  19548. return this._geometries.getIndirect( this );
  19549. }
  19550. /**
  19551. * Returns an array that acts as a key for identifying the render object in a chain map.
  19552. *
  19553. * @return {Array<Object>} An array with object references.
  19554. */
  19555. getChainArray() {
  19556. return [ this.object, this.material, this.context, this.lightsNode ];
  19557. }
  19558. /**
  19559. * This method is used when the geometry of a 3D object has been exchanged and the
  19560. * respective render object now requires an update.
  19561. *
  19562. * @param {BufferGeometry} geometry - The geometry to set.
  19563. */
  19564. setGeometry( geometry ) {
  19565. this.geometry = geometry;
  19566. this.attributes = null;
  19567. this.attributesId = null;
  19568. }
  19569. /**
  19570. * Returns the buffer attributes of the render object. The returned array holds
  19571. * attribute definitions on geometry and node level.
  19572. *
  19573. * @return {Array<BufferAttribute>} An array with buffer attributes.
  19574. */
  19575. getAttributes() {
  19576. if ( this.attributes !== null ) return this.attributes;
  19577. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  19578. const geometry = this.geometry;
  19579. const attributes = [];
  19580. const vertexBuffers = new Set();
  19581. const attributesId = {};
  19582. for ( const nodeAttribute of nodeAttributes ) {
  19583. let attribute;
  19584. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  19585. // node attribute
  19586. attribute = nodeAttribute.node.attribute;
  19587. } else {
  19588. // geometry attribute
  19589. attribute = geometry.getAttribute( nodeAttribute.name );
  19590. attributesId[ nodeAttribute.name ] = attribute.version;
  19591. }
  19592. if ( attribute === undefined ) continue;
  19593. attributes.push( attribute );
  19594. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  19595. vertexBuffers.add( bufferAttribute );
  19596. }
  19597. this.attributes = attributes;
  19598. this.attributesId = attributesId;
  19599. this.vertexBuffers = Array.from( vertexBuffers.values() );
  19600. return attributes;
  19601. }
  19602. /**
  19603. * Returns the vertex buffers of the render object.
  19604. *
  19605. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  19606. */
  19607. getVertexBuffers() {
  19608. if ( this.vertexBuffers === null ) this.getAttributes();
  19609. return this.vertexBuffers;
  19610. }
  19611. /**
  19612. * Returns the draw parameters for the render object.
  19613. *
  19614. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  19615. */
  19616. getDrawParameters() {
  19617. const { object, material, geometry, group, drawRange } = this;
  19618. const drawParams = this.drawParams || ( this.drawParams = {
  19619. vertexCount: 0,
  19620. firstVertex: 0,
  19621. instanceCount: 0,
  19622. firstInstance: 0
  19623. } );
  19624. const index = this.getIndex();
  19625. const hasIndex = ( index !== null );
  19626. let instanceCount = 1;
  19627. if ( geometry.isInstancedBufferGeometry === true ) {
  19628. instanceCount = geometry.instanceCount;
  19629. } else if ( object.count !== undefined ) {
  19630. instanceCount = Math.max( 0, object.count );
  19631. }
  19632. if ( instanceCount === 0 ) return null;
  19633. drawParams.instanceCount = instanceCount;
  19634. if ( object.isBatchedMesh === true ) return drawParams;
  19635. let rangeFactor = 1;
  19636. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  19637. rangeFactor = 2;
  19638. }
  19639. let firstVertex = drawRange.start * rangeFactor;
  19640. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  19641. if ( group !== null ) {
  19642. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  19643. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  19644. }
  19645. const position = geometry.attributes.position;
  19646. let itemCount = Infinity;
  19647. if ( hasIndex ) {
  19648. itemCount = index.count;
  19649. } else if ( position !== undefined && position !== null ) {
  19650. itemCount = position.count;
  19651. }
  19652. firstVertex = Math.max( firstVertex, 0 );
  19653. lastVertex = Math.min( lastVertex, itemCount );
  19654. const count = lastVertex - firstVertex;
  19655. if ( count < 0 || count === Infinity ) return null;
  19656. drawParams.vertexCount = count;
  19657. drawParams.firstVertex = firstVertex;
  19658. return drawParams;
  19659. }
  19660. /**
  19661. * Returns the render object's geometry cache key.
  19662. *
  19663. * The geometry cache key is part of the material cache key.
  19664. *
  19665. * @return {string} The geometry cache key.
  19666. */
  19667. getGeometryCacheKey() {
  19668. const { geometry } = this;
  19669. let cacheKey = '';
  19670. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  19671. const attribute = geometry.attributes[ name ];
  19672. cacheKey += name + ',';
  19673. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  19674. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  19675. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  19676. if ( attribute.normalized ) cacheKey += 'n,';
  19677. }
  19678. // structural equality isn't sufficient for morph targets since the
  19679. // data are maintained in textures. only if the targets are all equal
  19680. // the texture and thus the instance of `MorphNode` can be shared.
  19681. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  19682. const targets = geometry.morphAttributes[ name ];
  19683. cacheKey += 'morph-' + name + ',';
  19684. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  19685. const attribute = targets[ i ];
  19686. cacheKey += attribute.id + ',';
  19687. }
  19688. }
  19689. if ( geometry.index ) {
  19690. cacheKey += 'index,';
  19691. }
  19692. return cacheKey;
  19693. }
  19694. /**
  19695. * Returns the render object's material cache key.
  19696. *
  19697. * The material cache key is part of the render object cache key.
  19698. *
  19699. * @return {number} The material cache key.
  19700. */
  19701. getMaterialCacheKey() {
  19702. const { object, material, renderer } = this;
  19703. let cacheKey = material.customProgramCacheKey();
  19704. for ( const property of getKeys( material ) ) {
  19705. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  19706. const value = material[ property ];
  19707. let valueKey;
  19708. if ( value !== null ) {
  19709. // some material values require a formatting
  19710. const type = typeof value;
  19711. if ( type === 'number' ) {
  19712. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  19713. } else if ( type === 'object' ) {
  19714. valueKey = '{';
  19715. if ( value.isTexture ) {
  19716. valueKey += value.mapping;
  19717. // WebGPU must honor the sampler data because they are part of the bindings
  19718. if ( renderer.backend.isWebGPUBackend === true ) {
  19719. valueKey += value.magFilter;
  19720. valueKey += value.minFilter;
  19721. valueKey += value.wrapS;
  19722. valueKey += value.wrapT;
  19723. valueKey += value.wrapR;
  19724. }
  19725. }
  19726. valueKey += '}';
  19727. } else {
  19728. valueKey = String( value );
  19729. }
  19730. } else {
  19731. valueKey = String( value );
  19732. }
  19733. cacheKey += /*property + ':' +*/ valueKey + ',';
  19734. }
  19735. cacheKey += this.clippingContextCacheKey + ',';
  19736. if ( object.geometry ) {
  19737. cacheKey += this.getGeometryCacheKey();
  19738. }
  19739. if ( object.skeleton ) {
  19740. cacheKey += object.skeleton.bones.length + ',';
  19741. }
  19742. if ( object.isBatchedMesh ) {
  19743. cacheKey += object._matricesTexture.uuid + ',';
  19744. if ( object._colorsTexture !== null ) {
  19745. cacheKey += object._colorsTexture.uuid + ',';
  19746. }
  19747. }
  19748. if ( object.count > 1 ) {
  19749. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  19750. cacheKey += object.uuid + ',';
  19751. }
  19752. cacheKey += object.receiveShadow + ',';
  19753. return hashString( cacheKey );
  19754. }
  19755. /**
  19756. * Whether the geometry requires an update or not.
  19757. *
  19758. * @type {boolean}
  19759. * @readonly
  19760. */
  19761. get needsGeometryUpdate() {
  19762. if ( this.geometry.id !== this.object.geometry.id ) return true;
  19763. if ( this.attributes !== null ) {
  19764. const attributesId = this.attributesId;
  19765. for ( const name in attributesId ) {
  19766. const attribute = this.geometry.getAttribute( name );
  19767. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  19768. return true;
  19769. }
  19770. }
  19771. }
  19772. return false;
  19773. }
  19774. /**
  19775. * Whether the render object requires an update or not.
  19776. *
  19777. * Note: There are two distinct places where render objects are checked for an update.
  19778. *
  19779. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  19780. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  19781. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  19782. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  19783. * a need for a refresh due to material, geometry or object related value changes.
  19784. *
  19785. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  19786. * that performs the 'needsUpdate' check.
  19787. *
  19788. * @type {boolean}
  19789. * @readonly
  19790. */
  19791. get needsUpdate() {
  19792. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  19793. }
  19794. /**
  19795. * Returns the dynamic cache key which represents a key that is computed per draw command.
  19796. *
  19797. * @return {number} The cache key.
  19798. */
  19799. getDynamicCacheKey() {
  19800. let cacheKey = 0;
  19801. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  19802. // the renderer is inside a shadow pass.
  19803. if ( this.material.isShadowPassMaterial !== true ) {
  19804. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  19805. }
  19806. if ( this.camera.isArrayCamera ) {
  19807. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  19808. }
  19809. if ( this.object.receiveShadow ) {
  19810. cacheKey = hash$1( cacheKey, 1 );
  19811. }
  19812. return cacheKey;
  19813. }
  19814. /**
  19815. * Returns the render object's cache key.
  19816. *
  19817. * @return {number} The cache key.
  19818. */
  19819. getCacheKey() {
  19820. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  19821. }
  19822. /**
  19823. * Frees internal resources.
  19824. */
  19825. dispose() {
  19826. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  19827. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  19828. this.onDispose();
  19829. }
  19830. }
  19831. const _chainKeys$5 = [];
  19832. /**
  19833. * This module manages the render objects of the renderer.
  19834. *
  19835. * @private
  19836. */
  19837. class RenderObjects {
  19838. /**
  19839. * Constructs a new render object management component.
  19840. *
  19841. * @param {Renderer} renderer - The renderer.
  19842. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19843. * @param {Geometries} geometries - Renderer component for managing geometries.
  19844. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  19845. * @param {Bindings} bindings - Renderer component for managing bindings.
  19846. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19847. */
  19848. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  19849. /**
  19850. * The renderer.
  19851. *
  19852. * @type {Renderer}
  19853. */
  19854. this.renderer = renderer;
  19855. /**
  19856. * Renderer component for managing nodes related logic.
  19857. *
  19858. * @type {Nodes}
  19859. */
  19860. this.nodes = nodes;
  19861. /**
  19862. * Renderer component for managing geometries.
  19863. *
  19864. * @type {Geometries}
  19865. */
  19866. this.geometries = geometries;
  19867. /**
  19868. * Renderer component for managing pipelines.
  19869. *
  19870. * @type {Pipelines}
  19871. */
  19872. this.pipelines = pipelines;
  19873. /**
  19874. * Renderer component for managing bindings.
  19875. *
  19876. * @type {Bindings}
  19877. */
  19878. this.bindings = bindings;
  19879. /**
  19880. * Renderer component for managing metrics and monitoring data.
  19881. *
  19882. * @type {Info}
  19883. */
  19884. this.info = info;
  19885. /**
  19886. * A dictionary that manages render contexts in chain maps
  19887. * for each pass ID.
  19888. *
  19889. * @type {Object<string,ChainMap>}
  19890. */
  19891. this.chainMaps = {};
  19892. }
  19893. /**
  19894. * Returns a render object for the given object and state data.
  19895. *
  19896. * @param {Object3D} object - The 3D object.
  19897. * @param {Material} material - The 3D object's material.
  19898. * @param {Scene} scene - The scene the 3D object belongs to.
  19899. * @param {Camera} camera - The camera the 3D object should be rendered with.
  19900. * @param {LightsNode} lightsNode - The lights node.
  19901. * @param {RenderContext} renderContext - The render context.
  19902. * @param {ClippingContext} clippingContext - The clipping context.
  19903. * @param {string} [passId] - An optional ID for identifying the pass.
  19904. * @return {RenderObject} The render object.
  19905. */
  19906. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19907. const chainMap = this.getChainMap( passId );
  19908. // reuse chainArray
  19909. _chainKeys$5[ 0 ] = object;
  19910. _chainKeys$5[ 1 ] = material;
  19911. _chainKeys$5[ 2 ] = renderContext;
  19912. _chainKeys$5[ 3 ] = lightsNode;
  19913. let renderObject = chainMap.get( _chainKeys$5 );
  19914. if ( renderObject === undefined ) {
  19915. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19916. chainMap.set( _chainKeys$5, renderObject );
  19917. } else {
  19918. renderObject.updateClipping( clippingContext );
  19919. if ( renderObject.needsGeometryUpdate ) {
  19920. renderObject.setGeometry( object.geometry );
  19921. }
  19922. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  19923. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  19924. renderObject.dispose();
  19925. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19926. } else {
  19927. renderObject.version = material.version;
  19928. }
  19929. }
  19930. }
  19931. _chainKeys$5.length = 0;
  19932. return renderObject;
  19933. }
  19934. /**
  19935. * Returns a chain map for the given pass ID.
  19936. *
  19937. * @param {string} [passId='default'] - The pass ID.
  19938. * @return {ChainMap} The chain map.
  19939. */
  19940. getChainMap( passId = 'default' ) {
  19941. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  19942. }
  19943. /**
  19944. * Frees internal resources.
  19945. */
  19946. dispose() {
  19947. this.chainMaps = {};
  19948. }
  19949. /**
  19950. * Factory method for creating render objects with the given list of parameters.
  19951. *
  19952. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19953. * @param {Geometries} geometries - Renderer component for managing geometries.
  19954. * @param {Renderer} renderer - The renderer.
  19955. * @param {Object3D} object - The 3D object.
  19956. * @param {Material} material - The object's material.
  19957. * @param {Scene} scene - The scene the 3D object belongs to.
  19958. * @param {Camera} camera - The camera the object should be rendered with.
  19959. * @param {LightsNode} lightsNode - The lights node.
  19960. * @param {RenderContext} renderContext - The render context.
  19961. * @param {ClippingContext} clippingContext - The clipping context.
  19962. * @param {string} [passId] - An optional ID for identifying the pass.
  19963. * @return {RenderObject} The render object.
  19964. */
  19965. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19966. const chainMap = this.getChainMap( passId );
  19967. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  19968. renderObject.onDispose = () => {
  19969. this.pipelines.delete( renderObject );
  19970. this.bindings.delete( renderObject );
  19971. this.nodes.delete( renderObject );
  19972. chainMap.delete( renderObject.getChainArray() );
  19973. };
  19974. return renderObject;
  19975. }
  19976. }
  19977. /**
  19978. * Data structure for the renderer. It is intended to manage
  19979. * data of objects in dictionaries.
  19980. *
  19981. * @private
  19982. */
  19983. class DataMap {
  19984. /**
  19985. * Constructs a new data map.
  19986. */
  19987. constructor() {
  19988. /**
  19989. * `DataMap` internally uses a weak map
  19990. * to manage its data.
  19991. *
  19992. * @type {WeakMap}
  19993. */
  19994. this.data = new WeakMap();
  19995. }
  19996. /**
  19997. * Returns the dictionary for the given object.
  19998. *
  19999. * @param {Object} object - The object.
  20000. * @return {Object} The dictionary.
  20001. */
  20002. get( object ) {
  20003. let map = this.data.get( object );
  20004. if ( map === undefined ) {
  20005. map = {};
  20006. this.data.set( object, map );
  20007. }
  20008. return map;
  20009. }
  20010. /**
  20011. * Deletes the dictionary for the given object.
  20012. *
  20013. * @param {Object} object - The object.
  20014. * @return {?Object} The deleted dictionary.
  20015. */
  20016. delete( object ) {
  20017. let map = null;
  20018. if ( this.data.has( object ) ) {
  20019. map = this.data.get( object );
  20020. this.data.delete( object );
  20021. }
  20022. return map;
  20023. }
  20024. /**
  20025. * Returns `true` if the given object has a dictionary defined.
  20026. *
  20027. * @param {Object} object - The object to test.
  20028. * @return {boolean} Whether a dictionary is defined or not.
  20029. */
  20030. has( object ) {
  20031. return this.data.has( object );
  20032. }
  20033. /**
  20034. * Frees internal resources.
  20035. */
  20036. dispose() {
  20037. this.data = new WeakMap();
  20038. }
  20039. }
  20040. const AttributeType = {
  20041. VERTEX: 1,
  20042. INDEX: 2,
  20043. STORAGE: 3,
  20044. INDIRECT: 4
  20045. };
  20046. // size of a chunk in bytes (STD140 layout)
  20047. const GPU_CHUNK_BYTES = 16;
  20048. // @TODO: Move to src/constants.js
  20049. const BlendColorFactor = 211;
  20050. const OneMinusBlendColorFactor = 212;
  20051. /**
  20052. * This renderer module manages geometry attributes.
  20053. *
  20054. * @private
  20055. * @augments DataMap
  20056. */
  20057. class Attributes extends DataMap {
  20058. /**
  20059. * Constructs a new attribute management component.
  20060. *
  20061. * @param {Backend} backend - The renderer's backend.
  20062. */
  20063. constructor( backend ) {
  20064. super();
  20065. /**
  20066. * The renderer's backend.
  20067. *
  20068. * @type {Backend}
  20069. */
  20070. this.backend = backend;
  20071. }
  20072. /**
  20073. * Deletes the data for the given attribute.
  20074. *
  20075. * @param {BufferAttribute} attribute - The attribute.
  20076. * @return {Object|null} The deleted attribute data.
  20077. */
  20078. delete( attribute ) {
  20079. const attributeData = super.delete( attribute );
  20080. if ( attributeData !== null ) {
  20081. this.backend.destroyAttribute( attribute );
  20082. }
  20083. return attributeData;
  20084. }
  20085. /**
  20086. * Updates the given attribute. This method creates attribute buffers
  20087. * for new attributes and updates data for existing ones.
  20088. *
  20089. * @param {BufferAttribute} attribute - The attribute to update.
  20090. * @param {number} type - The attribute type.
  20091. */
  20092. update( attribute, type ) {
  20093. const data = this.get( attribute );
  20094. if ( data.version === undefined ) {
  20095. if ( type === AttributeType.VERTEX ) {
  20096. this.backend.createAttribute( attribute );
  20097. } else if ( type === AttributeType.INDEX ) {
  20098. this.backend.createIndexAttribute( attribute );
  20099. } else if ( type === AttributeType.STORAGE ) {
  20100. this.backend.createStorageAttribute( attribute );
  20101. } else if ( type === AttributeType.INDIRECT ) {
  20102. this.backend.createIndirectStorageAttribute( attribute );
  20103. }
  20104. data.version = this._getBufferAttribute( attribute ).version;
  20105. } else {
  20106. const bufferAttribute = this._getBufferAttribute( attribute );
  20107. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20108. this.backend.updateAttribute( attribute );
  20109. data.version = bufferAttribute.version;
  20110. }
  20111. }
  20112. }
  20113. /**
  20114. * Utility method for handling interleaved buffer attributes correctly.
  20115. * To process them, their `InterleavedBuffer` is returned.
  20116. *
  20117. * @param {BufferAttribute} attribute - The attribute.
  20118. * @return {BufferAttribute|InterleavedBuffer}
  20119. */
  20120. _getBufferAttribute( attribute ) {
  20121. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20122. return attribute;
  20123. }
  20124. }
  20125. /**
  20126. * Returns the wireframe version for the given geometry.
  20127. *
  20128. * @private
  20129. * @function
  20130. * @param {BufferGeometry} geometry - The geometry.
  20131. * @return {number} The version.
  20132. */
  20133. function getWireframeVersion( geometry ) {
  20134. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  20135. }
  20136. /**
  20137. * Returns a wireframe index attribute for the given geometry.
  20138. *
  20139. * @private
  20140. * @function
  20141. * @param {BufferGeometry} geometry - The geometry.
  20142. * @return {BufferAttribute} The wireframe index attribute.
  20143. */
  20144. function getWireframeIndex( geometry ) {
  20145. const indices = [];
  20146. const geometryIndex = geometry.index;
  20147. const geometryPosition = geometry.attributes.position;
  20148. if ( geometryIndex !== null ) {
  20149. const array = geometryIndex.array;
  20150. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  20151. const a = array[ i + 0 ];
  20152. const b = array[ i + 1 ];
  20153. const c = array[ i + 2 ];
  20154. indices.push( a, b, b, c, c, a );
  20155. }
  20156. } else {
  20157. const array = geometryPosition.array;
  20158. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  20159. const a = i + 0;
  20160. const b = i + 1;
  20161. const c = i + 2;
  20162. indices.push( a, b, b, c, c, a );
  20163. }
  20164. }
  20165. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  20166. attribute.version = getWireframeVersion( geometry );
  20167. return attribute;
  20168. }
  20169. /**
  20170. * This renderer module manages geometries.
  20171. *
  20172. * @private
  20173. * @augments DataMap
  20174. */
  20175. class Geometries extends DataMap {
  20176. /**
  20177. * Constructs a new geometry management component.
  20178. *
  20179. * @param {Attributes} attributes - Renderer component for managing attributes.
  20180. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20181. */
  20182. constructor( attributes, info ) {
  20183. super();
  20184. /**
  20185. * Renderer component for managing attributes.
  20186. *
  20187. * @type {Attributes}
  20188. */
  20189. this.attributes = attributes;
  20190. /**
  20191. * Renderer component for managing metrics and monitoring data.
  20192. *
  20193. * @type {Info}
  20194. */
  20195. this.info = info;
  20196. /**
  20197. * Weak Map for managing attributes for wireframe rendering.
  20198. *
  20199. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20200. */
  20201. this.wireframes = new WeakMap();
  20202. /**
  20203. * This Weak Map is used to make sure buffer attributes are
  20204. * updated only once per render call.
  20205. *
  20206. * @type {WeakMap<BufferAttribute,number>}
  20207. */
  20208. this.attributeCall = new WeakMap();
  20209. }
  20210. /**
  20211. * Returns `true` if the given render object has an initialized geometry.
  20212. *
  20213. * @param {RenderObject} renderObject - The render object.
  20214. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20215. */
  20216. has( renderObject ) {
  20217. const geometry = renderObject.geometry;
  20218. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20219. }
  20220. /**
  20221. * Prepares the geometry of the given render object for rendering.
  20222. *
  20223. * @param {RenderObject} renderObject - The render object.
  20224. */
  20225. updateForRender( renderObject ) {
  20226. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20227. this.updateAttributes( renderObject );
  20228. }
  20229. /**
  20230. * Initializes the geometry of the given render object.
  20231. *
  20232. * @param {RenderObject} renderObject - The render object.
  20233. */
  20234. initGeometry( renderObject ) {
  20235. const geometry = renderObject.geometry;
  20236. const geometryData = this.get( geometry );
  20237. geometryData.initialized = true;
  20238. this.info.memory.geometries ++;
  20239. const onDispose = () => {
  20240. this.info.memory.geometries --;
  20241. const index = geometry.index;
  20242. const geometryAttributes = renderObject.getAttributes();
  20243. if ( index !== null ) {
  20244. this.attributes.delete( index );
  20245. }
  20246. for ( const geometryAttribute of geometryAttributes ) {
  20247. this.attributes.delete( geometryAttribute );
  20248. }
  20249. const wireframeAttribute = this.wireframes.get( geometry );
  20250. if ( wireframeAttribute !== undefined ) {
  20251. this.attributes.delete( wireframeAttribute );
  20252. }
  20253. geometry.removeEventListener( 'dispose', onDispose );
  20254. };
  20255. geometry.addEventListener( 'dispose', onDispose );
  20256. }
  20257. /**
  20258. * Updates the geometry attributes of the given render object.
  20259. *
  20260. * @param {RenderObject} renderObject - The render object.
  20261. */
  20262. updateAttributes( renderObject ) {
  20263. // attributes
  20264. const attributes = renderObject.getAttributes();
  20265. for ( const attribute of attributes ) {
  20266. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20267. this.updateAttribute( attribute, AttributeType.STORAGE );
  20268. } else {
  20269. this.updateAttribute( attribute, AttributeType.VERTEX );
  20270. }
  20271. }
  20272. // indexes
  20273. const index = this.getIndex( renderObject );
  20274. if ( index !== null ) {
  20275. this.updateAttribute( index, AttributeType.INDEX );
  20276. }
  20277. // indirect
  20278. const indirect = renderObject.geometry.indirect;
  20279. if ( indirect !== null ) {
  20280. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20281. }
  20282. }
  20283. /**
  20284. * Updates the given attribute.
  20285. *
  20286. * @param {BufferAttribute} attribute - The attribute to update.
  20287. * @param {number} type - The attribute type.
  20288. */
  20289. updateAttribute( attribute, type ) {
  20290. const callId = this.info.render.calls;
  20291. if ( ! attribute.isInterleavedBufferAttribute ) {
  20292. if ( this.attributeCall.get( attribute ) !== callId ) {
  20293. this.attributes.update( attribute, type );
  20294. this.attributeCall.set( attribute, callId );
  20295. }
  20296. } else {
  20297. if ( this.attributeCall.get( attribute ) === undefined ) {
  20298. this.attributes.update( attribute, type );
  20299. this.attributeCall.set( attribute, callId );
  20300. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20301. this.attributes.update( attribute, type );
  20302. this.attributeCall.set( attribute.data, callId );
  20303. this.attributeCall.set( attribute, callId );
  20304. }
  20305. }
  20306. }
  20307. /**
  20308. * Returns the indirect buffer attribute of the given render object.
  20309. *
  20310. * @param {RenderObject} renderObject - The render object.
  20311. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20312. */
  20313. getIndirect( renderObject ) {
  20314. return renderObject.geometry.indirect;
  20315. }
  20316. /**
  20317. * Returns the index of the given render object's geometry. This is implemented
  20318. * in a method to return a wireframe index if necessary.
  20319. *
  20320. * @param {RenderObject} renderObject - The render object.
  20321. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20322. */
  20323. getIndex( renderObject ) {
  20324. const { geometry, material } = renderObject;
  20325. let index = geometry.index;
  20326. if ( material.wireframe === true ) {
  20327. const wireframes = this.wireframes;
  20328. let wireframeAttribute = wireframes.get( geometry );
  20329. if ( wireframeAttribute === undefined ) {
  20330. wireframeAttribute = getWireframeIndex( geometry );
  20331. wireframes.set( geometry, wireframeAttribute );
  20332. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20333. this.attributes.delete( wireframeAttribute );
  20334. wireframeAttribute = getWireframeIndex( geometry );
  20335. wireframes.set( geometry, wireframeAttribute );
  20336. }
  20337. index = wireframeAttribute;
  20338. }
  20339. return index;
  20340. }
  20341. }
  20342. /**
  20343. * This renderer module provides a series of statistical information
  20344. * about the GPU memory and the rendering process. Useful for debugging
  20345. * and monitoring.
  20346. */
  20347. class Info {
  20348. /**
  20349. * Constructs a new info component.
  20350. */
  20351. constructor() {
  20352. /**
  20353. * Whether frame related metrics should automatically
  20354. * be resetted or not. This property should be set to `false`
  20355. * by apps which manage their own animation loop. They must
  20356. * then call `renderer.info.reset()` once per frame manually.
  20357. *
  20358. * @type {boolean}
  20359. * @default true
  20360. */
  20361. this.autoReset = true;
  20362. /**
  20363. * The current frame ID. This ID is managed
  20364. * by `NodeFrame`.
  20365. *
  20366. * @type {number}
  20367. * @readonly
  20368. * @default 0
  20369. */
  20370. this.frame = 0;
  20371. /**
  20372. * The number of render calls since the
  20373. * app has been started.
  20374. *
  20375. * @type {number}
  20376. * @readonly
  20377. * @default 0
  20378. */
  20379. this.calls = 0;
  20380. /**
  20381. * Render related metrics.
  20382. *
  20383. * @type {Object}
  20384. * @readonly
  20385. * @property {number} calls - The number of render calls since the app has been started.
  20386. * @property {number} frameCalls - The number of render calls of the current frame.
  20387. * @property {number} drawCalls - The number of draw calls of the current frame.
  20388. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20389. * @property {number} points - The number of rendered point primitives of the current frame.
  20390. * @property {number} lines - The number of rendered line primitives of the current frame.
  20391. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  20392. */
  20393. this.render = {
  20394. calls: 0,
  20395. frameCalls: 0,
  20396. drawCalls: 0,
  20397. triangles: 0,
  20398. points: 0,
  20399. lines: 0,
  20400. timestamp: 0,
  20401. };
  20402. /**
  20403. * Compute related metrics.
  20404. *
  20405. * @type {Object}
  20406. * @readonly
  20407. * @property {number} calls - The number of compute calls since the app has been started.
  20408. * @property {number} frameCalls - The number of compute calls of the current frame.
  20409. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20410. */
  20411. this.compute = {
  20412. calls: 0,
  20413. frameCalls: 0,
  20414. timestamp: 0
  20415. };
  20416. /**
  20417. * Memory related metrics.
  20418. *
  20419. * @type {Object}
  20420. * @readonly
  20421. * @property {number} geometries - The number of active geometries.
  20422. * @property {number} frameCalls - The number of active textures.
  20423. */
  20424. this.memory = {
  20425. geometries: 0,
  20426. textures: 0
  20427. };
  20428. }
  20429. /**
  20430. * This method should be executed per draw call and updates the corresponding metrics.
  20431. *
  20432. * @param {Object3D} object - The 3D object that is going to be rendered.
  20433. * @param {number} count - The vertex or index count.
  20434. * @param {number} instanceCount - The instance count.
  20435. */
  20436. update( object, count, instanceCount ) {
  20437. this.render.drawCalls ++;
  20438. if ( object.isMesh || object.isSprite ) {
  20439. this.render.triangles += instanceCount * ( count / 3 );
  20440. } else if ( object.isPoints ) {
  20441. this.render.points += instanceCount * count;
  20442. } else if ( object.isLineSegments ) {
  20443. this.render.lines += instanceCount * ( count / 2 );
  20444. } else if ( object.isLine ) {
  20445. this.render.lines += instanceCount * ( count - 1 );
  20446. } else {
  20447. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  20448. }
  20449. }
  20450. /**
  20451. * Resets frame related metrics.
  20452. */
  20453. reset() {
  20454. this.render.drawCalls = 0;
  20455. this.render.frameCalls = 0;
  20456. this.compute.frameCalls = 0;
  20457. this.render.triangles = 0;
  20458. this.render.points = 0;
  20459. this.render.lines = 0;
  20460. }
  20461. /**
  20462. * Performs a complete reset of the object.
  20463. */
  20464. dispose() {
  20465. this.reset();
  20466. this.calls = 0;
  20467. this.render.calls = 0;
  20468. this.compute.calls = 0;
  20469. this.render.timestamp = 0;
  20470. this.compute.timestamp = 0;
  20471. this.memory.geometries = 0;
  20472. this.memory.textures = 0;
  20473. }
  20474. }
  20475. /**
  20476. * Abstract class for representing pipelines.
  20477. *
  20478. * @private
  20479. * @abstract
  20480. */
  20481. class Pipeline {
  20482. /**
  20483. * Constructs a new pipeline.
  20484. *
  20485. * @param {string} cacheKey - The pipeline's cache key.
  20486. */
  20487. constructor( cacheKey ) {
  20488. /**
  20489. * The pipeline's cache key.
  20490. *
  20491. * @type {string}
  20492. */
  20493. this.cacheKey = cacheKey;
  20494. /**
  20495. * How often the pipeline is currently in use.
  20496. *
  20497. * @type {number}
  20498. * @default 0
  20499. */
  20500. this.usedTimes = 0;
  20501. }
  20502. }
  20503. /**
  20504. * Class for representing render pipelines.
  20505. *
  20506. * @private
  20507. * @augments Pipeline
  20508. */
  20509. class RenderPipeline extends Pipeline {
  20510. /**
  20511. * Constructs a new render pipeline.
  20512. *
  20513. * @param {string} cacheKey - The pipeline's cache key.
  20514. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  20515. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  20516. */
  20517. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  20518. super( cacheKey );
  20519. /**
  20520. * The pipeline's vertex shader.
  20521. *
  20522. * @type {ProgrammableStage}
  20523. */
  20524. this.vertexProgram = vertexProgram;
  20525. /**
  20526. * The pipeline's fragment shader.
  20527. *
  20528. * @type {ProgrammableStage}
  20529. */
  20530. this.fragmentProgram = fragmentProgram;
  20531. }
  20532. }
  20533. /**
  20534. * Class for representing compute pipelines.
  20535. *
  20536. * @private
  20537. * @augments Pipeline
  20538. */
  20539. class ComputePipeline extends Pipeline {
  20540. /**
  20541. * Constructs a new render pipeline.
  20542. *
  20543. * @param {string} cacheKey - The pipeline's cache key.
  20544. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  20545. */
  20546. constructor( cacheKey, computeProgram ) {
  20547. super( cacheKey );
  20548. /**
  20549. * The pipeline's compute shader.
  20550. *
  20551. * @type {ProgrammableStage}
  20552. */
  20553. this.computeProgram = computeProgram;
  20554. /**
  20555. * This flag can be used for type testing.
  20556. *
  20557. * @type {boolean}
  20558. * @readonly
  20559. * @default true
  20560. */
  20561. this.isComputePipeline = true;
  20562. }
  20563. }
  20564. let _id$8 = 0;
  20565. /**
  20566. * Class for representing programmable stages which are vertex,
  20567. * fragment or compute shaders. Unlike fixed-function states (like blending),
  20568. * they represent the programmable part of a pipeline.
  20569. *
  20570. * @private
  20571. */
  20572. class ProgrammableStage {
  20573. /**
  20574. * Constructs a new programmable stage.
  20575. *
  20576. * @param {string} code - The shader code.
  20577. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  20578. * @param {string} name - The name of the shader.
  20579. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20580. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20581. */
  20582. constructor( code, stage, name, transforms = null, attributes = null ) {
  20583. /**
  20584. * The id of the programmable stage.
  20585. *
  20586. * @type {number}
  20587. */
  20588. this.id = _id$8 ++;
  20589. /**
  20590. * The shader code.
  20591. *
  20592. * @type {string}
  20593. */
  20594. this.code = code;
  20595. /**
  20596. * The type of stage.
  20597. *
  20598. * @type {string}
  20599. */
  20600. this.stage = stage;
  20601. /**
  20602. * The name of the stage.
  20603. * This is used for debugging purposes.
  20604. *
  20605. * @type {string}
  20606. */
  20607. this.name = name;
  20608. /**
  20609. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20610. *
  20611. * @type {?Array<Object>}
  20612. */
  20613. this.transforms = transforms;
  20614. /**
  20615. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20616. *
  20617. * @type {?Array<Object>}
  20618. */
  20619. this.attributes = attributes;
  20620. /**
  20621. * How often the programmable stage is currently in use.
  20622. *
  20623. * @type {number}
  20624. * @default 0
  20625. */
  20626. this.usedTimes = 0;
  20627. }
  20628. }
  20629. /**
  20630. * This renderer module manages the pipelines of the renderer.
  20631. *
  20632. * @private
  20633. * @augments DataMap
  20634. */
  20635. class Pipelines extends DataMap {
  20636. /**
  20637. * Constructs a new pipeline management component.
  20638. *
  20639. * @param {Backend} backend - The renderer's backend.
  20640. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20641. */
  20642. constructor( backend, nodes ) {
  20643. super();
  20644. /**
  20645. * The renderer's backend.
  20646. *
  20647. * @type {Backend}
  20648. */
  20649. this.backend = backend;
  20650. /**
  20651. * Renderer component for managing nodes related logic.
  20652. *
  20653. * @type {Nodes}
  20654. */
  20655. this.nodes = nodes;
  20656. /**
  20657. * A references to the bindings management component.
  20658. * This reference will be set inside the `Bindings`
  20659. * constructor.
  20660. *
  20661. * @type {?Bindings}
  20662. * @default null
  20663. */
  20664. this.bindings = null;
  20665. /**
  20666. * Internal cache for maintaining pipelines.
  20667. * The key of the map is a cache key, the value the pipeline.
  20668. *
  20669. * @type {Map<string,Pipeline>}
  20670. */
  20671. this.caches = new Map();
  20672. /**
  20673. * This dictionary maintains for each shader stage type (vertex,
  20674. * fragment and compute) the programmable stage objects which
  20675. * represent the actual shader code.
  20676. *
  20677. * @type {Object<string,Map>}
  20678. */
  20679. this.programs = {
  20680. vertex: new Map(),
  20681. fragment: new Map(),
  20682. compute: new Map()
  20683. };
  20684. }
  20685. /**
  20686. * Returns a compute pipeline for the given compute node.
  20687. *
  20688. * @param {Node} computeNode - The compute node.
  20689. * @param {Array<BindGroup>} bindings - The bindings.
  20690. * @return {ComputePipeline} The compute pipeline.
  20691. */
  20692. getForCompute( computeNode, bindings ) {
  20693. const { backend } = this;
  20694. const data = this.get( computeNode );
  20695. if ( this._needsComputeUpdate( computeNode ) ) {
  20696. const previousPipeline = data.pipeline;
  20697. if ( previousPipeline ) {
  20698. previousPipeline.usedTimes --;
  20699. previousPipeline.computeProgram.usedTimes --;
  20700. }
  20701. // get shader
  20702. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  20703. // programmable stage
  20704. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  20705. if ( stageCompute === undefined ) {
  20706. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  20707. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  20708. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  20709. backend.createProgram( stageCompute );
  20710. }
  20711. // determine compute pipeline
  20712. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  20713. let pipeline = this.caches.get( cacheKey );
  20714. if ( pipeline === undefined ) {
  20715. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20716. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  20717. }
  20718. // keep track of all used times
  20719. pipeline.usedTimes ++;
  20720. stageCompute.usedTimes ++;
  20721. //
  20722. data.version = computeNode.version;
  20723. data.pipeline = pipeline;
  20724. }
  20725. return data.pipeline;
  20726. }
  20727. /**
  20728. * Returns a render pipeline for the given render object.
  20729. *
  20730. * @param {RenderObject} renderObject - The render object.
  20731. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20732. * @return {RenderPipeline} The render pipeline.
  20733. */
  20734. getForRender( renderObject, promises = null ) {
  20735. const { backend } = this;
  20736. const data = this.get( renderObject );
  20737. if ( this._needsRenderUpdate( renderObject ) ) {
  20738. const previousPipeline = data.pipeline;
  20739. if ( previousPipeline ) {
  20740. previousPipeline.usedTimes --;
  20741. previousPipeline.vertexProgram.usedTimes --;
  20742. previousPipeline.fragmentProgram.usedTimes --;
  20743. }
  20744. // get shader
  20745. const nodeBuilderState = renderObject.getNodeBuilderState();
  20746. const name = renderObject.material ? renderObject.material.name : '';
  20747. // programmable stages
  20748. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  20749. if ( stageVertex === undefined ) {
  20750. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  20751. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  20752. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  20753. backend.createProgram( stageVertex );
  20754. }
  20755. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  20756. if ( stageFragment === undefined ) {
  20757. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  20758. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  20759. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  20760. backend.createProgram( stageFragment );
  20761. }
  20762. // determine render pipeline
  20763. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20764. let pipeline = this.caches.get( cacheKey );
  20765. if ( pipeline === undefined ) {
  20766. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20767. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  20768. } else {
  20769. renderObject.pipeline = pipeline;
  20770. }
  20771. // keep track of all used times
  20772. pipeline.usedTimes ++;
  20773. stageVertex.usedTimes ++;
  20774. stageFragment.usedTimes ++;
  20775. //
  20776. data.pipeline = pipeline;
  20777. }
  20778. return data.pipeline;
  20779. }
  20780. /**
  20781. * Deletes the pipeline for the given render object.
  20782. *
  20783. * @param {RenderObject} object - The render object.
  20784. * @return {?Object} The deleted dictionary.
  20785. */
  20786. delete( object ) {
  20787. const pipeline = this.get( object ).pipeline;
  20788. if ( pipeline ) {
  20789. // pipeline
  20790. pipeline.usedTimes --;
  20791. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  20792. // programs
  20793. if ( pipeline.isComputePipeline ) {
  20794. pipeline.computeProgram.usedTimes --;
  20795. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  20796. } else {
  20797. pipeline.fragmentProgram.usedTimes --;
  20798. pipeline.vertexProgram.usedTimes --;
  20799. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  20800. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  20801. }
  20802. }
  20803. return super.delete( object );
  20804. }
  20805. /**
  20806. * Frees internal resources.
  20807. */
  20808. dispose() {
  20809. super.dispose();
  20810. this.caches = new Map();
  20811. this.programs = {
  20812. vertex: new Map(),
  20813. fragment: new Map(),
  20814. compute: new Map()
  20815. };
  20816. }
  20817. /**
  20818. * Updates the pipeline for the given render object.
  20819. *
  20820. * @param {RenderObject} renderObject - The render object.
  20821. */
  20822. updateForRender( renderObject ) {
  20823. this.getForRender( renderObject );
  20824. }
  20825. /**
  20826. * Returns a compute pipeline for the given parameters.
  20827. *
  20828. * @private
  20829. * @param {Node} computeNode - The compute node.
  20830. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20831. * @param {string} cacheKey - The cache key.
  20832. * @param {Array<BindGroup>} bindings - The bindings.
  20833. * @return {ComputePipeline} The compute pipeline.
  20834. */
  20835. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  20836. // check for existing pipeline
  20837. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  20838. let pipeline = this.caches.get( cacheKey );
  20839. if ( pipeline === undefined ) {
  20840. pipeline = new ComputePipeline( cacheKey, stageCompute );
  20841. this.caches.set( cacheKey, pipeline );
  20842. this.backend.createComputePipeline( pipeline, bindings );
  20843. }
  20844. return pipeline;
  20845. }
  20846. /**
  20847. * Returns a render pipeline for the given parameters.
  20848. *
  20849. * @private
  20850. * @param {RenderObject} renderObject - The render object.
  20851. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20852. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20853. * @param {string} cacheKey - The cache key.
  20854. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20855. * @return {ComputePipeline} The compute pipeline.
  20856. */
  20857. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  20858. // check for existing pipeline
  20859. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20860. let pipeline = this.caches.get( cacheKey );
  20861. if ( pipeline === undefined ) {
  20862. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  20863. this.caches.set( cacheKey, pipeline );
  20864. renderObject.pipeline = pipeline;
  20865. // The `promises` array is `null` by default and only set to an empty array when
  20866. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  20867. // pending promises that resolve when the render pipelines are ready for rendering.
  20868. this.backend.createRenderPipeline( renderObject, promises );
  20869. }
  20870. return pipeline;
  20871. }
  20872. /**
  20873. * Computes a cache key representing a compute pipeline.
  20874. *
  20875. * @private
  20876. * @param {Node} computeNode - The compute node.
  20877. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20878. * @return {string} The cache key.
  20879. */
  20880. _getComputeCacheKey( computeNode, stageCompute ) {
  20881. return computeNode.id + ',' + stageCompute.id;
  20882. }
  20883. /**
  20884. * Computes a cache key representing a render pipeline.
  20885. *
  20886. * @private
  20887. * @param {RenderObject} renderObject - The render object.
  20888. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20889. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20890. * @return {string} The cache key.
  20891. */
  20892. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  20893. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  20894. }
  20895. /**
  20896. * Releases the given pipeline.
  20897. *
  20898. * @private
  20899. * @param {Pipeline} pipeline - The pipeline to release.
  20900. */
  20901. _releasePipeline( pipeline ) {
  20902. this.caches.delete( pipeline.cacheKey );
  20903. }
  20904. /**
  20905. * Releases the shader program.
  20906. *
  20907. * @private
  20908. * @param {Object} program - The shader program to release.
  20909. */
  20910. _releaseProgram( program ) {
  20911. const code = program.code;
  20912. const stage = program.stage;
  20913. this.programs[ stage ].delete( code );
  20914. }
  20915. /**
  20916. * Returns `true` if the compute pipeline for the given compute node requires an update.
  20917. *
  20918. * @private
  20919. * @param {Node} computeNode - The compute node.
  20920. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  20921. */
  20922. _needsComputeUpdate( computeNode ) {
  20923. const data = this.get( computeNode );
  20924. return data.pipeline === undefined || data.version !== computeNode.version;
  20925. }
  20926. /**
  20927. * Returns `true` if the render pipeline for the given render object requires an update.
  20928. *
  20929. * @private
  20930. * @param {RenderObject} renderObject - The render object.
  20931. * @return {boolean} Whether the render object for the given render object requires an update or not.
  20932. */
  20933. _needsRenderUpdate( renderObject ) {
  20934. const data = this.get( renderObject );
  20935. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  20936. }
  20937. }
  20938. /**
  20939. * This renderer module manages the bindings of the renderer.
  20940. *
  20941. * @private
  20942. * @augments DataMap
  20943. */
  20944. class Bindings extends DataMap {
  20945. /**
  20946. * Constructs a new bindings management component.
  20947. *
  20948. * @param {Backend} backend - The renderer's backend.
  20949. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20950. * @param {Textures} textures - Renderer component for managing textures.
  20951. * @param {Attributes} attributes - Renderer component for managing attributes.
  20952. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20953. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20954. */
  20955. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  20956. super();
  20957. /**
  20958. * The renderer's backend.
  20959. *
  20960. * @type {Backend}
  20961. */
  20962. this.backend = backend;
  20963. /**
  20964. * Renderer component for managing textures.
  20965. *
  20966. * @type {Textures}
  20967. */
  20968. this.textures = textures;
  20969. /**
  20970. * Renderer component for managing pipelines.
  20971. *
  20972. * @type {Pipelines}
  20973. */
  20974. this.pipelines = pipelines;
  20975. /**
  20976. * Renderer component for managing attributes.
  20977. *
  20978. * @type {Attributes}
  20979. */
  20980. this.attributes = attributes;
  20981. /**
  20982. * Renderer component for managing nodes related logic.
  20983. *
  20984. * @type {Nodes}
  20985. */
  20986. this.nodes = nodes;
  20987. /**
  20988. * Renderer component for managing metrics and monitoring data.
  20989. *
  20990. * @type {Info}
  20991. */
  20992. this.info = info;
  20993. this.pipelines.bindings = this; // assign bindings to pipelines
  20994. }
  20995. /**
  20996. * Returns the bind groups for the given render object.
  20997. *
  20998. * @param {RenderObject} renderObject - The render object.
  20999. * @return {Array<BindGroup>} The bind groups.
  21000. */
  21001. getForRender( renderObject ) {
  21002. const bindings = renderObject.getBindings();
  21003. for ( const bindGroup of bindings ) {
  21004. const groupData = this.get( bindGroup );
  21005. if ( groupData.bindGroup === undefined ) {
  21006. // each object defines an array of bindings (ubos, textures, samplers etc.)
  21007. this._init( bindGroup );
  21008. this.backend.createBindings( bindGroup, bindings, 0 );
  21009. groupData.bindGroup = bindGroup;
  21010. }
  21011. }
  21012. return bindings;
  21013. }
  21014. /**
  21015. * Returns the bind groups for the given compute node.
  21016. *
  21017. * @param {Node} computeNode - The compute node.
  21018. * @return {Array<BindGroup>} The bind groups.
  21019. */
  21020. getForCompute( computeNode ) {
  21021. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21022. for ( const bindGroup of bindings ) {
  21023. const groupData = this.get( bindGroup );
  21024. if ( groupData.bindGroup === undefined ) {
  21025. this._init( bindGroup );
  21026. this.backend.createBindings( bindGroup, bindings, 0 );
  21027. groupData.bindGroup = bindGroup;
  21028. }
  21029. }
  21030. return bindings;
  21031. }
  21032. /**
  21033. * Updates the bindings for the given compute node.
  21034. *
  21035. * @param {Node} computeNode - The compute node.
  21036. */
  21037. updateForCompute( computeNode ) {
  21038. this._updateBindings( this.getForCompute( computeNode ) );
  21039. }
  21040. /**
  21041. * Updates the bindings for the given render object.
  21042. *
  21043. * @param {RenderObject} renderObject - The render object.
  21044. */
  21045. updateForRender( renderObject ) {
  21046. this._updateBindings( this.getForRender( renderObject ) );
  21047. }
  21048. /**
  21049. * Updates the given array of bindings.
  21050. *
  21051. * @param {Array<BindGroup>} bindings - The bind groups.
  21052. */
  21053. _updateBindings( bindings ) {
  21054. for ( const bindGroup of bindings ) {
  21055. this._update( bindGroup, bindings );
  21056. }
  21057. }
  21058. /**
  21059. * Initializes the given bind group.
  21060. *
  21061. * @param {BindGroup} bindGroup - The bind group to initialize.
  21062. */
  21063. _init( bindGroup ) {
  21064. for ( const binding of bindGroup.bindings ) {
  21065. if ( binding.isSampledTexture ) {
  21066. this.textures.updateTexture( binding.texture );
  21067. } else if ( binding.isStorageBuffer ) {
  21068. const attribute = binding.attribute;
  21069. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21070. this.attributes.update( attribute, attributeType );
  21071. }
  21072. }
  21073. }
  21074. /**
  21075. * Updates the given bind group.
  21076. *
  21077. * @param {BindGroup} bindGroup - The bind group to update.
  21078. * @param {Array<BindGroup>} bindings - The bind groups.
  21079. */
  21080. _update( bindGroup, bindings ) {
  21081. const { backend } = this;
  21082. let needsBindingsUpdate = false;
  21083. let cacheBindings = true;
  21084. let cacheIndex = 0;
  21085. let version = 0;
  21086. // iterate over all bindings and check if buffer updates or a new binding group is required
  21087. for ( const binding of bindGroup.bindings ) {
  21088. if ( binding.isNodeUniformsGroup ) {
  21089. const updated = this.nodes.updateGroup( binding );
  21090. // every uniforms group is a uniform buffer. So if no update is required,
  21091. // we move one with the next binding. Otherwise the next if block will update the group.
  21092. if ( updated === false ) continue;
  21093. }
  21094. if ( binding.isStorageBuffer ) {
  21095. const attribute = binding.attribute;
  21096. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21097. this.attributes.update( attribute, attributeType );
  21098. }
  21099. if ( binding.isUniformBuffer ) {
  21100. const updated = binding.update();
  21101. if ( updated ) {
  21102. backend.updateBinding( binding );
  21103. }
  21104. } else if ( binding.isSampledTexture ) {
  21105. const updated = binding.update();
  21106. // get the texture data after the update, to sync the texture reference from node
  21107. const texture = binding.texture;
  21108. const texturesTextureData = this.textures.get( texture );
  21109. if ( updated ) {
  21110. // version: update the texture data or create a new one
  21111. this.textures.updateTexture( texture );
  21112. // generation: update the bindings if a new texture has been created
  21113. if ( binding.generation !== texturesTextureData.generation ) {
  21114. binding.generation = texturesTextureData.generation;
  21115. needsBindingsUpdate = true;
  21116. }
  21117. }
  21118. const textureData = backend.get( texture );
  21119. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  21120. cacheBindings = false;
  21121. } else {
  21122. cacheIndex = cacheIndex * 10 + texture.id;
  21123. version += texture.version;
  21124. }
  21125. if ( texture.isStorageTexture === true ) {
  21126. const textureData = this.get( texture );
  21127. if ( binding.store === true ) {
  21128. textureData.needsMipmap = true;
  21129. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  21130. this.backend.generateMipmaps( texture );
  21131. textureData.needsMipmap = false;
  21132. }
  21133. }
  21134. } else if ( binding.isSampler ) {
  21135. binding.update();
  21136. }
  21137. }
  21138. if ( needsBindingsUpdate === true ) {
  21139. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  21140. }
  21141. }
  21142. }
  21143. /**
  21144. * Default sorting function for opaque render items.
  21145. *
  21146. * @private
  21147. * @function
  21148. * @param {Object} a - The first render item.
  21149. * @param {Object} b - The second render item.
  21150. * @return {number} A numeric value which defines the sort order.
  21151. */
  21152. function painterSortStable( a, b ) {
  21153. if ( a.groupOrder !== b.groupOrder ) {
  21154. return a.groupOrder - b.groupOrder;
  21155. } else if ( a.renderOrder !== b.renderOrder ) {
  21156. return a.renderOrder - b.renderOrder;
  21157. } else if ( a.z !== b.z ) {
  21158. return a.z - b.z;
  21159. } else {
  21160. return a.id - b.id;
  21161. }
  21162. }
  21163. /**
  21164. * Default sorting function for transparent render items.
  21165. *
  21166. * @private
  21167. * @function
  21168. * @param {Object} a - The first render item.
  21169. * @param {Object} b - The second render item.
  21170. * @return {number} A numeric value which defines the sort order.
  21171. */
  21172. function reversePainterSortStable( a, b ) {
  21173. if ( a.groupOrder !== b.groupOrder ) {
  21174. return a.groupOrder - b.groupOrder;
  21175. } else if ( a.renderOrder !== b.renderOrder ) {
  21176. return a.renderOrder - b.renderOrder;
  21177. } else if ( a.z !== b.z ) {
  21178. return b.z - a.z;
  21179. } else {
  21180. return a.id - b.id;
  21181. }
  21182. }
  21183. /**
  21184. * Returns `true` if the given transparent material requires a double pass.
  21185. *
  21186. * @private
  21187. * @function
  21188. * @param {Material} material - The transparent material.
  21189. * @return {boolean} Whether the given material requires a double pass or not.
  21190. */
  21191. function needsDoublePass( material ) {
  21192. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  21193. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21194. }
  21195. /**
  21196. * When the renderer analyzes the scene at the beginning of a render call,
  21197. * it stores 3D object for further processing in render lists. Depending on the
  21198. * properties of a 3D objects (like their transformation or material state), the
  21199. * objects are maintained in ordered lists for the actual rendering.
  21200. *
  21201. * Render lists are unique per scene and camera combination.
  21202. *
  21203. * @private
  21204. * @augments Pipeline
  21205. */
  21206. class RenderList {
  21207. /**
  21208. * Constructs a render list.
  21209. *
  21210. * @param {Lighting} lighting - The lighting management component.
  21211. * @param {Scene} scene - The scene.
  21212. * @param {Camera} camera - The camera the scene is rendered with.
  21213. */
  21214. constructor( lighting, scene, camera ) {
  21215. /**
  21216. * 3D objects are transformed into render items and stored in this array.
  21217. *
  21218. * @type {Array<Object>}
  21219. */
  21220. this.renderItems = [];
  21221. /**
  21222. * The current render items index.
  21223. *
  21224. * @type {number}
  21225. * @default 0
  21226. */
  21227. this.renderItemsIndex = 0;
  21228. /**
  21229. * A list with opaque render items.
  21230. *
  21231. * @type {Array<Object>}
  21232. */
  21233. this.opaque = [];
  21234. /**
  21235. * A list with transparent render items which require
  21236. * double pass rendering (e.g. transmissive objects).
  21237. *
  21238. * @type {Array<Object>}
  21239. */
  21240. this.transparentDoublePass = [];
  21241. /**
  21242. * A list with transparent render items.
  21243. *
  21244. * @type {Array<Object>}
  21245. */
  21246. this.transparent = [];
  21247. /**
  21248. * A list with transparent render bundle data.
  21249. *
  21250. * @type {Array<Object>}
  21251. */
  21252. this.bundles = [];
  21253. /**
  21254. * The render list's lights node. This node is later
  21255. * relevant for the actual analytical light nodes which
  21256. * compute the scene's lighting in the shader.
  21257. *
  21258. * @type {LightsNode}
  21259. */
  21260. this.lightsNode = lighting.getNode( scene, camera );
  21261. /**
  21262. * The scene's lights stored in an array. This array
  21263. * is used to setup the lights node.
  21264. *
  21265. * @type {Array<Light>}
  21266. */
  21267. this.lightsArray = [];
  21268. /**
  21269. * The scene.
  21270. *
  21271. * @type {Scene}
  21272. */
  21273. this.scene = scene;
  21274. /**
  21275. * The camera the scene is rendered with.
  21276. *
  21277. * @type {Camera}
  21278. */
  21279. this.camera = camera;
  21280. /**
  21281. * How many objects perform occlusion query tests.
  21282. *
  21283. * @type {number}
  21284. * @default 0
  21285. */
  21286. this.occlusionQueryCount = 0;
  21287. }
  21288. /**
  21289. * This method is called right at the beginning of a render call
  21290. * before the scene is analyzed. It prepares the internal data
  21291. * structures for the upcoming render lists generation.
  21292. *
  21293. * @return {RenderList} A reference to this render list.
  21294. */
  21295. begin() {
  21296. this.renderItemsIndex = 0;
  21297. this.opaque.length = 0;
  21298. this.transparentDoublePass.length = 0;
  21299. this.transparent.length = 0;
  21300. this.bundles.length = 0;
  21301. this.lightsArray.length = 0;
  21302. this.occlusionQueryCount = 0;
  21303. return this;
  21304. }
  21305. /**
  21306. * Returns a render item for the giving render item state. The state is defined
  21307. * by a series of object-related parameters.
  21308. *
  21309. * The method avoids object creation by holding render items and reusing them in
  21310. * subsequent render calls (just with different property values).
  21311. *
  21312. * @param {Object3D} object - The 3D object.
  21313. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21314. * @param {Material} material - The 3D object's material.
  21315. * @param {number} groupOrder - The current group order.
  21316. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21317. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21318. * @param {ClippingContext} clippingContext - The current clipping context.
  21319. * @return {Object} The render item.
  21320. */
  21321. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21322. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21323. if ( renderItem === undefined ) {
  21324. renderItem = {
  21325. id: object.id,
  21326. object: object,
  21327. geometry: geometry,
  21328. material: material,
  21329. groupOrder: groupOrder,
  21330. renderOrder: object.renderOrder,
  21331. z: z,
  21332. group: group,
  21333. clippingContext: clippingContext
  21334. };
  21335. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21336. } else {
  21337. renderItem.id = object.id;
  21338. renderItem.object = object;
  21339. renderItem.geometry = geometry;
  21340. renderItem.material = material;
  21341. renderItem.groupOrder = groupOrder;
  21342. renderItem.renderOrder = object.renderOrder;
  21343. renderItem.z = z;
  21344. renderItem.group = group;
  21345. renderItem.clippingContext = clippingContext;
  21346. }
  21347. this.renderItemsIndex ++;
  21348. return renderItem;
  21349. }
  21350. /**
  21351. * Pushes the given object as a render item to the internal render lists.
  21352. * The selected lists depend on the object properties.
  21353. *
  21354. * @param {Object3D} object - The 3D object.
  21355. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21356. * @param {Material} material - The 3D object's material.
  21357. * @param {number} groupOrder - The current group order.
  21358. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21359. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21360. * @param {ClippingContext} clippingContext - The current clipping context.
  21361. */
  21362. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21363. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21364. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21365. if ( material.transparent === true || material.transmission > 0 ) {
  21366. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21367. this.transparent.push( renderItem );
  21368. } else {
  21369. this.opaque.push( renderItem );
  21370. }
  21371. }
  21372. /**
  21373. * Inserts the given object as a render item at the start of the internal render lists.
  21374. * The selected lists depend on the object properties.
  21375. *
  21376. * @param {Object3D} object - The 3D object.
  21377. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21378. * @param {Material} material - The 3D object's material.
  21379. * @param {number} groupOrder - The current group order.
  21380. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21381. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21382. * @param {ClippingContext} clippingContext - The current clipping context.
  21383. */
  21384. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21385. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21386. if ( material.transparent === true || material.transmission > 0 ) {
  21387. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21388. this.transparent.unshift( renderItem );
  21389. } else {
  21390. this.opaque.unshift( renderItem );
  21391. }
  21392. }
  21393. /**
  21394. * Pushes render bundle group data into the render list.
  21395. *
  21396. * @param {Object} group - Bundle group data.
  21397. */
  21398. pushBundle( group ) {
  21399. this.bundles.push( group );
  21400. }
  21401. /**
  21402. * Pushes a light into the render list.
  21403. *
  21404. * @param {Light} light - The light.
  21405. */
  21406. pushLight( light ) {
  21407. this.lightsArray.push( light );
  21408. }
  21409. /**
  21410. * Sorts the internal render lists.
  21411. *
  21412. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  21413. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  21414. */
  21415. sort( customOpaqueSort, customTransparentSort ) {
  21416. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  21417. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  21418. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  21419. }
  21420. /**
  21421. * This method performs finalizing tasks right after the render lists
  21422. * have been generated.
  21423. */
  21424. finish() {
  21425. // update lights
  21426. this.lightsNode.setLights( this.lightsArray );
  21427. // Clear references from inactive renderItems in the list
  21428. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  21429. const renderItem = this.renderItems[ i ];
  21430. if ( renderItem.id === null ) break;
  21431. renderItem.id = null;
  21432. renderItem.object = null;
  21433. renderItem.geometry = null;
  21434. renderItem.material = null;
  21435. renderItem.groupOrder = null;
  21436. renderItem.renderOrder = null;
  21437. renderItem.z = null;
  21438. renderItem.group = null;
  21439. renderItem.clippingContext = null;
  21440. }
  21441. }
  21442. }
  21443. const _chainKeys$4 = [];
  21444. /**
  21445. * This renderer module manages the render lists which are unique
  21446. * per scene and camera combination.
  21447. *
  21448. * @private
  21449. */
  21450. class RenderLists {
  21451. /**
  21452. * Constructs a render lists management component.
  21453. *
  21454. * @param {Lighting} lighting - The lighting management component.
  21455. */
  21456. constructor( lighting ) {
  21457. /**
  21458. * The lighting management component.
  21459. *
  21460. * @type {Lighting}
  21461. */
  21462. this.lighting = lighting;
  21463. /**
  21464. * The internal chain map which holds the render lists.
  21465. *
  21466. * @type {ChainMap}
  21467. */
  21468. this.lists = new ChainMap();
  21469. }
  21470. /**
  21471. * Returns a render list for the given scene and camera.
  21472. *
  21473. * @param {Scene} scene - The scene.
  21474. * @param {Camera} camera - The camera.
  21475. * @return {RenderList} The render list.
  21476. */
  21477. get( scene, camera ) {
  21478. const lists = this.lists;
  21479. _chainKeys$4[ 0 ] = scene;
  21480. _chainKeys$4[ 1 ] = camera;
  21481. let list = lists.get( _chainKeys$4 );
  21482. if ( list === undefined ) {
  21483. list = new RenderList( this.lighting, scene, camera );
  21484. lists.set( _chainKeys$4, list );
  21485. }
  21486. _chainKeys$4.length = 0;
  21487. return list;
  21488. }
  21489. /**
  21490. * Frees all internal resources.
  21491. */
  21492. dispose() {
  21493. this.lists = new ChainMap();
  21494. }
  21495. }
  21496. let _id$7 = 0;
  21497. /**
  21498. * Any render or compute command is executed in a specific context that defines
  21499. * the state of the renderer and its backend. Typical examples for such context
  21500. * data are the current clear values or data from the active framebuffer. This
  21501. * module is used to represent these contexts as objects.
  21502. *
  21503. * @private
  21504. */
  21505. class RenderContext {
  21506. /**
  21507. * Constructs a new render context.
  21508. */
  21509. constructor() {
  21510. /**
  21511. * The context's ID.
  21512. *
  21513. * @type {number}
  21514. */
  21515. this.id = _id$7 ++;
  21516. /**
  21517. * Whether the current active framebuffer has a color attachment.
  21518. *
  21519. * @type {boolean}
  21520. * @default true
  21521. */
  21522. this.color = true;
  21523. /**
  21524. * Whether the color attachment should be cleared or not.
  21525. *
  21526. * @type {boolean}
  21527. * @default true
  21528. */
  21529. this.clearColor = true;
  21530. /**
  21531. * The clear color value.
  21532. *
  21533. * @type {Object}
  21534. * @default true
  21535. */
  21536. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  21537. /**
  21538. * Whether the current active framebuffer has a depth attachment.
  21539. *
  21540. * @type {boolean}
  21541. * @default true
  21542. */
  21543. this.depth = true;
  21544. /**
  21545. * Whether the depth attachment should be cleared or not.
  21546. *
  21547. * @type {boolean}
  21548. * @default true
  21549. */
  21550. this.clearDepth = true;
  21551. /**
  21552. * The clear depth value.
  21553. *
  21554. * @type {number}
  21555. * @default 1
  21556. */
  21557. this.clearDepthValue = 1;
  21558. /**
  21559. * Whether the current active framebuffer has a stencil attachment.
  21560. *
  21561. * @type {boolean}
  21562. * @default false
  21563. */
  21564. this.stencil = false;
  21565. /**
  21566. * Whether the stencil attachment should be cleared or not.
  21567. *
  21568. * @type {boolean}
  21569. * @default true
  21570. */
  21571. this.clearStencil = true;
  21572. /**
  21573. * The clear stencil value.
  21574. *
  21575. * @type {number}
  21576. * @default 1
  21577. */
  21578. this.clearStencilValue = 1;
  21579. /**
  21580. * By default the viewport encloses the entire framebuffer If a smaller
  21581. * viewport is manually defined, this property is to `true` by the renderer.
  21582. *
  21583. * @type {boolean}
  21584. * @default false
  21585. */
  21586. this.viewport = false;
  21587. /**
  21588. * The viewport value. This value is in physical pixels meaning it incorporates
  21589. * the renderer's pixel ratio. The viewport property of render targets or
  21590. * the renderer is in logical pixels.
  21591. *
  21592. * @type {Vector4}
  21593. */
  21594. this.viewportValue = new Vector4();
  21595. /**
  21596. * When the scissor test is active and scissor rectangle smaller than the
  21597. * framebuffers dimensions, this property is to `true` by the renderer.
  21598. *
  21599. * @type {boolean}
  21600. * @default false
  21601. */
  21602. this.scissor = false;
  21603. /**
  21604. * The scissor rectangle.
  21605. *
  21606. * @type {Vector4}
  21607. */
  21608. this.scissorValue = new Vector4();
  21609. /**
  21610. * The active render target.
  21611. *
  21612. * @type {?RenderTarget}
  21613. * @default null
  21614. */
  21615. this.renderTarget = null;
  21616. /**
  21617. * The textures of the active render target.
  21618. * `null` when no render target is set.
  21619. *
  21620. * @type {?Array<Texture>}
  21621. * @default null
  21622. */
  21623. this.textures = null;
  21624. /**
  21625. * The depth texture of the active render target.
  21626. * `null` when no render target is set.
  21627. *
  21628. * @type {?DepthTexture}
  21629. * @default null
  21630. */
  21631. this.depthTexture = null;
  21632. /**
  21633. * The active cube face.
  21634. *
  21635. * @type {number}
  21636. * @default 0
  21637. */
  21638. this.activeCubeFace = 0;
  21639. /**
  21640. * The active mipmap level.
  21641. *
  21642. * @type {number}
  21643. * @default 0
  21644. */
  21645. this.activeMipmapLevel = 0;
  21646. /**
  21647. * The number of MSAA samples. This value is always `1` when
  21648. * MSAA isn't used.
  21649. *
  21650. * @type {number}
  21651. * @default 1
  21652. */
  21653. this.sampleCount = 1;
  21654. /**
  21655. * The active render target's width in physical pixels.
  21656. *
  21657. * @type {number}
  21658. * @default 0
  21659. */
  21660. this.width = 0;
  21661. /**
  21662. * The active render target's height in physical pixels.
  21663. *
  21664. * @type {number}
  21665. * @default 0
  21666. */
  21667. this.height = 0;
  21668. /**
  21669. * The occlusion query count.
  21670. *
  21671. * @type {number}
  21672. * @default 0
  21673. */
  21674. this.occlusionQueryCount = 0;
  21675. /**
  21676. * The current clipping context.
  21677. *
  21678. * @type {?ClippingContext}
  21679. * @default null
  21680. */
  21681. this.clippingContext = null;
  21682. /**
  21683. * This flag can be used for type testing.
  21684. *
  21685. * @type {boolean}
  21686. * @readonly
  21687. * @default true
  21688. */
  21689. this.isRenderContext = true;
  21690. }
  21691. /**
  21692. * Returns the cache key of this render context.
  21693. *
  21694. * @return {number} The cache key.
  21695. */
  21696. getCacheKey() {
  21697. return getCacheKey( this );
  21698. }
  21699. }
  21700. /**
  21701. * Computes a cache key for the given render context. This key
  21702. * should identify the render target state so it is possible to
  21703. * configure the correct attachments in the respective backend.
  21704. *
  21705. * @param {RenderContext} renderContext - The render context.
  21706. * @return {number} The cache key.
  21707. */
  21708. function getCacheKey( renderContext ) {
  21709. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  21710. const values = [ activeCubeFace, activeMipmapLevel ];
  21711. for ( const texture of textures ) {
  21712. values.push( texture.id );
  21713. }
  21714. return hashArray( values );
  21715. }
  21716. const _chainKeys$3 = [];
  21717. const _defaultScene = /*@__PURE__*/ new Scene();
  21718. const _defaultCamera = /*@__PURE__*/ new Camera();
  21719. /**
  21720. * This module manages the render contexts of the renderer.
  21721. *
  21722. * @private
  21723. */
  21724. class RenderContexts {
  21725. /**
  21726. * Constructs a new render context management component.
  21727. */
  21728. constructor() {
  21729. /**
  21730. * A dictionary that manages render contexts in chain maps
  21731. * for each attachment state.
  21732. *
  21733. * @type {Object<string,ChainMap>}
  21734. */
  21735. this.chainMaps = {};
  21736. }
  21737. /**
  21738. * Returns a render context for the given scene, camera and render target.
  21739. *
  21740. * @param {Scene} scene - The scene.
  21741. * @param {Camera} camera - The camera that is used to render the scene.
  21742. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21743. * @return {RenderContext} The render context.
  21744. */
  21745. get( scene, camera, renderTarget = null ) {
  21746. _chainKeys$3[ 0 ] = scene;
  21747. _chainKeys$3[ 1 ] = camera;
  21748. let attachmentState;
  21749. if ( renderTarget === null ) {
  21750. attachmentState = 'default';
  21751. } else {
  21752. const format = renderTarget.texture.format;
  21753. const count = renderTarget.textures.length;
  21754. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  21755. }
  21756. const chainMap = this._getChainMap( attachmentState );
  21757. let renderState = chainMap.get( _chainKeys$3 );
  21758. if ( renderState === undefined ) {
  21759. renderState = new RenderContext();
  21760. chainMap.set( _chainKeys$3, renderState );
  21761. }
  21762. _chainKeys$3.length = 0;
  21763. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21764. return renderState;
  21765. }
  21766. /**
  21767. * Returns a render context intended for clear operations.
  21768. *
  21769. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21770. * @return {RenderContext} The render context.
  21771. */
  21772. getForClear( renderTarget = null ) {
  21773. return this.get( _defaultScene, _defaultCamera, renderTarget );
  21774. }
  21775. /**
  21776. * Returns a chain map for the given attachment state.
  21777. *
  21778. * @private
  21779. * @param {string} attachmentState - The attachment state.
  21780. * @return {ChainMap} The chain map.
  21781. */
  21782. _getChainMap( attachmentState ) {
  21783. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  21784. }
  21785. /**
  21786. * Frees internal resources.
  21787. */
  21788. dispose() {
  21789. this.chainMaps = {};
  21790. }
  21791. }
  21792. const _size$3 = /*@__PURE__*/ new Vector3();
  21793. /**
  21794. * This module manages the textures of the renderer.
  21795. *
  21796. * @private
  21797. * @augments DataMap
  21798. */
  21799. class Textures extends DataMap {
  21800. /**
  21801. * Constructs a new texture management component.
  21802. *
  21803. * @param {Renderer} renderer - The renderer.
  21804. * @param {Backend} backend - The renderer's backend.
  21805. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21806. */
  21807. constructor( renderer, backend, info ) {
  21808. super();
  21809. /**
  21810. * The renderer.
  21811. *
  21812. * @type {Renderer}
  21813. */
  21814. this.renderer = renderer;
  21815. /**
  21816. * The backend.
  21817. *
  21818. * @type {Backend}
  21819. */
  21820. this.backend = backend;
  21821. /**
  21822. * Renderer component for managing metrics and monitoring data.
  21823. *
  21824. * @type {Info}
  21825. */
  21826. this.info = info;
  21827. }
  21828. /**
  21829. * Updates the given render target. Based on the given render target configuration,
  21830. * it updates the texture states representing the attachments of the framebuffer.
  21831. *
  21832. * @param {RenderTarget} renderTarget - The render target to update.
  21833. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  21834. */
  21835. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  21836. const renderTargetData = this.get( renderTarget );
  21837. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21838. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  21839. const textures = renderTarget.textures;
  21840. const size = this.getSize( textures[ 0 ] );
  21841. const mipWidth = size.width >> activeMipmapLevel;
  21842. const mipHeight = size.height >> activeMipmapLevel;
  21843. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  21844. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  21845. let textureNeedsUpdate = false;
  21846. if ( depthTexture === undefined && useDepthTexture ) {
  21847. depthTexture = new DepthTexture();
  21848. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  21849. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  21850. depthTexture.image.width = mipWidth;
  21851. depthTexture.image.height = mipHeight;
  21852. depthTexture.image.depth = size.depth;
  21853. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  21854. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  21855. }
  21856. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  21857. textureNeedsUpdate = true;
  21858. if ( depthTexture ) {
  21859. depthTexture.needsUpdate = true;
  21860. depthTexture.image.width = mipWidth;
  21861. depthTexture.image.height = mipHeight;
  21862. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  21863. }
  21864. }
  21865. renderTargetData.width = size.width;
  21866. renderTargetData.height = size.height;
  21867. renderTargetData.textures = textures;
  21868. renderTargetData.depthTexture = depthTexture || null;
  21869. renderTargetData.depth = renderTarget.depthBuffer;
  21870. renderTargetData.stencil = renderTarget.stencilBuffer;
  21871. renderTargetData.renderTarget = renderTarget;
  21872. if ( renderTargetData.sampleCount !== sampleCount ) {
  21873. textureNeedsUpdate = true;
  21874. if ( depthTexture ) {
  21875. depthTexture.needsUpdate = true;
  21876. }
  21877. renderTargetData.sampleCount = sampleCount;
  21878. }
  21879. //
  21880. const options = { sampleCount };
  21881. // XR render targets require no texture updates
  21882. if ( renderTarget.isXRRenderTarget !== true ) {
  21883. for ( let i = 0; i < textures.length; i ++ ) {
  21884. const texture = textures[ i ];
  21885. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  21886. this.updateTexture( texture, options );
  21887. }
  21888. if ( depthTexture ) {
  21889. this.updateTexture( depthTexture, options );
  21890. }
  21891. }
  21892. // dispose handler
  21893. if ( renderTargetData.initialized !== true ) {
  21894. renderTargetData.initialized = true;
  21895. // dispose
  21896. const onDispose = () => {
  21897. renderTarget.removeEventListener( 'dispose', onDispose );
  21898. for ( let i = 0; i < textures.length; i ++ ) {
  21899. this._destroyTexture( textures[ i ] );
  21900. }
  21901. if ( depthTexture ) {
  21902. this._destroyTexture( depthTexture );
  21903. }
  21904. this.delete( renderTarget );
  21905. this.backend.delete( renderTarget );
  21906. };
  21907. renderTarget.addEventListener( 'dispose', onDispose );
  21908. }
  21909. }
  21910. /**
  21911. * Updates the given texture. Depending on the texture state, this method
  21912. * triggers the upload of texture data to the GPU memory. If the texture data are
  21913. * not yet ready for the upload, it uses default texture data for as a placeholder.
  21914. *
  21915. * @param {Texture} texture - The texture to update.
  21916. * @param {Object} [options={}] - The options.
  21917. */
  21918. updateTexture( texture, options = {} ) {
  21919. const textureData = this.get( texture );
  21920. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  21921. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  21922. const backend = this.backend;
  21923. if ( isRenderTarget && textureData.initialized === true ) {
  21924. // it's an update
  21925. backend.destroySampler( texture );
  21926. backend.destroyTexture( texture );
  21927. }
  21928. //
  21929. if ( texture.isFramebufferTexture ) {
  21930. const renderTarget = this.renderer.getRenderTarget();
  21931. if ( renderTarget ) {
  21932. texture.type = renderTarget.texture.type;
  21933. } else {
  21934. texture.type = UnsignedByteType;
  21935. }
  21936. }
  21937. //
  21938. const { width, height, depth } = this.getSize( texture );
  21939. options.width = width;
  21940. options.height = height;
  21941. options.depth = depth;
  21942. options.needsMipmaps = this.needsMipmaps( texture );
  21943. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  21944. // TODO: Uniformly handle mipmap definitions
  21945. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  21946. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  21947. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  21948. //
  21949. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  21950. backend.createSampler( texture );
  21951. backend.createTexture( texture, options );
  21952. textureData.generation = texture.version;
  21953. } else {
  21954. const needsCreate = textureData.initialized !== true;
  21955. if ( needsCreate ) backend.createSampler( texture );
  21956. if ( texture.version > 0 ) {
  21957. const image = texture.image;
  21958. if ( image === undefined ) {
  21959. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  21960. } else if ( image.complete === false ) {
  21961. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  21962. } else {
  21963. if ( texture.images ) {
  21964. const images = [];
  21965. for ( const image of texture.images ) {
  21966. images.push( image );
  21967. }
  21968. options.images = images;
  21969. } else {
  21970. options.image = image;
  21971. }
  21972. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  21973. backend.createTexture( texture, options );
  21974. textureData.isDefaultTexture = false;
  21975. textureData.generation = texture.version;
  21976. }
  21977. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  21978. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  21979. }
  21980. } else {
  21981. // async update
  21982. backend.createDefaultTexture( texture );
  21983. textureData.isDefaultTexture = true;
  21984. textureData.generation = texture.version;
  21985. }
  21986. }
  21987. // dispose handler
  21988. if ( textureData.initialized !== true ) {
  21989. textureData.initialized = true;
  21990. textureData.generation = texture.version;
  21991. //
  21992. this.info.memory.textures ++;
  21993. //
  21994. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  21995. console.warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  21996. }
  21997. // dispose
  21998. const onDispose = () => {
  21999. texture.removeEventListener( 'dispose', onDispose );
  22000. this._destroyTexture( texture );
  22001. };
  22002. texture.addEventListener( 'dispose', onDispose );
  22003. }
  22004. //
  22005. textureData.version = texture.version;
  22006. }
  22007. /**
  22008. * Computes the size of the given texture and writes the result
  22009. * into the target vector. This vector is also returned by the
  22010. * method.
  22011. *
  22012. * If no texture data are available for the compute yet, the method
  22013. * returns default size values.
  22014. *
  22015. * @param {Texture} texture - The texture to compute the size for.
  22016. * @param {Vector3} target - The target vector.
  22017. * @return {Vector3} The target vector.
  22018. */
  22019. getSize( texture, target = _size$3 ) {
  22020. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22021. if ( image ) {
  22022. if ( image.image !== undefined ) image = image.image;
  22023. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22024. target.width = image.videoWidth || 1;
  22025. target.height = image.videoHeight || 1;
  22026. target.depth = 1;
  22027. } else if ( image instanceof VideoFrame ) {
  22028. target.width = image.displayWidth || 1;
  22029. target.height = image.displayHeight || 1;
  22030. target.depth = 1;
  22031. } else {
  22032. target.width = image.width || 1;
  22033. target.height = image.height || 1;
  22034. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22035. }
  22036. } else {
  22037. target.width = target.height = target.depth = 1;
  22038. }
  22039. return target;
  22040. }
  22041. /**
  22042. * Computes the number of mipmap levels for the given texture.
  22043. *
  22044. * @param {Texture} texture - The texture.
  22045. * @param {number} width - The texture's width.
  22046. * @param {number} height - The texture's height.
  22047. * @return {number} The number of mipmap levels.
  22048. */
  22049. getMipLevels( texture, width, height ) {
  22050. let mipLevelCount;
  22051. if ( texture.mipmaps.length > 0 ) {
  22052. mipLevelCount = texture.mipmaps.length;
  22053. } else {
  22054. if ( texture.isCompressedTexture === true ) {
  22055. // it is not possible to compute mipmaps for compressed textures. So
  22056. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22057. // level of 1
  22058. mipLevelCount = 1;
  22059. } else {
  22060. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22061. }
  22062. }
  22063. return mipLevelCount;
  22064. }
  22065. /**
  22066. * Returns `true` if the given texture makes use of mipmapping.
  22067. *
  22068. * @param {Texture} texture - The texture.
  22069. * @return {boolean} Whether mipmaps are required or not.
  22070. */
  22071. needsMipmaps( texture ) {
  22072. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  22073. }
  22074. /**
  22075. * Frees internal resource when the given texture isn't
  22076. * required anymore.
  22077. *
  22078. * @param {Texture} texture - The texture to destroy.
  22079. */
  22080. _destroyTexture( texture ) {
  22081. if ( this.has( texture ) === true ) {
  22082. this.backend.destroySampler( texture );
  22083. this.backend.destroyTexture( texture );
  22084. this.delete( texture );
  22085. this.info.memory.textures --;
  22086. }
  22087. }
  22088. }
  22089. /**
  22090. * A four-component version of {@link Color} which is internally
  22091. * used by the renderer to represents clear color with alpha as
  22092. * one object.
  22093. *
  22094. * @private
  22095. * @augments Color
  22096. */
  22097. class Color4 extends Color {
  22098. /**
  22099. * Constructs a new four-component color.
  22100. * You can also pass a single THREE.Color, hex or
  22101. * string argument to this constructor.
  22102. *
  22103. * @param {number|string} [r=1] - The red value.
  22104. * @param {number} [g=1] - The green value.
  22105. * @param {number} [b=1] - The blue value.
  22106. * @param {number} [a=1] - The alpha value.
  22107. */
  22108. constructor( r, g, b, a = 1 ) {
  22109. super( r, g, b );
  22110. this.a = a;
  22111. }
  22112. /**
  22113. * Overwrites the default to honor alpha.
  22114. * You can also pass a single THREE.Color, hex or
  22115. * string argument to this method.
  22116. *
  22117. * @param {number|string|Color} r - The red value.
  22118. * @param {number} [g] - The green value.
  22119. * @param {number} [b] - The blue value.
  22120. * @param {number} [a=1] - The alpha value.
  22121. * @return {Color4} A reference to this object.
  22122. */
  22123. set( r, g, b, a = 1 ) {
  22124. this.a = a;
  22125. return super.set( r, g, b );
  22126. }
  22127. /**
  22128. * Overwrites the default to honor alpha.
  22129. *
  22130. * @param {Color4} color - The color to copy.
  22131. * @return {Color4} A reference to this object.
  22132. */
  22133. copy( color ) {
  22134. if ( color.a !== undefined ) this.a = color.a;
  22135. return super.copy( color );
  22136. }
  22137. /**
  22138. * Overwrites the default to honor alpha.
  22139. *
  22140. * @return {Color4} The cloned color.
  22141. */
  22142. clone() {
  22143. return new this.constructor( this.r, this.g, this.b, this.a );
  22144. }
  22145. }
  22146. /**
  22147. * Special version of {@link PropertyNode} which is used for parameters.
  22148. *
  22149. * @augments PropertyNode
  22150. */
  22151. class ParameterNode extends PropertyNode {
  22152. static get type() {
  22153. return 'ParameterNode';
  22154. }
  22155. /**
  22156. * Constructs a new parameter node.
  22157. *
  22158. * @param {string} nodeType - The type of the node.
  22159. * @param {?string} [name=null] - The name of the parameter in the shader.
  22160. */
  22161. constructor( nodeType, name = null ) {
  22162. super( nodeType, name );
  22163. /**
  22164. * This flag can be used for type testing.
  22165. *
  22166. * @type {boolean}
  22167. * @readonly
  22168. * @default true
  22169. */
  22170. this.isParameterNode = true;
  22171. }
  22172. getHash() {
  22173. return this.uuid;
  22174. }
  22175. generate() {
  22176. return this.name;
  22177. }
  22178. }
  22179. /**
  22180. * TSL function for creating a parameter node.
  22181. *
  22182. * @tsl
  22183. * @function
  22184. * @param {string} type - The type of the node.
  22185. * @param {?string} name - The name of the parameter in the shader.
  22186. * @returns {ParameterNode}
  22187. */
  22188. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  22189. /**
  22190. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  22191. * They are usually needed in cases like `If`, `Else`.
  22192. *
  22193. * @augments Node
  22194. */
  22195. class StackNode extends Node {
  22196. static get type() {
  22197. return 'StackNode';
  22198. }
  22199. /**
  22200. * Constructs a new stack node.
  22201. *
  22202. * @param {?StackNode} [parent=null] - The parent stack node.
  22203. */
  22204. constructor( parent = null ) {
  22205. super();
  22206. /**
  22207. * List of nodes.
  22208. *
  22209. * @type {Array<Node>}
  22210. */
  22211. this.nodes = [];
  22212. /**
  22213. * The output node.
  22214. *
  22215. * @type {?Node}
  22216. * @default null
  22217. */
  22218. this.outputNode = null;
  22219. /**
  22220. * The parent stack node.
  22221. *
  22222. * @type {?StackNode}
  22223. * @default null
  22224. */
  22225. this.parent = parent;
  22226. /**
  22227. * The current conditional node.
  22228. *
  22229. * @private
  22230. * @type {ConditionalNode}
  22231. * @default null
  22232. */
  22233. this._currentCond = null;
  22234. /**
  22235. * The expression node. Only
  22236. * relevant for Switch/Case.
  22237. *
  22238. * @private
  22239. * @type {Node}
  22240. * @default null
  22241. */
  22242. this._expressionNode = null;
  22243. /**
  22244. * This flag can be used for type testing.
  22245. *
  22246. * @type {boolean}
  22247. * @readonly
  22248. * @default true
  22249. */
  22250. this.isStackNode = true;
  22251. }
  22252. getNodeType( builder ) {
  22253. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  22254. }
  22255. getMemberType( builder, name ) {
  22256. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  22257. }
  22258. /**
  22259. * Adds a node to this stack.
  22260. *
  22261. * @param {Node} node - The node to add.
  22262. * @return {StackNode} A reference to this stack node.
  22263. */
  22264. add( node ) {
  22265. if ( node.isNode !== true ) {
  22266. console.error( 'THREE.TSL: Invalid node added to stack.' );
  22267. return this;
  22268. }
  22269. this.nodes.push( node );
  22270. return this;
  22271. }
  22272. /**
  22273. * Represent an `if` statement in TSL.
  22274. *
  22275. * @param {Node} boolNode - Represents the condition.
  22276. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22277. * @return {StackNode} A reference to this stack node.
  22278. */
  22279. If( boolNode, method ) {
  22280. const methodNode = new ShaderNode( method );
  22281. this._currentCond = select( boolNode, methodNode );
  22282. return this.add( this._currentCond );
  22283. }
  22284. /**
  22285. * Represent an `elseif` statement in TSL.
  22286. *
  22287. * @param {Node} boolNode - Represents the condition.
  22288. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22289. * @return {StackNode} A reference to this stack node.
  22290. */
  22291. ElseIf( boolNode, method ) {
  22292. const methodNode = new ShaderNode( method );
  22293. const ifNode = select( boolNode, methodNode );
  22294. this._currentCond.elseNode = ifNode;
  22295. this._currentCond = ifNode;
  22296. return this;
  22297. }
  22298. /**
  22299. * Represent an `else` statement in TSL.
  22300. *
  22301. * @param {Function} method - TSL code which is executed in the `else` case.
  22302. * @return {StackNode} A reference to this stack node.
  22303. */
  22304. Else( method ) {
  22305. this._currentCond.elseNode = new ShaderNode( method );
  22306. return this;
  22307. }
  22308. /**
  22309. * Represents a `switch` statement in TSL.
  22310. *
  22311. * @param {any} expression - Represents the expression.
  22312. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22313. * @return {StackNode} A reference to this stack node.
  22314. */
  22315. Switch( expression ) {
  22316. this._expressionNode = nodeObject( expression );
  22317. return this;
  22318. }
  22319. /**
  22320. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22321. * The last parameter must be the callback method that should be executed in the `true` case.
  22322. *
  22323. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22324. * @return {StackNode} A reference to this stack node.
  22325. */
  22326. Case( ...params ) {
  22327. const caseNodes = [];
  22328. // extract case nodes from the parameter list
  22329. if ( params.length >= 2 ) {
  22330. for ( let i = 0; i < params.length - 1; i ++ ) {
  22331. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22332. }
  22333. } else {
  22334. console.error( 'THREE.TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22335. }
  22336. // extract method
  22337. const method = params[ params.length - 1 ];
  22338. const methodNode = new ShaderNode( method );
  22339. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22340. let caseNode = caseNodes[ 0 ];
  22341. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22342. caseNode = caseNode.or( caseNodes[ i ] );
  22343. }
  22344. // build condition
  22345. const condNode = select( caseNode, methodNode );
  22346. if ( this._currentCond === null ) {
  22347. this._currentCond = condNode;
  22348. return this.add( this._currentCond );
  22349. } else {
  22350. this._currentCond.elseNode = condNode;
  22351. this._currentCond = condNode;
  22352. return this;
  22353. }
  22354. }
  22355. /**
  22356. * Represents the default code block of a Switch/Case statement.
  22357. *
  22358. * @param {Function} method - TSL code which is executed in the `else` case.
  22359. * @return {StackNode} A reference to this stack node.
  22360. */
  22361. Default( method ) {
  22362. this.Else( method );
  22363. return this;
  22364. }
  22365. setup( builder ) {
  22366. const nodeProperties = builder.getNodeProperties( this );
  22367. let index = 0;
  22368. for ( const childNode of this.getChildren() ) {
  22369. if ( childNode.isVarNode && childNode.intent === true ) {
  22370. const properties = builder.getNodeProperties( childNode );
  22371. if ( properties.assign !== true ) {
  22372. continue;
  22373. }
  22374. }
  22375. nodeProperties[ 'node' + index ++ ] = childNode;
  22376. }
  22377. // return a outputNode if exists or null
  22378. return nodeProperties.outputNode || null;
  22379. }
  22380. get hasOutput() {
  22381. return this.outputNode && this.outputNode.isNode;
  22382. }
  22383. build( builder, ...params ) {
  22384. const previousBuildStack = builder.currentStack;
  22385. const previousStack = getCurrentStack();
  22386. setCurrentStack( this );
  22387. builder.currentStack = this;
  22388. const buildStage = builder.buildStage;
  22389. for ( const node of this.nodes ) {
  22390. if ( node.isVarNode && node.intent === true ) {
  22391. const properties = builder.getNodeProperties( node );
  22392. if ( properties.assign !== true ) {
  22393. continue;
  22394. }
  22395. }
  22396. if ( buildStage === 'setup' ) {
  22397. node.build( builder );
  22398. } else if ( buildStage === 'analyze' ) {
  22399. node.build( builder, this );
  22400. } else if ( buildStage === 'generate' ) {
  22401. const stages = builder.getDataFromNode( node, 'any' ).stages;
  22402. const parents = stages && stages[ builder.shaderStage ];
  22403. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  22404. continue; // skip var nodes that are only used in .toVarying()
  22405. }
  22406. node.build( builder, 'void' );
  22407. }
  22408. }
  22409. //
  22410. let result;
  22411. if ( this.hasOutput ) {
  22412. result = this.outputNode.build( builder, ...params );
  22413. } else {
  22414. result = super.build( builder, ...params );
  22415. }
  22416. setCurrentStack( previousStack );
  22417. builder.currentStack = previousBuildStack;
  22418. return result;
  22419. }
  22420. }
  22421. /**
  22422. * TSL function for creating a stack node.
  22423. *
  22424. * @tsl
  22425. * @function
  22426. * @param {?StackNode} [parent=null] - The parent stack node.
  22427. * @returns {StackNode}
  22428. */
  22429. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  22430. /**
  22431. * Generates a layout for struct members.
  22432. * This function takes an object representing struct members and returns an array of member layouts.
  22433. * Each member layout includes the member's name, type, and whether it is atomic.
  22434. *
  22435. * @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.
  22436. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  22437. */
  22438. function getMembersLayout( members ) {
  22439. return Object.entries( members ).map( ( [ name, value ] ) => {
  22440. if ( typeof value === 'string' ) {
  22441. return { name, type: value, atomic: false };
  22442. }
  22443. return { name, type: value.type, atomic: value.atomic || false };
  22444. } );
  22445. }
  22446. /**
  22447. * Represents a struct type node in the node-based system.
  22448. * This class is used to define and manage the layout and types of struct members.
  22449. * It extends the base Node class and provides methods to get the length of the struct,
  22450. * retrieve member types, and generate the struct type for a builder.
  22451. *
  22452. * @augments Node
  22453. */
  22454. class StructTypeNode extends Node {
  22455. static get type() {
  22456. return 'StructTypeNode';
  22457. }
  22458. /**
  22459. * Creates an instance of StructTypeNode.
  22460. *
  22461. * @param {Object} membersLayout - The layout of the members for the struct.
  22462. * @param {?string} [name=null] - The optional name of the struct.
  22463. */
  22464. constructor( membersLayout, name = null ) {
  22465. super( 'struct' );
  22466. /**
  22467. * The layout of the members for the struct
  22468. *
  22469. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  22470. */
  22471. this.membersLayout = getMembersLayout( membersLayout );
  22472. /**
  22473. * The name of the struct.
  22474. *
  22475. * @type {?string}
  22476. * @default null
  22477. */
  22478. this.name = name;
  22479. /**
  22480. * This flag can be used for type testing.
  22481. *
  22482. * @type {boolean}
  22483. * @readonly
  22484. * @default true
  22485. */
  22486. this.isStructLayoutNode = true;
  22487. }
  22488. /**
  22489. * Returns the length of the struct.
  22490. * The length is calculated by summing the lengths of the struct's members.
  22491. *
  22492. * @returns {number} The length of the struct.
  22493. */
  22494. getLength() {
  22495. const GPU_CHUNK_BYTES = 8;
  22496. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  22497. let offset = 0; // global buffer offset in bytes
  22498. for ( const member of this.membersLayout ) {
  22499. const type = member.type;
  22500. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  22501. const boundary = getByteBoundaryFromType( type );
  22502. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  22503. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  22504. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  22505. offset += chunkPadding;
  22506. // Check for chunk overflow
  22507. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  22508. // Add padding to the end of the chunk
  22509. offset += ( GPU_CHUNK_BYTES - chunkStart );
  22510. }
  22511. offset += itemSize;
  22512. }
  22513. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  22514. }
  22515. getMemberType( builder, name ) {
  22516. const member = this.membersLayout.find( m => m.name === name );
  22517. return member ? member.type : 'void';
  22518. }
  22519. getNodeType( builder ) {
  22520. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22521. return structType.name;
  22522. }
  22523. setup( builder ) {
  22524. builder.addInclude( this );
  22525. }
  22526. generate( builder ) {
  22527. return this.getNodeType( builder );
  22528. }
  22529. }
  22530. /**
  22531. * StructNode allows to create custom structures with multiple members.
  22532. * This can also be used to define structures in attribute and uniform data.
  22533. *
  22534. * ```js
  22535. * // Define a custom struct
  22536. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  22537. *
  22538. * // Create a new instance of the struct
  22539. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  22540. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  22541. *
  22542. * // Access the struct members
  22543. * const min = bb.get( 'min' );
  22544. *
  22545. * // Assign a new value to a member
  22546. * min.assign( vec3() );
  22547. * ```
  22548. * @augments Node
  22549. */
  22550. class StructNode extends Node {
  22551. static get type() {
  22552. return 'StructNode';
  22553. }
  22554. constructor( structLayoutNode, values ) {
  22555. super( 'vec3' );
  22556. this.structLayoutNode = structLayoutNode;
  22557. this.values = values;
  22558. this.isStructNode = true;
  22559. }
  22560. getNodeType( builder ) {
  22561. return this.structLayoutNode.getNodeType( builder );
  22562. }
  22563. getMemberType( builder, name ) {
  22564. return this.structLayoutNode.getMemberType( builder, name );
  22565. }
  22566. generate( builder ) {
  22567. const nodeVar = builder.getVarFromNode( this );
  22568. const structType = nodeVar.type;
  22569. const propertyName = builder.getPropertyName( nodeVar );
  22570. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  22571. return nodeVar.name;
  22572. }
  22573. }
  22574. /**
  22575. * TSL function for creating a struct node.
  22576. *
  22577. * @tsl
  22578. * @function
  22579. * @param {Object} membersLayout - The layout of the struct members.
  22580. * @param {?string} [name=null] - The name of the struct.
  22581. * @returns {Function} The struct function.
  22582. */
  22583. const struct = ( membersLayout, name = null ) => {
  22584. const structLayout = new StructTypeNode( membersLayout, name );
  22585. const struct = ( ...params ) => {
  22586. let values = null;
  22587. if ( params.length > 0 ) {
  22588. if ( params[ 0 ].isNode ) {
  22589. values = {};
  22590. const names = Object.keys( membersLayout );
  22591. for ( let i = 0; i < params.length; i ++ ) {
  22592. values[ names[ i ] ] = params[ i ];
  22593. }
  22594. } else {
  22595. values = params[ 0 ];
  22596. }
  22597. }
  22598. return nodeObject( new StructNode( structLayout, values ) );
  22599. };
  22600. struct.layout = structLayout;
  22601. struct.isStruct = true;
  22602. return struct;
  22603. };
  22604. /**
  22605. * This node can be used to define multiple outputs in a shader programs.
  22606. *
  22607. * @augments Node
  22608. */
  22609. class OutputStructNode extends Node {
  22610. static get type() {
  22611. return 'OutputStructNode';
  22612. }
  22613. /**
  22614. * Constructs a new output struct node. The constructor can be invoked with an
  22615. * arbitrary number of nodes representing the members.
  22616. *
  22617. * @param {...Node} members - A parameter list of nodes.
  22618. */
  22619. constructor( ...members ) {
  22620. super();
  22621. /**
  22622. * An array of nodes which defines the output.
  22623. *
  22624. * @type {Array<Node>}
  22625. */
  22626. this.members = members;
  22627. /**
  22628. * This flag can be used for type testing.
  22629. *
  22630. * @type {boolean}
  22631. * @readonly
  22632. * @default true
  22633. */
  22634. this.isOutputStructNode = true;
  22635. }
  22636. getNodeType( builder ) {
  22637. const properties = builder.getNodeProperties( this );
  22638. if ( properties.membersLayout === undefined ) {
  22639. const members = this.members;
  22640. const membersLayout = [];
  22641. for ( let i = 0; i < members.length; i ++ ) {
  22642. const name = 'm' + i;
  22643. const type = members[ i ].getNodeType( builder );
  22644. membersLayout.push( { name, type, index: i } );
  22645. }
  22646. properties.membersLayout = membersLayout;
  22647. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  22648. }
  22649. return properties.structType.name;
  22650. }
  22651. generate( builder ) {
  22652. const propertyName = builder.getOutputStructName();
  22653. const members = this.members;
  22654. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  22655. for ( let i = 0; i < members.length; i ++ ) {
  22656. const snippet = members[ i ].build( builder );
  22657. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  22658. }
  22659. return propertyName;
  22660. }
  22661. }
  22662. /**
  22663. * TSL function for creating an output struct node.
  22664. *
  22665. * @tsl
  22666. * @function
  22667. * @param {...Node} members - A parameter list of nodes.
  22668. * @returns {OutputStructNode}
  22669. */
  22670. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  22671. /**
  22672. * Returns the MRT texture index for the given name.
  22673. *
  22674. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  22675. * @param {string} name - The name of the MRT texture which index is requested.
  22676. * @return {number} The texture index.
  22677. */
  22678. function getTextureIndex( textures, name ) {
  22679. for ( let i = 0; i < textures.length; i ++ ) {
  22680. if ( textures[ i ].name === name ) {
  22681. return i;
  22682. }
  22683. }
  22684. return -1;
  22685. }
  22686. /**
  22687. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  22688. * post-processing is shown below:
  22689. * ```js
  22690. * const mrtNode = mrt( {
  22691. * output: output,
  22692. * normal: normalView
  22693. * } ) );
  22694. * ```
  22695. * The MRT output is defined as a dictionary.
  22696. *
  22697. * @augments OutputStructNode
  22698. */
  22699. class MRTNode extends OutputStructNode {
  22700. static get type() {
  22701. return 'MRTNode';
  22702. }
  22703. /**
  22704. * Constructs a new output struct node.
  22705. *
  22706. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22707. */
  22708. constructor( outputNodes ) {
  22709. super();
  22710. /**
  22711. * A dictionary representing the MRT outputs. The key
  22712. * is the name of the output, the value the node which produces
  22713. * the output result.
  22714. *
  22715. * @type {Object<string, Node>}
  22716. */
  22717. this.outputNodes = outputNodes;
  22718. /**
  22719. * This flag can be used for type testing.
  22720. *
  22721. * @type {boolean}
  22722. * @readonly
  22723. * @default true
  22724. */
  22725. this.isMRTNode = true;
  22726. }
  22727. /**
  22728. * Returns `true` if the MRT node has an output with the given name.
  22729. *
  22730. * @param {string} name - The name of the output.
  22731. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  22732. */
  22733. has( name ) {
  22734. return this.outputNodes[ name ] !== undefined;
  22735. }
  22736. /**
  22737. * Returns the output node for the given name.
  22738. *
  22739. * @param {string} name - The name of the output.
  22740. * @return {Node} The output node.
  22741. */
  22742. get( name ) {
  22743. return this.outputNodes[ name ];
  22744. }
  22745. /**
  22746. * Merges the outputs of the given MRT node with the outputs of this node.
  22747. *
  22748. * @param {MRTNode} mrtNode - The MRT to merge.
  22749. * @return {MRTNode} A new MRT node with merged outputs..
  22750. */
  22751. merge( mrtNode ) {
  22752. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  22753. return mrt( outputs );
  22754. }
  22755. setup( builder ) {
  22756. const outputNodes = this.outputNodes;
  22757. const mrt = builder.renderer.getRenderTarget();
  22758. const members = [];
  22759. const textures = mrt.textures;
  22760. for ( const name in outputNodes ) {
  22761. const index = getTextureIndex( textures, name );
  22762. members[ index ] = vec4( outputNodes[ name ] );
  22763. }
  22764. this.members = members;
  22765. return super.setup( builder );
  22766. }
  22767. }
  22768. /**
  22769. * TSL function for creating a MRT node.
  22770. *
  22771. * @tsl
  22772. * @function
  22773. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22774. * @returns {MRTNode}
  22775. */
  22776. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  22777. /**
  22778. * Generates a hash value in the range `[0, 1]` from the given seed.
  22779. *
  22780. * @tsl
  22781. * @function
  22782. * @param {Node<float>} seed - The seed.
  22783. * @return {Node<float>} The hash value.
  22784. */
  22785. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  22786. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  22787. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  22788. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  22789. const result = word.shiftRight( 22 ).bitXor( word );
  22790. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  22791. } );
  22792. /**
  22793. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22794. * The corners are mapped to `0` and the center to `1`.
  22795. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22796. *
  22797. * @tsl
  22798. * @function
  22799. * @param {Node<float>} x - The value to remap.
  22800. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  22801. * @return {Node<float>} The remapped value.
  22802. */
  22803. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  22804. /**
  22805. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22806. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  22807. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22808. *
  22809. * @tsl
  22810. * @function
  22811. * @param {Node<float>} x - The value to remap.
  22812. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  22813. * @return {Node<float>} The remapped value.
  22814. */
  22815. 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 ) );
  22816. /**
  22817. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22818. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  22819. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22820. *
  22821. * @tsl
  22822. * @function
  22823. * @param {Node<float>} x - The value to remap.
  22824. * @param {Node<float>} a - First control parameter.
  22825. * @param {Node<float>} b - Second control parameter.
  22826. * @return {Node<float>} The remapped value.
  22827. */
  22828. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  22829. /**
  22830. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  22831. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22832. *
  22833. * @tsl
  22834. * @function
  22835. * @param {Node<float>} x - The value to compute the sin for.
  22836. * @param {Node<float>} k - Controls the amount of bounces.
  22837. * @return {Node<float>} The result value.
  22838. */
  22839. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  22840. // https://github.com/cabbibo/glsl-tri-noise-3d
  22841. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  22842. return x.fract().sub( .5 ).abs();
  22843. } ).setLayout( {
  22844. name: 'tri',
  22845. type: 'float',
  22846. inputs: [
  22847. { name: 'x', type: 'float' }
  22848. ]
  22849. } );
  22850. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  22851. 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. ) ) ) ) );
  22852. } ).setLayout( {
  22853. name: 'tri3',
  22854. type: 'vec3',
  22855. inputs: [
  22856. { name: 'p', type: 'vec3' }
  22857. ]
  22858. } );
  22859. /**
  22860. * Generates a noise value from the given position, speed and time parameters.
  22861. *
  22862. * @tsl
  22863. * @function
  22864. * @param {Node<vec3>} position - The position.
  22865. * @param {Node<float>} speed - The speed.
  22866. * @param {Node<float>} time - The time.
  22867. * @return {Node<float>} The generated noise.
  22868. */
  22869. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  22870. const p = vec3( position ).toVar();
  22871. const z = float( 1.4 ).toVar();
  22872. const rz = float( 0.0 ).toVar();
  22873. const bp = vec3( p ).toVar();
  22874. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  22875. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  22876. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  22877. bp.mulAssign( 1.8 );
  22878. z.mulAssign( 1.5 );
  22879. p.mulAssign( 1.2 );
  22880. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  22881. rz.addAssign( t.div( z ) );
  22882. bp.addAssign( 0.14 );
  22883. } );
  22884. return rz;
  22885. } ).setLayout( {
  22886. name: 'triNoise3D',
  22887. type: 'float',
  22888. inputs: [
  22889. { name: 'position', type: 'vec3' },
  22890. { name: 'speed', type: 'float' },
  22891. { name: 'time', type: 'float' }
  22892. ]
  22893. } );
  22894. /**
  22895. * This class allows to define multiple overloaded versions
  22896. * of the same function. Depending on the parameters of the function
  22897. * call, the node picks the best-fit overloaded version.
  22898. *
  22899. * @augments Node
  22900. */
  22901. class FunctionOverloadingNode extends Node {
  22902. static get type() {
  22903. return 'FunctionOverloadingNode';
  22904. }
  22905. /**
  22906. * Constructs a new function overloading node.
  22907. *
  22908. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22909. * @param {...Node} parametersNodes - A list of parameter nodes.
  22910. */
  22911. constructor( functionNodes = [], ...parametersNodes ) {
  22912. super();
  22913. /**
  22914. * Array of `Fn` function definitions.
  22915. *
  22916. * @type {Array<Function>}
  22917. */
  22918. this.functionNodes = functionNodes;
  22919. /**
  22920. * A list of parameter nodes.
  22921. *
  22922. * @type {Array<Node>}
  22923. */
  22924. this.parametersNodes = parametersNodes;
  22925. /**
  22926. * The selected overloaded function call.
  22927. *
  22928. * @private
  22929. * @type {ShaderCallNodeInternal}
  22930. */
  22931. this._candidateFnCall = null;
  22932. /**
  22933. * This node is marked as global.
  22934. *
  22935. * @type {boolean}
  22936. * @default true
  22937. */
  22938. this.global = true;
  22939. }
  22940. /**
  22941. * This method is overwritten since the node type is inferred from
  22942. * the function's return type.
  22943. *
  22944. * @param {NodeBuilder} builder - The current node builder.
  22945. * @return {string} The node type.
  22946. */
  22947. getNodeType() {
  22948. return this.functionNodes[ 0 ].shaderNode.layout.type;
  22949. }
  22950. setup( builder ) {
  22951. const params = this.parametersNodes;
  22952. let candidateFnCall = this._candidateFnCall;
  22953. if ( candidateFnCall === null ) {
  22954. let candidateFn = null;
  22955. let candidateScore = -1;
  22956. for ( const functionNode of this.functionNodes ) {
  22957. const shaderNode = functionNode.shaderNode;
  22958. const layout = shaderNode.layout;
  22959. if ( layout === null ) {
  22960. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  22961. }
  22962. const inputs = layout.inputs;
  22963. if ( params.length === inputs.length ) {
  22964. let score = 0;
  22965. for ( let i = 0; i < params.length; i ++ ) {
  22966. const param = params[ i ];
  22967. const input = inputs[ i ];
  22968. if ( param.getNodeType( builder ) === input.type ) {
  22969. score ++;
  22970. } else {
  22971. score = 0;
  22972. }
  22973. }
  22974. if ( score > candidateScore ) {
  22975. candidateFn = functionNode;
  22976. candidateScore = score;
  22977. }
  22978. }
  22979. }
  22980. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  22981. }
  22982. return candidateFnCall;
  22983. }
  22984. }
  22985. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  22986. /**
  22987. * TSL function for creating a function overloading node.
  22988. *
  22989. * @tsl
  22990. * @function
  22991. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22992. * @returns {FunctionOverloadingNode}
  22993. */
  22994. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  22995. /**
  22996. * Represents the elapsed time in seconds.
  22997. *
  22998. * @tsl
  22999. * @type {UniformNode<float>}
  23000. */
  23001. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  23002. /**
  23003. * Represents the delta time in seconds.
  23004. *
  23005. * @tsl
  23006. * @type {UniformNode<float>}
  23007. */
  23008. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  23009. /**
  23010. * Represents the current frame ID.
  23011. *
  23012. * @tsl
  23013. * @type {UniformNode<uint>}
  23014. */
  23015. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  23016. /**
  23017. * Generates a sine 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 oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  23025. /**
  23026. * Generates a square 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 oscSquare = ( t = time ) => t.fract().round();
  23034. /**
  23035. * Generates a triangle 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 oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  23043. /**
  23044. * Generates a sawtooth wave oscillation based on a timer.
  23045. *
  23046. * @tsl
  23047. * @function
  23048. * @param {Node<float>} t - The timer to generate the oscillation with.
  23049. * @return {Node<float>} The oscillation node.
  23050. */
  23051. const oscSawtooth = ( t = time ) => t.fract();
  23052. /**
  23053. * Rotates the given uv coordinates around a center point
  23054. *
  23055. * @tsl
  23056. * @function
  23057. * @param {Node<vec2>} uv - The uv coordinates.
  23058. * @param {Node<float>} rotation - The rotation defined in radians.
  23059. * @param {Node<vec2>} center - The center of rotation
  23060. * @return {Node<vec2>} The rotated uv coordinates.
  23061. */
  23062. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  23063. return rotate( uv.sub( center ), rotation ).add( center );
  23064. } );
  23065. /**
  23066. * Applies a spherical warping effect to the given uv coordinates.
  23067. *
  23068. * @tsl
  23069. * @function
  23070. * @param {Node<vec2>} uv - The uv coordinates.
  23071. * @param {Node<float>} strength - The strength of the effect.
  23072. * @param {Node<vec2>} center - The center point
  23073. * @return {Node<vec2>} The updated uv coordinates.
  23074. */
  23075. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  23076. const delta = uv.sub( center );
  23077. const delta2 = delta.dot( delta );
  23078. const delta4 = delta2.mul( delta2 );
  23079. const deltaOffset = delta4.mul( strength );
  23080. return uv.add( delta.mul( deltaOffset ) );
  23081. } );
  23082. /**
  23083. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  23084. * oriented always towards the camera.
  23085. *
  23086. * ```js
  23087. * material.vertexNode = billboarding();
  23088. * ```
  23089. *
  23090. * @tsl
  23091. * @function
  23092. * @param {Object} config - The configuration object.
  23093. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  23094. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  23095. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  23096. * @return {Node<vec3>} The updated vertex position in clip space.
  23097. */
  23098. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  23099. let worldMatrix;
  23100. if ( position !== null ) {
  23101. worldMatrix = modelWorldMatrix.toVar();
  23102. worldMatrix[ 3 ][ 0 ] = position.x;
  23103. worldMatrix[ 3 ][ 1 ] = position.y;
  23104. worldMatrix[ 3 ][ 2 ] = position.z;
  23105. } else {
  23106. worldMatrix = modelWorldMatrix;
  23107. }
  23108. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  23109. if ( defined( horizontal ) ) {
  23110. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  23111. modelViewMatrix[ 0 ][ 1 ] = 0;
  23112. modelViewMatrix[ 0 ][ 2 ] = 0;
  23113. }
  23114. if ( defined( vertical ) ) {
  23115. modelViewMatrix[ 1 ][ 0 ] = 0;
  23116. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  23117. modelViewMatrix[ 1 ][ 2 ] = 0;
  23118. }
  23119. modelViewMatrix[ 2 ][ 0 ] = 0;
  23120. modelViewMatrix[ 2 ][ 1 ] = 0;
  23121. modelViewMatrix[ 2 ][ 2 ] = 1;
  23122. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23123. } );
  23124. /**
  23125. * A special version of a screen uv function that involves a depth comparison
  23126. * when computing the final uvs. The function mitigates visual errors when
  23127. * using viewport texture nodes for refraction purposes. Without this function
  23128. * objects in front of a refractive surface might appear on the refractive surface
  23129. * which is incorrect.
  23130. *
  23131. * @tsl
  23132. * @function
  23133. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  23134. * @return {Node<vec2>} The update uv coordinates.
  23135. */
  23136. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  23137. const depth = linearDepth();
  23138. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  23139. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  23140. return finalUV;
  23141. } );
  23142. /**
  23143. * Can be used to compute texture coordinates for animated sprite sheets.
  23144. *
  23145. * ```js
  23146. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  23147. *
  23148. * material.colorNode = texture( spriteSheet, uvNode );
  23149. * ```
  23150. *
  23151. * @augments Node
  23152. */
  23153. class SpriteSheetUVNode extends Node {
  23154. static get type() {
  23155. return 'SpriteSheetUVNode';
  23156. }
  23157. /**
  23158. * Constructs a new sprite sheet uv node.
  23159. *
  23160. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23161. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  23162. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23163. */
  23164. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  23165. super( 'vec2' );
  23166. /**
  23167. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23168. *
  23169. * @type {Node<vec2>}
  23170. */
  23171. this.countNode = countNode;
  23172. /**
  23173. * The uv node.
  23174. *
  23175. * @type {Node<vec2>}
  23176. */
  23177. this.uvNode = uvNode;
  23178. /**
  23179. * The node that defines the current frame/sprite.
  23180. *
  23181. * @type {Node<float>}
  23182. */
  23183. this.frameNode = frameNode;
  23184. }
  23185. setup() {
  23186. const { frameNode, uvNode, countNode } = this;
  23187. const { width, height } = countNode;
  23188. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  23189. const column = frameNum.mod( width );
  23190. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  23191. const scale = countNode.reciprocal();
  23192. const uvFrameOffset = vec2( column, row );
  23193. return uvNode.add( uvFrameOffset ).mul( scale );
  23194. }
  23195. }
  23196. /**
  23197. * TSL function for creating a sprite sheet uv node.
  23198. *
  23199. * @tsl
  23200. * @function
  23201. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23202. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  23203. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23204. * @returns {SpriteSheetUVNode}
  23205. */
  23206. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  23207. /**
  23208. * TSL function for creating a triplanar textures node.
  23209. *
  23210. * Can be used for triplanar texture mapping.
  23211. *
  23212. * ```js
  23213. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  23214. * ```
  23215. *
  23216. * @tsl
  23217. * @function
  23218. * @param {Node} textureXNode - First texture node.
  23219. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23220. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23221. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23222. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23223. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23224. * @returns {Node<vec4>}
  23225. */
  23226. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  23227. // Reference: https://github.com/keijiro/StandardTriplanar
  23228. // Blending factor of triplanar mapping
  23229. let bf = normalNode.abs().normalize();
  23230. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  23231. // Triplanar mapping
  23232. const tx = positionNode.yz.mul( scaleNode );
  23233. const ty = positionNode.zx.mul( scaleNode );
  23234. const tz = positionNode.xy.mul( scaleNode );
  23235. // Base color
  23236. const textureX = textureXNode.value;
  23237. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  23238. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  23239. const cx = texture( textureX, tx ).mul( bf.x );
  23240. const cy = texture( textureY, ty ).mul( bf.y );
  23241. const cz = texture( textureZ, tz ).mul( bf.z );
  23242. return add( cx, cy, cz );
  23243. } );
  23244. /**
  23245. * TSL function for creating a triplanar textures node.
  23246. *
  23247. * @tsl
  23248. * @function
  23249. * @param {Node} textureXNode - First texture node.
  23250. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23251. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23252. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23253. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23254. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23255. * @returns {Node<vec4>}
  23256. */
  23257. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  23258. const _reflectorPlane = new Plane();
  23259. const _normal = new Vector3();
  23260. const _reflectorWorldPosition = new Vector3();
  23261. const _cameraWorldPosition = new Vector3();
  23262. const _rotationMatrix = new Matrix4();
  23263. const _lookAtPosition = new Vector3( 0, 0, -1 );
  23264. const clipPlane = new Vector4();
  23265. const _view = new Vector3();
  23266. const _target = new Vector3();
  23267. const _q = new Vector4();
  23268. const _size$2 = new Vector2();
  23269. const _defaultRT = new RenderTarget();
  23270. const _defaultUV = screenUV.flipX();
  23271. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  23272. let _inReflector = false;
  23273. /**
  23274. * This node can be used to implement mirror-like flat reflective surfaces.
  23275. *
  23276. * ```js
  23277. * const groundReflector = reflector();
  23278. * material.colorNode = groundReflector;
  23279. *
  23280. * const plane = new Mesh( geometry, material );
  23281. * plane.add( groundReflector.target );
  23282. * ```
  23283. *
  23284. * @augments TextureNode
  23285. */
  23286. class ReflectorNode extends TextureNode {
  23287. static get type() {
  23288. return 'ReflectorNode';
  23289. }
  23290. /**
  23291. * Constructs a new reflector node.
  23292. *
  23293. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23294. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23295. * @param {number} [parameters.resolution=1] - The resolution scale.
  23296. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23297. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23298. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23299. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23300. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23301. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23302. */
  23303. constructor( parameters = {} ) {
  23304. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  23305. /**
  23306. * A reference to the internal reflector base node which holds the actual implementation.
  23307. *
  23308. * @private
  23309. * @type {ReflectorBaseNode}
  23310. * @default ReflectorBaseNode
  23311. */
  23312. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  23313. /**
  23314. * A reference to the internal depth node.
  23315. *
  23316. * @private
  23317. * @type {?Node}
  23318. * @default null
  23319. */
  23320. this._depthNode = null;
  23321. this.setUpdateMatrix( false );
  23322. }
  23323. /**
  23324. * A reference to the internal reflector node.
  23325. *
  23326. * @type {ReflectorBaseNode}
  23327. */
  23328. get reflector() {
  23329. return this._reflectorBaseNode;
  23330. }
  23331. /**
  23332. * A reference to 3D object the reflector is linked to.
  23333. *
  23334. * @type {Object3D}
  23335. */
  23336. get target() {
  23337. return this._reflectorBaseNode.target;
  23338. }
  23339. /**
  23340. * Returns a node representing the mirror's depth. That can be used
  23341. * to implement more advanced reflection effects like distance attenuation.
  23342. *
  23343. * @return {Node} The depth node.
  23344. */
  23345. getDepthNode() {
  23346. if ( this._depthNode === null ) {
  23347. if ( this._reflectorBaseNode.depth !== true ) {
  23348. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  23349. }
  23350. this._depthNode = nodeObject( new ReflectorNode( {
  23351. defaultTexture: _defaultRT.depthTexture,
  23352. reflector: this._reflectorBaseNode
  23353. } ) );
  23354. }
  23355. return this._depthNode;
  23356. }
  23357. setup( builder ) {
  23358. // ignore if used in post-processing
  23359. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  23360. return super.setup( builder );
  23361. }
  23362. clone() {
  23363. const newNode = new this.constructor( this.reflectorNode );
  23364. newNode.uvNode = this.uvNode;
  23365. newNode.levelNode = this.levelNode;
  23366. newNode.biasNode = this.biasNode;
  23367. newNode.sampler = this.sampler;
  23368. newNode.depthNode = this.depthNode;
  23369. newNode.compareNode = this.compareNode;
  23370. newNode.gradNode = this.gradNode;
  23371. newNode._reflectorBaseNode = this._reflectorBaseNode;
  23372. return newNode;
  23373. }
  23374. /**
  23375. * Frees internal resources. Should be called when the node is no longer in use.
  23376. */
  23377. dispose() {
  23378. super.dispose();
  23379. this._reflectorBaseNode.dispose();
  23380. }
  23381. }
  23382. /**
  23383. * Holds the actual implementation of the reflector.
  23384. *
  23385. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  23386. * in `ReflectorNode`, see #29619.
  23387. *
  23388. * @private
  23389. * @augments Node
  23390. */
  23391. class ReflectorBaseNode extends Node {
  23392. static get type() {
  23393. return 'ReflectorBaseNode';
  23394. }
  23395. /**
  23396. * Constructs a new reflector base node.
  23397. *
  23398. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  23399. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23400. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23401. * @param {number} [parameters.resolution=1] - The resolution scale.
  23402. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23403. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23404. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23405. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23406. */
  23407. constructor( textureNode, parameters = {} ) {
  23408. super();
  23409. const {
  23410. target = new Object3D(),
  23411. resolution = 1,
  23412. generateMipmaps = false,
  23413. bounces = true,
  23414. depth = false,
  23415. samples = 0
  23416. } = parameters;
  23417. /**
  23418. * Represents the rendered reflections as a texture node.
  23419. *
  23420. * @type {TextureNode}
  23421. */
  23422. this.textureNode = textureNode;
  23423. /**
  23424. * The 3D object the reflector is linked to.
  23425. *
  23426. * @type {Object3D}
  23427. * @default {new Object3D()}
  23428. */
  23429. this.target = target;
  23430. /**
  23431. * The resolution scale.
  23432. *
  23433. * @type {number}
  23434. * @default {1}
  23435. */
  23436. this.resolution = resolution;
  23437. /**
  23438. * Whether mipmaps should be generated or not.
  23439. *
  23440. * @type {boolean}
  23441. * @default {false}
  23442. */
  23443. this.generateMipmaps = generateMipmaps;
  23444. /**
  23445. * Whether reflectors can render other reflector nodes or not.
  23446. *
  23447. * @type {boolean}
  23448. * @default {true}
  23449. */
  23450. this.bounces = bounces;
  23451. /**
  23452. * Whether depth data should be generated or not.
  23453. *
  23454. * @type {boolean}
  23455. * @default {false}
  23456. */
  23457. this.depth = depth;
  23458. /**
  23459. * The number of anti-aliasing samples for the render-target
  23460. *
  23461. * @type {number}
  23462. * @default {0}
  23463. */
  23464. this.samples = samples;
  23465. /**
  23466. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  23467. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  23468. *
  23469. * @type {string}
  23470. * @default 'render'
  23471. */
  23472. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  23473. /**
  23474. * Weak map for managing virtual cameras.
  23475. *
  23476. * @type {WeakMap<Camera, Camera>}
  23477. */
  23478. this.virtualCameras = new WeakMap();
  23479. /**
  23480. * Weak map for managing render targets.
  23481. *
  23482. * @type {Map<Camera, RenderTarget>}
  23483. */
  23484. this.renderTargets = new Map();
  23485. /**
  23486. * Force render even if reflector is facing away from camera.
  23487. *
  23488. * @type {boolean}
  23489. * @default {false}
  23490. */
  23491. this.forceUpdate = false;
  23492. /**
  23493. * Whether the reflector has been rendered or not.
  23494. *
  23495. * When the reflector is facing away from the camera,
  23496. * this flag is set to `false` and the texture will be empty(black).
  23497. *
  23498. * @type {boolean}
  23499. * @default {false}
  23500. */
  23501. this.hasOutput = false;
  23502. }
  23503. /**
  23504. * Updates the resolution of the internal render target.
  23505. *
  23506. * @private
  23507. * @param {RenderTarget} renderTarget - The render target to resize.
  23508. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  23509. */
  23510. _updateResolution( renderTarget, renderer ) {
  23511. const resolution = this.resolution;
  23512. renderer.getDrawingBufferSize( _size$2 );
  23513. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  23514. }
  23515. setup( builder ) {
  23516. this._updateResolution( _defaultRT, builder.renderer );
  23517. return super.setup( builder );
  23518. }
  23519. /**
  23520. * Frees internal resources. Should be called when the node is no longer in use.
  23521. */
  23522. dispose() {
  23523. super.dispose();
  23524. for ( const renderTarget of this.renderTargets.values() ) {
  23525. renderTarget.dispose();
  23526. }
  23527. }
  23528. /**
  23529. * Returns a virtual camera for the given camera. The virtual camera is used to
  23530. * render the scene from the reflector's view so correct reflections can be produced.
  23531. *
  23532. * @param {Camera} camera - The scene's camera.
  23533. * @return {Camera} The corresponding virtual camera.
  23534. */
  23535. getVirtualCamera( camera ) {
  23536. let virtualCamera = this.virtualCameras.get( camera );
  23537. if ( virtualCamera === undefined ) {
  23538. virtualCamera = camera.clone();
  23539. this.virtualCameras.set( camera, virtualCamera );
  23540. }
  23541. return virtualCamera;
  23542. }
  23543. /**
  23544. * Returns a render target for the given camera. The reflections are rendered
  23545. * into this render target.
  23546. *
  23547. * @param {Camera} camera - The scene's camera.
  23548. * @return {RenderTarget} The render target.
  23549. */
  23550. getRenderTarget( camera ) {
  23551. let renderTarget = this.renderTargets.get( camera );
  23552. if ( renderTarget === undefined ) {
  23553. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  23554. if ( this.generateMipmaps === true ) {
  23555. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  23556. renderTarget.texture.generateMipmaps = true;
  23557. }
  23558. if ( this.depth === true ) {
  23559. renderTarget.depthTexture = new DepthTexture();
  23560. }
  23561. this.renderTargets.set( camera, renderTarget );
  23562. }
  23563. return renderTarget;
  23564. }
  23565. updateBefore( frame ) {
  23566. if ( this.bounces === false && _inReflector ) return false;
  23567. _inReflector = true;
  23568. const { scene, camera, renderer, material } = frame;
  23569. const { target } = this;
  23570. const virtualCamera = this.getVirtualCamera( camera );
  23571. const renderTarget = this.getRenderTarget( virtualCamera );
  23572. renderer.getDrawingBufferSize( _size$2 );
  23573. this._updateResolution( renderTarget, renderer );
  23574. //
  23575. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  23576. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  23577. _rotationMatrix.extractRotation( target.matrixWorld );
  23578. _normal.set( 0, 0, 1 );
  23579. _normal.applyMatrix4( _rotationMatrix );
  23580. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  23581. // Avoid rendering when reflector is facing away unless forcing an update
  23582. const isFacingAway = _view.dot( _normal ) > 0;
  23583. let needsClear = false;
  23584. if ( isFacingAway === true && this.forceUpdate === false ) {
  23585. if ( this.hasOutput === false ) {
  23586. _inReflector = false;
  23587. return;
  23588. }
  23589. needsClear = true;
  23590. }
  23591. _view.reflect( _normal ).negate();
  23592. _view.add( _reflectorWorldPosition );
  23593. _rotationMatrix.extractRotation( camera.matrixWorld );
  23594. _lookAtPosition.set( 0, 0, -1 );
  23595. _lookAtPosition.applyMatrix4( _rotationMatrix );
  23596. _lookAtPosition.add( _cameraWorldPosition );
  23597. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  23598. _target.reflect( _normal ).negate();
  23599. _target.add( _reflectorWorldPosition );
  23600. //
  23601. virtualCamera.coordinateSystem = camera.coordinateSystem;
  23602. virtualCamera.position.copy( _view );
  23603. virtualCamera.up.set( 0, 1, 0 );
  23604. virtualCamera.up.applyMatrix4( _rotationMatrix );
  23605. virtualCamera.up.reflect( _normal );
  23606. virtualCamera.lookAt( _target );
  23607. virtualCamera.near = camera.near;
  23608. virtualCamera.far = camera.far;
  23609. virtualCamera.updateMatrixWorld();
  23610. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  23611. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  23612. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  23613. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  23614. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  23615. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  23616. const projectionMatrix = virtualCamera.projectionMatrix;
  23617. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  23618. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  23619. _q.z = -1;
  23620. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  23621. // Calculate the scaled plane vector
  23622. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  23623. const clipBias = 0;
  23624. // Replacing the third row of the projection matrix
  23625. projectionMatrix.elements[ 2 ] = clipPlane.x;
  23626. projectionMatrix.elements[ 6 ] = clipPlane.y;
  23627. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  23628. projectionMatrix.elements[ 14 ] = clipPlane.w;
  23629. //
  23630. this.textureNode.value = renderTarget.texture;
  23631. if ( this.depth === true ) {
  23632. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  23633. }
  23634. material.visible = false;
  23635. const currentRenderTarget = renderer.getRenderTarget();
  23636. const currentMRT = renderer.getMRT();
  23637. const currentAutoClear = renderer.autoClear;
  23638. renderer.setMRT( null );
  23639. renderer.setRenderTarget( renderTarget );
  23640. renderer.autoClear = true;
  23641. if ( needsClear ) {
  23642. renderer.clear();
  23643. this.hasOutput = false;
  23644. } else {
  23645. renderer.render( scene, virtualCamera );
  23646. this.hasOutput = true;
  23647. }
  23648. renderer.setMRT( currentMRT );
  23649. renderer.setRenderTarget( currentRenderTarget );
  23650. renderer.autoClear = currentAutoClear;
  23651. material.visible = true;
  23652. _inReflector = false;
  23653. this.forceUpdate = false;
  23654. }
  23655. }
  23656. /**
  23657. * TSL function for creating a reflector node.
  23658. *
  23659. * @tsl
  23660. * @function
  23661. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23662. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23663. * @param {number} [parameters.resolution=1] - The resolution scale.
  23664. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23665. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23666. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23667. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23668. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23669. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23670. * @returns {ReflectorNode}
  23671. */
  23672. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  23673. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  23674. /**
  23675. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  23676. *
  23677. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  23678. *
  23679. * @private
  23680. * @augments BufferGeometry
  23681. */
  23682. class QuadGeometry extends BufferGeometry {
  23683. /**
  23684. * Constructs a new quad geometry.
  23685. *
  23686. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  23687. */
  23688. constructor( flipY = false ) {
  23689. super();
  23690. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  23691. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  23692. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  23693. }
  23694. }
  23695. const _geometry = /*@__PURE__*/ new QuadGeometry();
  23696. /**
  23697. * This module is a helper for passes which need to render a full
  23698. * screen effect which is quite common in context of post processing.
  23699. *
  23700. * The intended usage is to reuse a single quad mesh for rendering
  23701. * subsequent passes by just reassigning the `material` reference.
  23702. *
  23703. * Note: This module can only be used with `WebGPURenderer`.
  23704. *
  23705. * @augments Mesh
  23706. */
  23707. class QuadMesh extends Mesh {
  23708. /**
  23709. * Constructs a new quad mesh.
  23710. *
  23711. * @param {?Material} [material=null] - The material to render the quad mesh with.
  23712. */
  23713. constructor( material = null ) {
  23714. super( _geometry, material );
  23715. /**
  23716. * The camera to render the quad mesh with.
  23717. *
  23718. * @type {OrthographicCamera}
  23719. * @readonly
  23720. */
  23721. this.camera = _camera;
  23722. /**
  23723. * This flag can be used for type testing.
  23724. *
  23725. * @type {boolean}
  23726. * @readonly
  23727. * @default true
  23728. */
  23729. this.isQuadMesh = true;
  23730. }
  23731. /**
  23732. * Async version of `render()`.
  23733. *
  23734. * @async
  23735. * @param {Renderer} renderer - The renderer.
  23736. * @return {Promise} A Promise that resolves when the render has been finished.
  23737. */
  23738. async renderAsync( renderer ) {
  23739. return renderer.renderAsync( this, _camera );
  23740. }
  23741. /**
  23742. * Renders the quad mesh
  23743. *
  23744. * @param {Renderer} renderer - The renderer.
  23745. */
  23746. render( renderer ) {
  23747. renderer.render( this, _camera );
  23748. }
  23749. }
  23750. const _size$1 = /*@__PURE__*/ new Vector2();
  23751. /**
  23752. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  23753. * This module is especially relevant in context of post processing where certain nodes require
  23754. * texture input for their effects. With the helper function `convertToTexture()` which is based
  23755. * on this module, the node system can automatically ensure texture input if required.
  23756. *
  23757. * @augments TextureNode
  23758. */
  23759. class RTTNode extends TextureNode {
  23760. static get type() {
  23761. return 'RTTNode';
  23762. }
  23763. /**
  23764. * Constructs a new RTT node.
  23765. *
  23766. * @param {Node} node - The node to render a texture with.
  23767. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23768. * @param {?number} [height=null] - The height of the internal render target.
  23769. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23770. */
  23771. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  23772. const renderTarget = new RenderTarget( width, height, options );
  23773. super( renderTarget.texture, uv$1() );
  23774. /**
  23775. * This flag can be used for type testing.
  23776. *
  23777. * @type {boolean}
  23778. * @readonly
  23779. * @default true
  23780. */
  23781. this.isRTTNode = true;
  23782. /**
  23783. * The node to render a texture with.
  23784. *
  23785. * @type {Node}
  23786. */
  23787. this.node = node;
  23788. /**
  23789. * The width of the internal render target.
  23790. * If not width is applied, the render target is automatically resized.
  23791. *
  23792. * @type {?number}
  23793. * @default null
  23794. */
  23795. this.width = width;
  23796. /**
  23797. * The height of the internal render target.
  23798. *
  23799. * @type {?number}
  23800. * @default null
  23801. */
  23802. this.height = height;
  23803. /**
  23804. * The pixel ratio
  23805. *
  23806. * @type {number}
  23807. * @default 1
  23808. */
  23809. this.pixelRatio = 1;
  23810. /**
  23811. * The render target
  23812. *
  23813. * @type {RenderTarget}
  23814. */
  23815. this.renderTarget = renderTarget;
  23816. /**
  23817. * Whether the texture requires an update or not.
  23818. *
  23819. * @type {boolean}
  23820. * @default true
  23821. */
  23822. this.textureNeedsUpdate = true;
  23823. /**
  23824. * Whether the texture should automatically be updated or not.
  23825. *
  23826. * @type {boolean}
  23827. * @default true
  23828. */
  23829. this.autoUpdate = true;
  23830. /**
  23831. * The node which is used with the quad mesh for RTT.
  23832. *
  23833. * @private
  23834. * @type {Node}
  23835. * @default null
  23836. */
  23837. this._rttNode = null;
  23838. /**
  23839. * The internal quad mesh for RTT.
  23840. *
  23841. * @private
  23842. * @type {QuadMesh}
  23843. */
  23844. this._quadMesh = new QuadMesh( new NodeMaterial() );
  23845. /**
  23846. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  23847. * the texture once per render in its {@link RTTNode#updateBefore} method.
  23848. *
  23849. * @type {string}
  23850. * @default 'render'
  23851. */
  23852. this.updateBeforeType = NodeUpdateType.RENDER;
  23853. }
  23854. /**
  23855. * Whether the internal render target should automatically be resized or not.
  23856. *
  23857. * @type {boolean}
  23858. * @readonly
  23859. * @default true
  23860. */
  23861. get autoResize() {
  23862. return this.width === null;
  23863. }
  23864. setup( builder ) {
  23865. this._rttNode = this.node.context( builder.getSharedContext() );
  23866. this._quadMesh.material.name = 'RTT';
  23867. this._quadMesh.material.needsUpdate = true;
  23868. return super.setup( builder );
  23869. }
  23870. /**
  23871. * Sets the size of the internal render target
  23872. *
  23873. * @param {number} width - The width to set.
  23874. * @param {number} height - The width to set.
  23875. */
  23876. setSize( width, height ) {
  23877. this.width = width;
  23878. this.height = height;
  23879. const effectiveWidth = width * this.pixelRatio;
  23880. const effectiveHeight = height * this.pixelRatio;
  23881. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23882. this.textureNeedsUpdate = true;
  23883. }
  23884. /**
  23885. * Sets the pixel ratio. This will also resize the render target.
  23886. *
  23887. * @param {number} pixelRatio - The pixel ratio to set.
  23888. */
  23889. setPixelRatio( pixelRatio ) {
  23890. this.pixelRatio = pixelRatio;
  23891. this.setSize( this.width, this.height );
  23892. }
  23893. updateBefore( { renderer } ) {
  23894. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  23895. this.textureNeedsUpdate = false;
  23896. //
  23897. if ( this.autoResize === true ) {
  23898. const pixelRatio = renderer.getPixelRatio();
  23899. const size = renderer.getSize( _size$1 );
  23900. const effectiveWidth = size.width * pixelRatio;
  23901. const effectiveHeight = size.height * pixelRatio;
  23902. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  23903. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23904. this.textureNeedsUpdate = true;
  23905. }
  23906. }
  23907. //
  23908. this._quadMesh.material.fragmentNode = this._rttNode;
  23909. //
  23910. const currentRenderTarget = renderer.getRenderTarget();
  23911. renderer.setRenderTarget( this.renderTarget );
  23912. this._quadMesh.render( renderer );
  23913. renderer.setRenderTarget( currentRenderTarget );
  23914. }
  23915. clone() {
  23916. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  23917. newNode.sampler = this.sampler;
  23918. newNode.referenceNode = this;
  23919. return newNode;
  23920. }
  23921. }
  23922. /**
  23923. * TSL function for creating a RTT node.
  23924. *
  23925. * @tsl
  23926. * @function
  23927. * @param {Node} node - The node to render a texture with.
  23928. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23929. * @param {?number} [height=null] - The height of the internal render target.
  23930. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23931. * @returns {RTTNode}
  23932. */
  23933. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  23934. /**
  23935. * TSL function for converting nodes to textures nodes.
  23936. *
  23937. * @tsl
  23938. * @function
  23939. * @param {Node} node - The node to render a texture with.
  23940. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23941. * @param {?number} [height=null] - The height of the internal render target.
  23942. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23943. * @returns {RTTNode}
  23944. */
  23945. const convertToTexture = ( node, ...params ) => {
  23946. if ( node.isSampleNode || node.isTextureNode ) return node;
  23947. if ( node.isPassNode ) return node.getTextureNode();
  23948. return rtt( node, ...params );
  23949. };
  23950. /**
  23951. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  23952. * depth value and the camera's inverse projection matrix.
  23953. *
  23954. * @tsl
  23955. * @function
  23956. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  23957. * @param {Node<float>} depth - The fragment's depth value.
  23958. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23959. * @return {Node<vec3>} The fragments position in view space.
  23960. */
  23961. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  23962. let clipSpacePosition;
  23963. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  23964. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  23965. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  23966. } else {
  23967. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  23968. }
  23969. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  23970. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  23971. } );
  23972. /**
  23973. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  23974. * and the camera's projection matrix
  23975. *
  23976. * @tsl
  23977. * @function
  23978. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  23979. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  23980. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  23981. */
  23982. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  23983. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  23984. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  23985. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  23986. } );
  23987. /**
  23988. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  23989. * target is available or if flat surface normals are required.
  23990. *
  23991. * @tsl
  23992. * @function
  23993. * @param {Node<vec2>} uv - The texture coordinate.
  23994. * @param {DepthTexture} depthTexture - The depth texture.
  23995. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23996. * @return {Node<vec3>} The computed normal vector.
  23997. */
  23998. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  23999. const size = textureSize( textureLoad( depthTexture ) );
  24000. const p = ivec2( uv.mul( size ) ).toVar();
  24001. const c0 = textureLoad( depthTexture, p ).toVar();
  24002. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  24003. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  24004. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  24005. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  24006. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  24007. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  24008. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  24009. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  24010. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  24011. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  24012. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  24013. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  24014. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  24015. 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 ) ) );
  24016. 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 ) ) );
  24017. return normalize( cross( dpdx, dpdy ) );
  24018. } );
  24019. /**
  24020. * Class representing a node that samples a value using a provided callback function.
  24021. *
  24022. * @extends Node
  24023. */
  24024. class SampleNode extends Node {
  24025. /**
  24026. * Returns the type of the node.
  24027. *
  24028. * @type {string}
  24029. * @readonly
  24030. * @static
  24031. */
  24032. static get type() {
  24033. return 'SampleNode';
  24034. }
  24035. /**
  24036. * Creates an instance of SampleNode.
  24037. *
  24038. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24039. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  24040. */
  24041. constructor( callback, uvNode = null ) {
  24042. super();
  24043. this.callback = callback;
  24044. /**
  24045. * Represents the texture coordinates.
  24046. *
  24047. * @type {?Node<vec2|vec3>}
  24048. * @default null
  24049. */
  24050. this.uvNode = uvNode;
  24051. /**
  24052. * This flag can be used for type testing.
  24053. *
  24054. * @type {boolean}
  24055. * @readonly
  24056. * @default true
  24057. */
  24058. this.isSampleNode = true;
  24059. }
  24060. /**
  24061. * Sets up the node by sampling with the default UV accessor.
  24062. *
  24063. * @returns {Node} The result of the callback function when called with the UV node.
  24064. */
  24065. setup() {
  24066. return this.sample( uv$1() );
  24067. }
  24068. /**
  24069. * Calls the callback function with the provided UV node.
  24070. *
  24071. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  24072. * @returns {Node} The result of the callback function.
  24073. */
  24074. sample( uv ) {
  24075. return this.callback( uv );
  24076. }
  24077. }
  24078. /**
  24079. * Helper function to create a SampleNode wrapped as a node object.
  24080. *
  24081. * @function
  24082. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24083. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  24084. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  24085. */
  24086. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  24087. /**
  24088. * EventNode is a node that executes a callback during specific update phases.
  24089. *
  24090. * @augments Node
  24091. */
  24092. class EventNode extends Node {
  24093. static get type() {
  24094. return 'EventNode';
  24095. }
  24096. /**
  24097. * Creates an EventNode.
  24098. *
  24099. * @param {string} eventType - The type of event
  24100. * @param {Function} callback - The callback to execute on update.
  24101. */
  24102. constructor( eventType, callback ) {
  24103. super( 'void' );
  24104. this.eventType = eventType;
  24105. this.callback = callback;
  24106. if ( eventType === EventNode.OBJECT ) {
  24107. this.updateType = NodeUpdateType.OBJECT;
  24108. } else if ( eventType === EventNode.MATERIAL ) {
  24109. this.updateType = NodeUpdateType.RENDER;
  24110. }
  24111. }
  24112. update( frame ) {
  24113. this.callback( frame );
  24114. }
  24115. }
  24116. EventNode.OBJECT = 'object';
  24117. EventNode.MATERIAL = 'material';
  24118. /**
  24119. * Helper to create an EventNode and add it to the stack.
  24120. *
  24121. * @param {string} type - The event type.
  24122. * @param {Function} callback - The callback function.
  24123. * @returns {EventNode}
  24124. */
  24125. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  24126. /**
  24127. * Creates an event that triggers a function every time an object (Mesh|Sprite) 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 OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  24135. /**
  24136. * Creates an event that triggers a function when the first object that uses the material is rendered.
  24137. *
  24138. * 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.
  24139. *
  24140. * @param {Function} callback - The callback function.
  24141. * @returns {EventNode}
  24142. */
  24143. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  24144. /**
  24145. * This special type of instanced buffer attribute is intended for compute shaders.
  24146. * In earlier three.js versions it was only possible to update attribute data
  24147. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24148. * new material system and renderer it is now possible to use compute shaders
  24149. * to compute the data for an attribute more efficiently on the GPU.
  24150. *
  24151. * The idea is to create an instance of this class and provide it as an input
  24152. * to {@link StorageBufferNode}.
  24153. *
  24154. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24155. *
  24156. * @augments InstancedBufferAttribute
  24157. */
  24158. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24159. /**
  24160. * Constructs a new storage instanced buffer attribute.
  24161. *
  24162. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24163. * The subsequent parameters are then obsolete.
  24164. * @param {number} itemSize - The item size.
  24165. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24166. */
  24167. constructor( count, itemSize, typeClass = Float32Array ) {
  24168. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24169. super( array, itemSize );
  24170. /**
  24171. * This flag can be used for type testing.
  24172. *
  24173. * @type {boolean}
  24174. * @readonly
  24175. * @default true
  24176. */
  24177. this.isStorageInstancedBufferAttribute = true;
  24178. }
  24179. }
  24180. /**
  24181. * This special type of buffer attribute is intended for compute shaders.
  24182. * In earlier three.js versions it was only possible to update attribute data
  24183. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24184. * new material system and renderer it is now possible to use compute shaders
  24185. * to compute the data for an attribute more efficiently on the GPU.
  24186. *
  24187. * The idea is to create an instance of this class and provide it as an input
  24188. * to {@link StorageBufferNode}.
  24189. *
  24190. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24191. *
  24192. * @augments BufferAttribute
  24193. */
  24194. class StorageBufferAttribute extends BufferAttribute {
  24195. /**
  24196. * Constructs a new storage buffer attribute.
  24197. *
  24198. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24199. * The subsequent parameters are then obsolete.
  24200. * @param {number} itemSize - The item size.
  24201. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24202. */
  24203. constructor( count, itemSize, typeClass = Float32Array ) {
  24204. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24205. super( array, itemSize );
  24206. /**
  24207. * This flag can be used for type testing.
  24208. *
  24209. * @type {boolean}
  24210. * @readonly
  24211. * @default true
  24212. */
  24213. this.isStorageBufferAttribute = true;
  24214. }
  24215. }
  24216. /**
  24217. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  24218. *
  24219. * @tsl
  24220. * @function
  24221. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24222. * @param {string|Struct} [type='float'] - The data type.
  24223. * @returns {StorageBufferNode}
  24224. */
  24225. const attributeArray = ( count, type = 'float' ) => {
  24226. let itemSize, typedArray;
  24227. if ( type.isStruct === true ) {
  24228. itemSize = type.layout.getLength();
  24229. typedArray = getTypedArrayFromType( 'float' );
  24230. } else {
  24231. itemSize = getLengthFromType( type );
  24232. typedArray = getTypedArrayFromType( type );
  24233. }
  24234. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  24235. const node = storage( buffer, type, count );
  24236. return node;
  24237. };
  24238. /**
  24239. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  24240. *
  24241. * @tsl
  24242. * @function
  24243. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24244. * @param {string|Struct} [type='float'] - The data type.
  24245. * @returns {StorageBufferNode}
  24246. */
  24247. const instancedArray = ( count, type = 'float' ) => {
  24248. let itemSize, typedArray;
  24249. if ( type.isStruct === true ) {
  24250. itemSize = type.layout.getLength();
  24251. typedArray = getTypedArrayFromType( 'float' );
  24252. } else {
  24253. itemSize = getLengthFromType( type );
  24254. typedArray = getTypedArrayFromType( type );
  24255. }
  24256. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  24257. const node = storage( buffer, type, count );
  24258. return node;
  24259. };
  24260. /**
  24261. * A node for representing the uv coordinates of points.
  24262. *
  24263. * Can only be used with a WebGL backend. In WebGPU, point
  24264. * primitives always have the size of one pixel and can thus
  24265. * can't be used as sprite-like objects that display textures.
  24266. *
  24267. * @augments Node
  24268. */
  24269. class PointUVNode extends Node {
  24270. static get type() {
  24271. return 'PointUVNode';
  24272. }
  24273. /**
  24274. * Constructs a new point uv node.
  24275. */
  24276. constructor() {
  24277. super( 'vec2' );
  24278. /**
  24279. * This flag can be used for type testing.
  24280. *
  24281. * @type {boolean}
  24282. * @readonly
  24283. * @default true
  24284. */
  24285. this.isPointUVNode = true;
  24286. }
  24287. generate( /*builder*/ ) {
  24288. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  24289. }
  24290. }
  24291. /**
  24292. * TSL object that represents the uv coordinates of points.
  24293. *
  24294. * @tsl
  24295. * @type {PointUVNode}
  24296. */
  24297. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  24298. const _e1 = /*@__PURE__*/ new Euler();
  24299. const _m1 = /*@__PURE__*/ new Matrix4();
  24300. /**
  24301. * This module allows access to a collection of scene properties. The following predefined TSL objects
  24302. * are available for easier use:
  24303. *
  24304. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  24305. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  24306. * - `backgroundRotation`: A node that represents the scene's background rotation.
  24307. *
  24308. * @augments Node
  24309. */
  24310. class SceneNode extends Node {
  24311. static get type() {
  24312. return 'SceneNode';
  24313. }
  24314. /**
  24315. * Constructs a new scene node.
  24316. *
  24317. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  24318. * @param {?Scene} [scene=null] - A reference to the scene.
  24319. */
  24320. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  24321. super();
  24322. /**
  24323. * The scope defines the type of scene property that is accessed.
  24324. *
  24325. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  24326. */
  24327. this.scope = scope;
  24328. /**
  24329. * A reference to the scene that is going to be accessed.
  24330. *
  24331. * @type {?Scene}
  24332. * @default null
  24333. */
  24334. this.scene = scene;
  24335. }
  24336. /**
  24337. * Depending on the scope, the method returns a different type of node that represents
  24338. * the respective scene property.
  24339. *
  24340. * @param {NodeBuilder} builder - The current node builder.
  24341. * @return {Node} The output node.
  24342. */
  24343. setup( builder ) {
  24344. const scope = this.scope;
  24345. const scene = this.scene !== null ? this.scene : builder.scene;
  24346. let output;
  24347. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  24348. output = reference( 'backgroundBlurriness', 'float', scene );
  24349. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  24350. output = reference( 'backgroundIntensity', 'float', scene );
  24351. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  24352. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24353. const background = scene.background;
  24354. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  24355. _e1.copy( scene.backgroundRotation );
  24356. // accommodate left-handed frame
  24357. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  24358. _m1.makeRotationFromEuler( _e1 );
  24359. } else {
  24360. _m1.identity();
  24361. }
  24362. return _m1;
  24363. } );
  24364. } else {
  24365. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  24366. }
  24367. return output;
  24368. }
  24369. }
  24370. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  24371. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  24372. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  24373. /**
  24374. * TSL object that represents the scene's background blurriness.
  24375. *
  24376. * @tsl
  24377. * @type {SceneNode}
  24378. */
  24379. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  24380. /**
  24381. * TSL object that represents the scene's background intensity.
  24382. *
  24383. * @tsl
  24384. * @type {SceneNode}
  24385. */
  24386. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  24387. /**
  24388. * TSL object that represents the scene's background rotation.
  24389. *
  24390. * @tsl
  24391. * @type {SceneNode}
  24392. */
  24393. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  24394. /**
  24395. * This special version of a texture node can be used to
  24396. * write data into a storage texture with a compute shader.
  24397. *
  24398. * ```js
  24399. * const storageTexture = new THREE.StorageTexture( width, height );
  24400. *
  24401. * const computeTexture = Fn( ( { storageTexture } ) => {
  24402. *
  24403. * const posX = instanceIndex.mod( width );
  24404. * const posY = instanceIndex.div( width );
  24405. * const indexUV = uvec2( posX, posY );
  24406. *
  24407. * // generate RGB values
  24408. *
  24409. * const r = 1;
  24410. * const g = 1;
  24411. * const b = 1;
  24412. *
  24413. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  24414. *
  24415. * } );
  24416. *
  24417. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  24418. * renderer.computeAsync( computeNode );
  24419. * ```
  24420. *
  24421. * This node can only be used with a WebGPU backend.
  24422. *
  24423. * @augments TextureNode
  24424. */
  24425. class StorageTextureNode extends TextureNode {
  24426. static get type() {
  24427. return 'StorageTextureNode';
  24428. }
  24429. /**
  24430. * Constructs a new storage texture node.
  24431. *
  24432. * @param {StorageTexture} value - The storage texture.
  24433. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24434. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24435. */
  24436. constructor( value, uvNode, storeNode = null ) {
  24437. super( value, uvNode );
  24438. /**
  24439. * The value node that should be stored in the texture.
  24440. *
  24441. * @type {?Node}
  24442. * @default null
  24443. */
  24444. this.storeNode = storeNode;
  24445. /**
  24446. * This flag can be used for type testing.
  24447. *
  24448. * @type {boolean}
  24449. * @readonly
  24450. * @default true
  24451. */
  24452. this.isStorageTextureNode = true;
  24453. /**
  24454. * The access type of the texture node.
  24455. *
  24456. * @type {string}
  24457. * @default 'writeOnly'
  24458. */
  24459. this.access = NodeAccess.WRITE_ONLY;
  24460. }
  24461. /**
  24462. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  24463. *
  24464. * @param {NodeBuilder} builder - The current node builder.
  24465. * @return {string} The input type.
  24466. */
  24467. getInputType( /*builder*/ ) {
  24468. return 'storageTexture';
  24469. }
  24470. setup( builder ) {
  24471. super.setup( builder );
  24472. const properties = builder.getNodeProperties( this );
  24473. properties.storeNode = this.storeNode;
  24474. return properties;
  24475. }
  24476. /**
  24477. * Defines the node access.
  24478. *
  24479. * @param {string} value - The node access.
  24480. * @return {StorageTextureNode} A reference to this node.
  24481. */
  24482. setAccess( value ) {
  24483. this.access = value;
  24484. return this;
  24485. }
  24486. /**
  24487. * Generates the code snippet of the storage node. If no `storeNode`
  24488. * is defined, the texture node is generated as normal texture.
  24489. *
  24490. * @param {NodeBuilder} builder - The current node builder.
  24491. * @param {string} output - The current output.
  24492. * @return {string} The generated code snippet.
  24493. */
  24494. generate( builder, output ) {
  24495. let snippet;
  24496. if ( this.storeNode !== null ) {
  24497. snippet = this.generateStore( builder );
  24498. } else {
  24499. snippet = super.generate( builder, output );
  24500. }
  24501. return snippet;
  24502. }
  24503. /**
  24504. * Convenience method for configuring a read/write node access.
  24505. *
  24506. * @return {StorageTextureNode} A reference to this node.
  24507. */
  24508. toReadWrite() {
  24509. return this.setAccess( NodeAccess.READ_WRITE );
  24510. }
  24511. /**
  24512. * Convenience method for configuring a read-only node access.
  24513. *
  24514. * @return {StorageTextureNode} A reference to this node.
  24515. */
  24516. toReadOnly() {
  24517. return this.setAccess( NodeAccess.READ_ONLY );
  24518. }
  24519. /**
  24520. * Convenience method for configuring a write-only node access.
  24521. *
  24522. * @return {StorageTextureNode} A reference to this node.
  24523. */
  24524. toWriteOnly() {
  24525. return this.setAccess( NodeAccess.WRITE_ONLY );
  24526. }
  24527. /**
  24528. * Generates the code snippet of the storage texture node.
  24529. *
  24530. * @param {NodeBuilder} builder - The current node builder.
  24531. */
  24532. generateStore( builder ) {
  24533. const properties = builder.getNodeProperties( this );
  24534. const { uvNode, storeNode, depthNode } = properties;
  24535. const textureProperty = super.generate( builder, 'property' );
  24536. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  24537. const storeSnippet = storeNode.build( builder, 'vec4' );
  24538. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24539. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  24540. builder.addLineFlowCode( snippet, this );
  24541. }
  24542. clone() {
  24543. const newNode = super.clone();
  24544. newNode.storeNode = this.storeNode;
  24545. return newNode;
  24546. }
  24547. }
  24548. /**
  24549. * TSL function for creating a storage texture node.
  24550. *
  24551. * @tsl
  24552. * @function
  24553. * @param {StorageTexture} value - The storage texture.
  24554. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  24555. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24556. * @returns {StorageTextureNode}
  24557. */
  24558. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  24559. /**
  24560. * TODO: Explain difference to `storageTexture()`.
  24561. *
  24562. * @tsl
  24563. * @function
  24564. * @param {StorageTexture} value - The storage texture.
  24565. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24566. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24567. * @returns {StorageTextureNode}
  24568. */
  24569. const textureStore = ( value, uvNode, storeNode ) => {
  24570. const node = storageTexture( value, uvNode, storeNode );
  24571. if ( storeNode !== null ) node.toStack();
  24572. return node;
  24573. };
  24574. const normal = Fn( ( { texture, uv } ) => {
  24575. const epsilon = 0.0001;
  24576. const ret = vec3().toVar();
  24577. If( uv.x.lessThan( epsilon ), () => {
  24578. ret.assign( vec3( 1, 0, 0 ) );
  24579. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  24580. ret.assign( vec3( 0, 1, 0 ) );
  24581. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  24582. ret.assign( vec3( 0, 0, 1 ) );
  24583. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  24584. ret.assign( vec3( -1, 0, 0 ) );
  24585. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  24586. ret.assign( vec3( 0, -1, 0 ) );
  24587. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  24588. ret.assign( vec3( 0, 0, -1 ) );
  24589. } ).Else( () => {
  24590. const step = 0.01;
  24591. 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 );
  24592. 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 );
  24593. 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 );
  24594. ret.assign( vec3( x, y, z ) );
  24595. } );
  24596. return ret.normalize();
  24597. } );
  24598. /**
  24599. * This type of uniform node represents a 3D texture.
  24600. *
  24601. * @augments TextureNode
  24602. */
  24603. class Texture3DNode extends TextureNode {
  24604. static get type() {
  24605. return 'Texture3DNode';
  24606. }
  24607. /**
  24608. * Constructs a new 3D texture node.
  24609. *
  24610. * @param {Data3DTexture} value - The 3D texture.
  24611. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24612. * @param {?Node<int>} [levelNode=null] - The level node.
  24613. */
  24614. constructor( value, uvNode = null, levelNode = null ) {
  24615. super( value, uvNode, levelNode );
  24616. /**
  24617. * This flag can be used for type testing.
  24618. *
  24619. * @type {boolean}
  24620. * @readonly
  24621. * @default true
  24622. */
  24623. this.isTexture3DNode = true;
  24624. }
  24625. /**
  24626. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  24627. *
  24628. * @param {NodeBuilder} builder - The current node builder.
  24629. * @return {string} The input type.
  24630. */
  24631. getInputType( /*builder*/ ) {
  24632. return 'texture3D';
  24633. }
  24634. /**
  24635. * Returns a default uv node which is in context of 3D textures a three-dimensional
  24636. * uv node.
  24637. *
  24638. * @return {Node<vec3>} The default uv node.
  24639. */
  24640. getDefaultUV() {
  24641. return vec3( 0.5, 0.5, 0.5 );
  24642. }
  24643. /**
  24644. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  24645. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  24646. *
  24647. * @param {boolean} value - The update toggle.
  24648. */
  24649. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  24650. /**
  24651. * Overwrites the default implementation to return the unmodified uv node.
  24652. *
  24653. * @param {NodeBuilder} builder - The current node builder.
  24654. * @param {Node} uvNode - The uv node to setup.
  24655. * @return {Node} The unmodified uv node.
  24656. */
  24657. setupUV( builder, uvNode ) {
  24658. const texture = this.value;
  24659. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  24660. if ( this.sampler ) {
  24661. uvNode = uvNode.flipY();
  24662. } else {
  24663. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24664. }
  24665. }
  24666. return uvNode;
  24667. }
  24668. /**
  24669. * Generates the uv code snippet.
  24670. *
  24671. * @param {NodeBuilder} builder - The current node builder.
  24672. * @param {Node} uvNode - The uv node to generate code for.
  24673. * @return {string} The generated code snippet.
  24674. */
  24675. generateUV( builder, uvNode ) {
  24676. return uvNode.build( builder, 'vec3' );
  24677. }
  24678. /**
  24679. * TODO.
  24680. *
  24681. * @param {Node<vec3>} uvNode - The uv node .
  24682. * @return {Node<vec3>} TODO.
  24683. */
  24684. normal( uvNode ) {
  24685. return normal( { texture: this, uv: uvNode } );
  24686. }
  24687. }
  24688. /**
  24689. * TSL function for creating a 3D texture node.
  24690. *
  24691. * @tsl
  24692. * @function
  24693. * @param {Data3DTexture} value - The 3D texture.
  24694. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24695. * @param {?Node<int>} [levelNode=null] - The level node.
  24696. * @returns {Texture3DNode}
  24697. */
  24698. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  24699. /**
  24700. * A special type of reference node that allows to link values in
  24701. * `userData` fields to node objects.
  24702. * ```js
  24703. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  24704. *
  24705. * const material = new THREE.SpriteNodeMaterial();
  24706. * material.rotationNode = userData( 'rotation', 'float' );
  24707. * ```
  24708. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  24709. * will automatically be updated when the `rotation` user data field changes.
  24710. *
  24711. * @augments ReferenceNode
  24712. */
  24713. class UserDataNode extends ReferenceNode {
  24714. static get type() {
  24715. return 'UserDataNode';
  24716. }
  24717. /**
  24718. * Constructs a new user data node.
  24719. *
  24720. * @param {string} property - The property name that should be referenced by the node.
  24721. * @param {string} inputType - The node data type of the reference.
  24722. * @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.
  24723. */
  24724. constructor( property, inputType, userData = null ) {
  24725. super( property, inputType, userData );
  24726. /**
  24727. * A reference to the `userData` object. If not provided, the `userData`
  24728. * property of the 3D object that uses the node material is evaluated.
  24729. *
  24730. * @type {?Object}
  24731. * @default null
  24732. */
  24733. this.userData = userData;
  24734. }
  24735. /**
  24736. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  24737. * `userData` field.
  24738. *
  24739. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  24740. * @return {Object} A reference to the `userData` field.
  24741. */
  24742. updateReference( state ) {
  24743. this.reference = this.userData !== null ? this.userData : state.object.userData;
  24744. return this.reference;
  24745. }
  24746. }
  24747. /**
  24748. * TSL function for creating a user data node.
  24749. *
  24750. * @tsl
  24751. * @function
  24752. * @param {string} name - The property name that should be referenced by the node.
  24753. * @param {string} inputType - The node data type of the reference.
  24754. * @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.
  24755. * @returns {UserDataNode}
  24756. */
  24757. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  24758. const _objectData = new WeakMap();
  24759. /**
  24760. * A node for representing motion or velocity vectors. Foundation
  24761. * for advanced post processing effects like motion blur or TRAA.
  24762. *
  24763. * The node keeps track of the model, view and projection matrices
  24764. * of the previous frame and uses them to compute offsets in NDC space.
  24765. * These offsets represent the final velocity.
  24766. *
  24767. * @augments TempNode
  24768. */
  24769. class VelocityNode extends TempNode {
  24770. static get type() {
  24771. return 'VelocityNode';
  24772. }
  24773. /**
  24774. * Constructs a new vertex color node.
  24775. */
  24776. constructor() {
  24777. super( 'vec2' );
  24778. /**
  24779. * The current projection matrix.
  24780. *
  24781. * @type {?Matrix4}
  24782. * @default null
  24783. */
  24784. this.projectionMatrix = null;
  24785. /**
  24786. * Overwritten since velocity nodes are updated per object.
  24787. *
  24788. * @type {string}
  24789. * @default 'object'
  24790. */
  24791. this.updateType = NodeUpdateType.OBJECT;
  24792. /**
  24793. * Overwritten since velocity nodes save data after the update.
  24794. *
  24795. * @type {string}
  24796. * @default 'object'
  24797. */
  24798. this.updateAfterType = NodeUpdateType.OBJECT;
  24799. /**
  24800. * Uniform node representing the previous model matrix in world space.
  24801. *
  24802. * @type {UniformNode<mat4>}
  24803. * @default null
  24804. */
  24805. this.previousModelWorldMatrix = uniform( new Matrix4() );
  24806. /**
  24807. * Uniform node representing the previous projection matrix.
  24808. *
  24809. * @type {UniformNode<mat4>}
  24810. * @default null
  24811. */
  24812. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  24813. /**
  24814. * Uniform node representing the previous view matrix.
  24815. *
  24816. * @type {UniformNode<mat4>}
  24817. * @default null
  24818. */
  24819. this.previousCameraViewMatrix = uniform( new Matrix4() );
  24820. }
  24821. /**
  24822. * Sets the given projection matrix.
  24823. *
  24824. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  24825. */
  24826. setProjectionMatrix( projectionMatrix ) {
  24827. this.projectionMatrix = projectionMatrix;
  24828. }
  24829. /**
  24830. * Updates velocity specific uniforms.
  24831. *
  24832. * @param {NodeFrame} frame - A reference to the current node frame.
  24833. */
  24834. update( { frameId, camera, object } ) {
  24835. const previousModelMatrix = getPreviousMatrix( object );
  24836. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  24837. //
  24838. const cameraData = getData( camera );
  24839. if ( cameraData.frameId !== frameId ) {
  24840. cameraData.frameId = frameId;
  24841. if ( cameraData.previousProjectionMatrix === undefined ) {
  24842. cameraData.previousProjectionMatrix = new Matrix4();
  24843. cameraData.previousCameraViewMatrix = new Matrix4();
  24844. cameraData.currentProjectionMatrix = new Matrix4();
  24845. cameraData.currentCameraViewMatrix = new Matrix4();
  24846. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24847. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  24848. } else {
  24849. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  24850. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  24851. }
  24852. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24853. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  24854. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  24855. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  24856. }
  24857. }
  24858. /**
  24859. * Overwritten to updated velocity specific uniforms.
  24860. *
  24861. * @param {NodeFrame} frame - A reference to the current node frame.
  24862. */
  24863. updateAfter( { object } ) {
  24864. getPreviousMatrix( object ).copy( object.matrixWorld );
  24865. }
  24866. /**
  24867. * Implements the velocity computation based on the previous and current vertex data.
  24868. *
  24869. * @param {NodeBuilder} builder - A reference to the current node builder.
  24870. * @return {Node<vec2>} The motion vector.
  24871. */
  24872. setup( /*builder*/ ) {
  24873. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  24874. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  24875. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24876. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  24877. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  24878. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  24879. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  24880. return velocity;
  24881. }
  24882. }
  24883. function getData( object ) {
  24884. let objectData = _objectData.get( object );
  24885. if ( objectData === undefined ) {
  24886. objectData = {};
  24887. _objectData.set( object, objectData );
  24888. }
  24889. return objectData;
  24890. }
  24891. function getPreviousMatrix( object, index = 0 ) {
  24892. const objectData = getData( object );
  24893. let matrix = objectData[ index ];
  24894. if ( matrix === undefined ) {
  24895. objectData[ index ] = matrix = new Matrix4();
  24896. objectData[ index ].copy( object.matrixWorld );
  24897. }
  24898. return matrix;
  24899. }
  24900. /**
  24901. * TSL object that represents the velocity of a render pass.
  24902. *
  24903. * @tsl
  24904. * @type {VelocityNode}
  24905. */
  24906. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  24907. /**
  24908. * Computes a grayscale value for the given RGB color value.
  24909. *
  24910. * @tsl
  24911. * @function
  24912. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  24913. * @return {Node<vec3>} The grayscale color.
  24914. */
  24915. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24916. return luminance( color.rgb );
  24917. } );
  24918. /**
  24919. * Super-saturates or desaturates the given RGB color.
  24920. *
  24921. * @tsl
  24922. * @function
  24923. * @param {Node<vec3>} color - The input color.
  24924. * @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.
  24925. * @return {Node<vec3>} The saturated color.
  24926. */
  24927. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24928. return adjustment.mix( luminance( color.rgb ), color.rgb );
  24929. } );
  24930. /**
  24931. * Selectively enhance the intensity of less saturated RGB colors. Can result
  24932. * in a more natural and visually appealing image with enhanced color depth
  24933. * compared to {@link ColorAdjustment#saturation}.
  24934. *
  24935. * @tsl
  24936. * @function
  24937. * @param {Node<vec3>} color - The input color.
  24938. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  24939. * @return {Node<vec3>} The updated color.
  24940. */
  24941. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24942. const average = add( color.r, color.g, color.b ).div( 3.0 );
  24943. const mx = color.r.max( color.g.max( color.b ) );
  24944. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  24945. return mix( color.rgb, mx, amt );
  24946. } );
  24947. /**
  24948. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  24949. *
  24950. * @tsl
  24951. * @function
  24952. * @param {Node<vec3>} color - The input color.
  24953. * @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.
  24954. * @return {Node<vec3>} The updated color.
  24955. */
  24956. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24957. const k = vec3( 0.57735, 0.57735, 0.57735 );
  24958. const cosAngle = adjustment.cos();
  24959. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  24960. } );
  24961. /**
  24962. * Computes the luminance for the given RGB color value.
  24963. *
  24964. * @tsl
  24965. * @function
  24966. * @param {Node<vec3>} color - The color value to compute the luminance for.
  24967. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  24968. * @return {Node<vec3>} The luminance.
  24969. */
  24970. const luminance = (
  24971. color,
  24972. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  24973. ) => dot( color, luminanceCoefficients );
  24974. /**
  24975. * Color Decision List (CDL) v1.2
  24976. *
  24977. * Compact representation of color grading information, defined by slope, offset, power, and
  24978. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  24979. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  24980. *
  24981. * @tsl
  24982. * @function
  24983. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  24984. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  24985. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  24986. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  24987. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  24988. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  24989. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  24990. *
  24991. * References:
  24992. * - ASC CDL v1.2
  24993. * - {@link https://blender.stackexchange.com/a/55239/43930}
  24994. * - {@link https://docs.acescentral.com/specifications/acescc/}
  24995. */
  24996. const cdl = /*@__PURE__*/ Fn( ( [
  24997. color,
  24998. slope = vec3( 1 ),
  24999. offset = vec3( 0 ),
  25000. power = vec3( 1 ),
  25001. saturation = float( 1 ),
  25002. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  25003. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  25004. ] ) => {
  25005. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  25006. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  25007. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  25008. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  25009. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  25010. const pv = v.pow( power ).toVar();
  25011. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  25012. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  25013. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  25014. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  25015. return vec4( v.rgb, color.a );
  25016. } );
  25017. /**
  25018. * Represents a posterize effect which reduces the number of colors
  25019. * in an image, resulting in a more blocky and stylized appearance.
  25020. *
  25021. * @augments TempNode
  25022. */
  25023. class PosterizeNode extends TempNode {
  25024. static get type() {
  25025. return 'PosterizeNode';
  25026. }
  25027. /**
  25028. * Constructs a new posterize node.
  25029. *
  25030. * @param {Node} sourceNode - The input color.
  25031. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25032. */
  25033. constructor( sourceNode, stepsNode ) {
  25034. super();
  25035. /**
  25036. * The input color.
  25037. *
  25038. * @type {Node}
  25039. */
  25040. this.sourceNode = sourceNode;
  25041. /**
  25042. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25043. *
  25044. * @type {Node}
  25045. */
  25046. this.stepsNode = stepsNode;
  25047. }
  25048. setup() {
  25049. const { sourceNode, stepsNode } = this;
  25050. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  25051. }
  25052. }
  25053. /**
  25054. * TSL function for creating a posterize node.
  25055. *
  25056. * @tsl
  25057. * @function
  25058. * @param {Node} sourceNode - The input color.
  25059. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25060. * @returns {PosterizeNode}
  25061. */
  25062. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  25063. const _size = /*@__PURE__*/ new Vector2();
  25064. /**
  25065. * Represents the texture of a pass node.
  25066. *
  25067. * @augments TextureNode
  25068. */
  25069. class PassTextureNode extends TextureNode {
  25070. static get type() {
  25071. return 'PassTextureNode';
  25072. }
  25073. /**
  25074. * Constructs a new pass texture node.
  25075. *
  25076. * @param {PassNode} passNode - The pass node.
  25077. * @param {Texture} texture - The output texture.
  25078. */
  25079. constructor( passNode, texture ) {
  25080. super( texture );
  25081. /**
  25082. * A reference to the pass node.
  25083. *
  25084. * @type {PassNode}
  25085. */
  25086. this.passNode = passNode;
  25087. this.setUpdateMatrix( false );
  25088. }
  25089. setup( builder ) {
  25090. this.passNode.build( builder );
  25091. return super.setup( builder );
  25092. }
  25093. clone() {
  25094. return new this.constructor( this.passNode, this.value );
  25095. }
  25096. }
  25097. /**
  25098. * An extension of `PassTextureNode` which allows to manage more than one
  25099. * internal texture. Relevant for the `getPreviousTexture()` related API.
  25100. *
  25101. * @augments PassTextureNode
  25102. */
  25103. class PassMultipleTextureNode extends PassTextureNode {
  25104. static get type() {
  25105. return 'PassMultipleTextureNode';
  25106. }
  25107. /**
  25108. * Constructs a new pass texture node.
  25109. *
  25110. * @param {PassNode} passNode - The pass node.
  25111. * @param {string} textureName - The output texture name.
  25112. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  25113. */
  25114. constructor( passNode, textureName, previousTexture = false ) {
  25115. // null is passed to the super call since this class does not
  25116. // use an external texture for rendering pass data into. Instead
  25117. // the texture is managed by the pass node itself
  25118. super( passNode, null );
  25119. /**
  25120. * The output texture name.
  25121. *
  25122. * @type {string}
  25123. */
  25124. this.textureName = textureName;
  25125. /**
  25126. * Whether previous frame data should be used or not.
  25127. *
  25128. * @type {boolean}
  25129. */
  25130. this.previousTexture = previousTexture;
  25131. }
  25132. /**
  25133. * Updates the texture reference of this node.
  25134. */
  25135. updateTexture() {
  25136. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  25137. }
  25138. setup( builder ) {
  25139. this.updateTexture();
  25140. return super.setup( builder );
  25141. }
  25142. clone() {
  25143. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  25144. newNode.uvNode = this.uvNode;
  25145. newNode.levelNode = this.levelNode;
  25146. newNode.biasNode = this.biasNode;
  25147. newNode.sampler = this.sampler;
  25148. newNode.depthNode = this.depthNode;
  25149. newNode.compareNode = this.compareNode;
  25150. newNode.gradNode = this.gradNode;
  25151. return newNode;
  25152. }
  25153. }
  25154. /**
  25155. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  25156. * This pass produces a render for the given scene and camera and can provide multiple outputs
  25157. * via MRT for further processing.
  25158. *
  25159. * ```js
  25160. * const postProcessing = new PostProcessing( renderer );
  25161. *
  25162. * const scenePass = pass( scene, camera );
  25163. *
  25164. * postProcessing.outputNode = scenePass;
  25165. * ```
  25166. *
  25167. * @augments TempNode
  25168. */
  25169. class PassNode extends TempNode {
  25170. static get type() {
  25171. return 'PassNode';
  25172. }
  25173. /**
  25174. * Constructs a new pass node.
  25175. *
  25176. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  25177. * @param {Scene} scene - A reference to the scene.
  25178. * @param {Camera} camera - A reference to the camera.
  25179. * @param {Object} options - Options for the internal render target.
  25180. */
  25181. constructor( scope, scene, camera, options = {} ) {
  25182. super( 'vec4' );
  25183. /**
  25184. * The scope of the pass. The scope determines whether the node outputs color or depth.
  25185. *
  25186. * @type {('color'|'depth')}
  25187. */
  25188. this.scope = scope;
  25189. /**
  25190. * A reference to the scene.
  25191. *
  25192. * @type {Scene}
  25193. */
  25194. this.scene = scene;
  25195. /**
  25196. * A reference to the camera.
  25197. *
  25198. * @type {Camera}
  25199. */
  25200. this.camera = camera;
  25201. /**
  25202. * Options for the internal render target.
  25203. *
  25204. * @type {Object}
  25205. */
  25206. this.options = options;
  25207. /**
  25208. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  25209. *
  25210. * @private
  25211. * @type {number}
  25212. * @default 1
  25213. */
  25214. this._pixelRatio = 1;
  25215. /**
  25216. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  25217. * @private
  25218. * @type {number}
  25219. * @default 1
  25220. */
  25221. this._width = 1;
  25222. /**
  25223. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  25224. * @private
  25225. * @type {number}
  25226. * @default 1
  25227. */
  25228. this._height = 1;
  25229. const depthTexture = new DepthTexture();
  25230. depthTexture.isRenderTargetTexture = true;
  25231. //depthTexture.type = FloatType;
  25232. depthTexture.name = 'depth';
  25233. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  25234. renderTarget.texture.name = 'output';
  25235. renderTarget.depthTexture = depthTexture;
  25236. /**
  25237. * The pass's render target.
  25238. *
  25239. * @type {RenderTarget}
  25240. */
  25241. this.renderTarget = renderTarget;
  25242. /**
  25243. * A dictionary holding the internal result textures.
  25244. *
  25245. * @private
  25246. * @type {Object<string, Texture>}
  25247. */
  25248. this._textures = {
  25249. output: renderTarget.texture,
  25250. depth: depthTexture
  25251. };
  25252. /**
  25253. * A dictionary holding the internal texture nodes.
  25254. *
  25255. * @private
  25256. * @type {Object<string, TextureNode>}
  25257. */
  25258. this._textureNodes = {};
  25259. /**
  25260. * A dictionary holding the internal depth nodes.
  25261. *
  25262. * @private
  25263. * @type {Object}
  25264. */
  25265. this._linearDepthNodes = {};
  25266. /**
  25267. * A dictionary holding the internal viewZ nodes.
  25268. *
  25269. * @private
  25270. * @type {Object}
  25271. */
  25272. this._viewZNodes = {};
  25273. /**
  25274. * A dictionary holding the texture data of the previous frame.
  25275. * Used for computing velocity/motion vectors.
  25276. *
  25277. * @private
  25278. * @type {Object<string, Texture>}
  25279. */
  25280. this._previousTextures = {};
  25281. /**
  25282. * A dictionary holding the texture nodes of the previous frame.
  25283. * Used for computing velocity/motion vectors.
  25284. *
  25285. * @private
  25286. * @type {Object<string, TextureNode>}
  25287. */
  25288. this._previousTextureNodes = {};
  25289. /**
  25290. * The `near` property of the camera as a uniform.
  25291. *
  25292. * @private
  25293. * @type {UniformNode}
  25294. */
  25295. this._cameraNear = uniform( 0 );
  25296. /**
  25297. * The `far` property of the camera as a uniform.
  25298. *
  25299. * @private
  25300. * @type {UniformNode}
  25301. */
  25302. this._cameraFar = uniform( 0 );
  25303. /**
  25304. * A MRT node configuring the MRT settings.
  25305. *
  25306. * @private
  25307. * @type {?MRTNode}
  25308. * @default null
  25309. */
  25310. this._mrt = null;
  25311. /**
  25312. * Layer object for configuring the camera that is used
  25313. * to produce the pass.
  25314. *
  25315. * @private
  25316. * @type {?Layers}
  25317. * @default null
  25318. */
  25319. this._layers = null;
  25320. /**
  25321. * Scales the resolution of the internal render target.
  25322. *
  25323. * @private
  25324. * @type {number}
  25325. * @default 1
  25326. */
  25327. this._resolution = 1;
  25328. /**
  25329. * Custom viewport definition.
  25330. *
  25331. * @private
  25332. * @type {?Vector4}
  25333. * @default null
  25334. */
  25335. this._viewport = null;
  25336. /**
  25337. * Custom scissor definition.
  25338. *
  25339. * @private
  25340. * @type {?Vector4}
  25341. * @default null
  25342. */
  25343. this._scissor = null;
  25344. /**
  25345. * This flag can be used for type testing.
  25346. *
  25347. * @type {boolean}
  25348. * @readonly
  25349. * @default true
  25350. */
  25351. this.isPassNode = true;
  25352. /**
  25353. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  25354. * scene once per frame in its {@link PassNode#updateBefore} method.
  25355. *
  25356. * @type {string}
  25357. * @default 'frame'
  25358. */
  25359. this.updateBeforeType = NodeUpdateType.FRAME;
  25360. /**
  25361. * This flag is used for global cache.
  25362. *
  25363. * @type {boolean}
  25364. * @default true
  25365. */
  25366. this.global = true;
  25367. }
  25368. /**
  25369. * Sets the resolution for the pass.
  25370. * The resolution is a factor that is multiplied with the renderer's width and height.
  25371. *
  25372. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  25373. * @return {PassNode} A reference to this pass.
  25374. */
  25375. setResolution( resolution ) {
  25376. this._resolution = resolution;
  25377. return this;
  25378. }
  25379. /**
  25380. * Gets the current resolution of the pass.
  25381. *
  25382. * @return {number} The current resolution. A value of `1` means full resolution.
  25383. */
  25384. getResolution() {
  25385. return this._resolution;
  25386. }
  25387. /**
  25388. * Sets the layer configuration that should be used when rendering the pass.
  25389. *
  25390. * @param {Layers} layers - The layers object to set.
  25391. * @return {PassNode} A reference to this pass.
  25392. */
  25393. setLayers( layers ) {
  25394. this._layers = layers;
  25395. return this;
  25396. }
  25397. /**
  25398. * Gets the current layer configuration of the pass.
  25399. *
  25400. * @return {?Layers} .
  25401. */
  25402. getLayers() {
  25403. return this._layers;
  25404. }
  25405. /**
  25406. * Sets the given MRT node to setup MRT for this pass.
  25407. *
  25408. * @param {MRTNode} mrt - The MRT object.
  25409. * @return {PassNode} A reference to this pass.
  25410. */
  25411. setMRT( mrt ) {
  25412. this._mrt = mrt;
  25413. return this;
  25414. }
  25415. /**
  25416. * Returns the current MRT node.
  25417. *
  25418. * @return {MRTNode} The current MRT node.
  25419. */
  25420. getMRT() {
  25421. return this._mrt;
  25422. }
  25423. /**
  25424. * Returns the texture for the given output name.
  25425. *
  25426. * @param {string} name - The output name to get the texture for.
  25427. * @return {Texture} The texture.
  25428. */
  25429. getTexture( name ) {
  25430. let texture = this._textures[ name ];
  25431. if ( texture === undefined ) {
  25432. const refTexture = this.renderTarget.texture;
  25433. texture = refTexture.clone();
  25434. texture.name = name;
  25435. this._textures[ name ] = texture;
  25436. this.renderTarget.textures.push( texture );
  25437. }
  25438. return texture;
  25439. }
  25440. /**
  25441. * Returns the texture holding the data of the previous frame for the given output name.
  25442. *
  25443. * @param {string} name - The output name to get the texture for.
  25444. * @return {Texture} The texture holding the data of the previous frame.
  25445. */
  25446. getPreviousTexture( name ) {
  25447. let texture = this._previousTextures[ name ];
  25448. if ( texture === undefined ) {
  25449. texture = this.getTexture( name ).clone();
  25450. this._previousTextures[ name ] = texture;
  25451. }
  25452. return texture;
  25453. }
  25454. /**
  25455. * Switches current and previous textures for the given output name.
  25456. *
  25457. * @param {string} name - The output name.
  25458. */
  25459. toggleTexture( name ) {
  25460. const prevTexture = this._previousTextures[ name ];
  25461. if ( prevTexture !== undefined ) {
  25462. const texture = this._textures[ name ];
  25463. const index = this.renderTarget.textures.indexOf( texture );
  25464. this.renderTarget.textures[ index ] = prevTexture;
  25465. this._textures[ name ] = prevTexture;
  25466. this._previousTextures[ name ] = texture;
  25467. this._textureNodes[ name ].updateTexture();
  25468. this._previousTextureNodes[ name ].updateTexture();
  25469. }
  25470. }
  25471. /**
  25472. * Returns the texture node for the given output name.
  25473. *
  25474. * @param {string} [name='output'] - The output name to get the texture node for.
  25475. * @return {TextureNode} The texture node.
  25476. */
  25477. getTextureNode( name = 'output' ) {
  25478. let textureNode = this._textureNodes[ name ];
  25479. if ( textureNode === undefined ) {
  25480. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  25481. textureNode.updateTexture();
  25482. this._textureNodes[ name ] = textureNode;
  25483. }
  25484. return textureNode;
  25485. }
  25486. /**
  25487. * Returns the previous texture node for the given output name.
  25488. *
  25489. * @param {string} [name='output'] - The output name to get the previous texture node for.
  25490. * @return {TextureNode} The previous texture node.
  25491. */
  25492. getPreviousTextureNode( name = 'output' ) {
  25493. let textureNode = this._previousTextureNodes[ name ];
  25494. if ( textureNode === undefined ) {
  25495. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  25496. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  25497. textureNode.updateTexture();
  25498. this._previousTextureNodes[ name ] = textureNode;
  25499. }
  25500. return textureNode;
  25501. }
  25502. /**
  25503. * Returns a viewZ node of this pass.
  25504. *
  25505. * @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.
  25506. * @return {Node} The viewZ node.
  25507. */
  25508. getViewZNode( name = 'depth' ) {
  25509. let viewZNode = this._viewZNodes[ name ];
  25510. if ( viewZNode === undefined ) {
  25511. const cameraNear = this._cameraNear;
  25512. const cameraFar = this._cameraFar;
  25513. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  25514. }
  25515. return viewZNode;
  25516. }
  25517. /**
  25518. * Returns a linear depth node of this pass.
  25519. *
  25520. * @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.
  25521. * @return {Node} The linear depth node.
  25522. */
  25523. getLinearDepthNode( name = 'depth' ) {
  25524. let linearDepthNode = this._linearDepthNodes[ name ];
  25525. if ( linearDepthNode === undefined ) {
  25526. const cameraNear = this._cameraNear;
  25527. const cameraFar = this._cameraFar;
  25528. const viewZNode = this.getViewZNode( name );
  25529. // TODO: just if ( builder.camera.isPerspectiveCamera )
  25530. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  25531. }
  25532. return linearDepthNode;
  25533. }
  25534. /**
  25535. * Precompiles the pass.
  25536. *
  25537. * Note that this method must be called after the pass configuartion is complete.
  25538. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  25539. *
  25540. * @async
  25541. * @param {Renderer} renderer - The renderer.
  25542. * @return {Promise} A Promise that resolves when the compile has been finished.
  25543. * @see {@link Renderer#compileAsync}
  25544. */
  25545. async compileAsync( renderer ) {
  25546. const currentRenderTarget = renderer.getRenderTarget();
  25547. const currentMRT = renderer.getMRT();
  25548. renderer.setRenderTarget( this.renderTarget );
  25549. renderer.setMRT( this._mrt );
  25550. await renderer.compileAsync( this.scene, this.camera );
  25551. renderer.setRenderTarget( currentRenderTarget );
  25552. renderer.setMRT( currentMRT );
  25553. }
  25554. setup( { renderer } ) {
  25555. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  25556. this.renderTarget.texture.type = renderer.getColorBufferType();
  25557. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  25558. }
  25559. updateBefore( frame ) {
  25560. const { renderer } = frame;
  25561. const { scene } = this;
  25562. let camera;
  25563. let pixelRatio;
  25564. const outputRenderTarget = renderer.getOutputRenderTarget();
  25565. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  25566. pixelRatio = 1;
  25567. camera = renderer.xr.getCamera();
  25568. renderer.xr.updateCamera( camera );
  25569. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  25570. } else {
  25571. camera = this.camera;
  25572. pixelRatio = renderer.getPixelRatio();
  25573. renderer.getSize( _size );
  25574. }
  25575. this._pixelRatio = pixelRatio;
  25576. this.setSize( _size.width, _size.height );
  25577. const currentRenderTarget = renderer.getRenderTarget();
  25578. const currentMRT = renderer.getMRT();
  25579. const currentMask = camera.layers.mask;
  25580. this._cameraNear.value = camera.near;
  25581. this._cameraFar.value = camera.far;
  25582. if ( this._layers !== null ) {
  25583. camera.layers.mask = this._layers.mask;
  25584. }
  25585. for ( const name in this._previousTextures ) {
  25586. this.toggleTexture( name );
  25587. }
  25588. renderer.setRenderTarget( this.renderTarget );
  25589. renderer.setMRT( this._mrt );
  25590. renderer.render( scene, camera );
  25591. renderer.setRenderTarget( currentRenderTarget );
  25592. renderer.setMRT( currentMRT );
  25593. camera.layers.mask = currentMask;
  25594. }
  25595. /**
  25596. * Sets the size of the pass's render target. Honors the pixel ratio.
  25597. *
  25598. * @param {number} width - The width to set.
  25599. * @param {number} height - The height to set.
  25600. */
  25601. setSize( width, height ) {
  25602. this._width = width;
  25603. this._height = height;
  25604. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  25605. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  25606. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25607. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  25608. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  25609. }
  25610. /**
  25611. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  25612. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25613. * with `null` as the single argument.
  25614. *
  25615. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  25616. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  25617. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  25618. * @param {number} width - The width of the scissor box in logical pixel unit.
  25619. * @param {number} height - The height of the scissor box in logical pixel unit.
  25620. */
  25621. setScissor( x, y, width, height ) {
  25622. if ( x === null ) {
  25623. this._scissor = null;
  25624. } else {
  25625. if ( this._scissor === null ) this._scissor = new Vector4();
  25626. if ( x.isVector4 ) {
  25627. this._scissor.copy( x );
  25628. } else {
  25629. this._scissor.set( x, y, width, height );
  25630. }
  25631. this._scissor.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25632. }
  25633. }
  25634. /**
  25635. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  25636. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25637. * with `null` as the single argument.
  25638. *
  25639. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25640. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25641. * @param {number} width - The width of the viewport in logical pixel unit.
  25642. * @param {number} height - The height of the viewport in logical pixel unit.
  25643. */
  25644. setViewport( x, y, width, height ) {
  25645. if ( x === null ) {
  25646. this._viewport = null;
  25647. } else {
  25648. if ( this._viewport === null ) this._viewport = new Vector4();
  25649. if ( x.isVector4 ) {
  25650. this._viewport.copy( x );
  25651. } else {
  25652. this._viewport.set( x, y, width, height );
  25653. }
  25654. this._viewport.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25655. }
  25656. }
  25657. /**
  25658. * Sets the pixel ratio the pass's render target and updates the size.
  25659. *
  25660. * @param {number} pixelRatio - The pixel ratio to set.
  25661. */
  25662. setPixelRatio( pixelRatio ) {
  25663. this._pixelRatio = pixelRatio;
  25664. this.setSize( this._width, this._height );
  25665. }
  25666. /**
  25667. * Frees internal resources. Should be called when the node is no longer in use.
  25668. */
  25669. dispose() {
  25670. this.renderTarget.dispose();
  25671. }
  25672. }
  25673. /**
  25674. * @static
  25675. * @type {'color'}
  25676. * @default 'color'
  25677. */
  25678. PassNode.COLOR = 'color';
  25679. /**
  25680. * @static
  25681. * @type {'depth'}
  25682. * @default 'depth'
  25683. */
  25684. PassNode.DEPTH = 'depth';
  25685. /**
  25686. * TSL function for creating a pass node.
  25687. *
  25688. * @tsl
  25689. * @function
  25690. * @param {Scene} scene - A reference to the scene.
  25691. * @param {Camera} camera - A reference to the camera.
  25692. * @param {Object} options - Options for the internal render target.
  25693. * @returns {PassNode}
  25694. */
  25695. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  25696. /**
  25697. * TSL function for creating a pass texture node.
  25698. *
  25699. * @tsl
  25700. * @function
  25701. * @param {PassNode} pass - The pass node.
  25702. * @param {Texture} texture - The output texture.
  25703. * @returns {PassTextureNode}
  25704. */
  25705. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  25706. /**
  25707. * TSL function for creating a depth pass node.
  25708. *
  25709. * @tsl
  25710. * @function
  25711. * @param {Scene} scene - A reference to the scene.
  25712. * @param {Camera} camera - A reference to the camera.
  25713. * @param {Object} options - Options for the internal render target.
  25714. * @returns {PassNode}
  25715. */
  25716. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  25717. /**
  25718. * Represents a render pass for producing a toon outline effect on compatible objects.
  25719. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  25720. * will receive the outline.
  25721. *
  25722. * ```js
  25723. * const postProcessing = new PostProcessing( renderer );
  25724. *
  25725. * const scenePass = toonOutlinePass( scene, camera );
  25726. *
  25727. * postProcessing.outputNode = scenePass;
  25728. * ```
  25729. * @augments PassNode
  25730. */
  25731. class ToonOutlinePassNode extends PassNode {
  25732. static get type() {
  25733. return 'ToonOutlinePassNode';
  25734. }
  25735. /**
  25736. * Constructs a new outline pass node.
  25737. *
  25738. * @param {Scene} scene - A reference to the scene.
  25739. * @param {Camera} camera - A reference to the camera.
  25740. * @param {Node} colorNode - Defines the outline's color.
  25741. * @param {Node} thicknessNode - Defines the outline's thickness.
  25742. * @param {Node} alphaNode - Defines the outline's alpha.
  25743. */
  25744. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  25745. super( PassNode.COLOR, scene, camera );
  25746. /**
  25747. * Defines the outline's color.
  25748. *
  25749. * @type {Node}
  25750. */
  25751. this.colorNode = colorNode;
  25752. /**
  25753. * Defines the outline's thickness.
  25754. *
  25755. * @type {Node}
  25756. */
  25757. this.thicknessNode = thicknessNode;
  25758. /**
  25759. * Defines the outline's alpha.
  25760. *
  25761. * @type {Node}
  25762. */
  25763. this.alphaNode = alphaNode;
  25764. /**
  25765. * An internal material cache.
  25766. *
  25767. * @private
  25768. * @type {WeakMap<Material, NodeMaterial>}
  25769. */
  25770. this._materialCache = new WeakMap();
  25771. }
  25772. updateBefore( frame ) {
  25773. const { renderer } = frame;
  25774. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25775. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  25776. // only render outline for supported materials
  25777. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  25778. if ( material.wireframe === false ) {
  25779. const outlineMaterial = this._getOutlineMaterial( material );
  25780. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  25781. }
  25782. }
  25783. // default
  25784. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  25785. } );
  25786. super.updateBefore( frame );
  25787. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25788. }
  25789. /**
  25790. * Creates the material used for outline rendering.
  25791. *
  25792. * @private
  25793. * @return {NodeMaterial} The outline material.
  25794. */
  25795. _createMaterial() {
  25796. const material = new NodeMaterial();
  25797. material.isMeshToonOutlineMaterial = true;
  25798. material.name = 'Toon_Outline';
  25799. material.side = BackSide;
  25800. // vertex node
  25801. const outlineNormal = normalLocal.negate();
  25802. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  25803. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  25804. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  25805. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  25806. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  25807. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  25808. // color node
  25809. material.colorNode = vec4( this.colorNode, this.alphaNode );
  25810. return material;
  25811. }
  25812. /**
  25813. * For the given toon material, this method returns a corresponding
  25814. * outline material.
  25815. *
  25816. * @private
  25817. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  25818. * @return {NodeMaterial} The outline material.
  25819. */
  25820. _getOutlineMaterial( originalMaterial ) {
  25821. let outlineMaterial = this._materialCache.get( originalMaterial );
  25822. if ( outlineMaterial === undefined ) {
  25823. outlineMaterial = this._createMaterial();
  25824. this._materialCache.set( originalMaterial, outlineMaterial );
  25825. }
  25826. return outlineMaterial;
  25827. }
  25828. }
  25829. /**
  25830. * TSL function for creating a toon outline pass node.
  25831. *
  25832. * @tsl
  25833. * @function
  25834. * @param {Scene} scene - A reference to the scene.
  25835. * @param {Camera} camera - A reference to the camera.
  25836. * @param {Color} color - Defines the outline's color.
  25837. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  25838. * @param {number} [alpha=1] - Defines the outline's alpha.
  25839. * @returns {ToonOutlinePassNode}
  25840. */
  25841. 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 ) ) );
  25842. /**
  25843. * Linear tone mapping, exposure only.
  25844. *
  25845. * @tsl
  25846. * @function
  25847. * @param {Node<vec3>} color - The color that should be tone mapped.
  25848. * @param {Node<float>} exposure - The exposure.
  25849. * @return {Node<vec3>} The tone mapped color.
  25850. */
  25851. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25852. return color.mul( exposure ).clamp();
  25853. } ).setLayout( {
  25854. name: 'linearToneMapping',
  25855. type: 'vec3',
  25856. inputs: [
  25857. { name: 'color', type: 'vec3' },
  25858. { name: 'exposure', type: 'float' }
  25859. ]
  25860. } );
  25861. /**
  25862. * Reinhard tone mapping.
  25863. *
  25864. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  25865. *
  25866. * @tsl
  25867. * @function
  25868. * @param {Node<vec3>} color - The color that should be tone mapped.
  25869. * @param {Node<float>} exposure - The exposure.
  25870. * @return {Node<vec3>} The tone mapped color.
  25871. */
  25872. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25873. color = color.mul( exposure );
  25874. return color.div( color.add( 1.0 ) ).clamp();
  25875. } ).setLayout( {
  25876. name: 'reinhardToneMapping',
  25877. type: 'vec3',
  25878. inputs: [
  25879. { name: 'color', type: 'vec3' },
  25880. { name: 'exposure', type: 'float' }
  25881. ]
  25882. } );
  25883. /**
  25884. * Cineon tone mapping.
  25885. *
  25886. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  25887. *
  25888. * @tsl
  25889. * @function
  25890. * @param {Node<vec3>} color - The color that should be tone mapped.
  25891. * @param {Node<float>} exposure - The exposure.
  25892. * @return {Node<vec3>} The tone mapped color.
  25893. */
  25894. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25895. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  25896. color = color.mul( exposure );
  25897. color = color.sub( 0.004 ).max( 0.0 );
  25898. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  25899. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  25900. return a.div( b ).pow( 2.2 );
  25901. } ).setLayout( {
  25902. name: 'cineonToneMapping',
  25903. type: 'vec3',
  25904. inputs: [
  25905. { name: 'color', type: 'vec3' },
  25906. { name: 'exposure', type: 'float' }
  25907. ]
  25908. } );
  25909. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  25910. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25911. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  25912. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  25913. return a.div( b );
  25914. } );
  25915. /**
  25916. * ACESFilmic tone mapping.
  25917. *
  25918. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  25919. *
  25920. * @tsl
  25921. * @function
  25922. * @param {Node<vec3>} color - The color that should be tone mapped.
  25923. * @param {Node<float>} exposure - The exposure.
  25924. * @return {Node<vec3>} The tone mapped color.
  25925. */
  25926. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25927. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  25928. const ACESInputMat = mat3(
  25929. 0.59719, 0.35458, 0.04823,
  25930. 0.07600, 0.90834, 0.01566,
  25931. 0.02840, 0.13383, 0.83777
  25932. );
  25933. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  25934. const ACESOutputMat = mat3(
  25935. 1.60475, -0.53108, -0.07367,
  25936. -0.10208, 1.10813, -605e-5,
  25937. -327e-5, -0.07276, 1.07602
  25938. );
  25939. color = color.mul( exposure ).div( 0.6 );
  25940. color = ACESInputMat.mul( color );
  25941. // Apply RRT and ODT
  25942. color = RRTAndODTFit( color );
  25943. color = ACESOutputMat.mul( color );
  25944. // Clamp to [0, 1]
  25945. return color.clamp();
  25946. } ).setLayout( {
  25947. name: 'acesFilmicToneMapping',
  25948. type: 'vec3',
  25949. inputs: [
  25950. { name: 'color', type: 'vec3' },
  25951. { name: 'exposure', type: 'float' }
  25952. ]
  25953. } );
  25954. 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 ) );
  25955. 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 ) );
  25956. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25957. const x = vec3( x_immutable ).toVar();
  25958. const x2 = vec3( x.mul( x ) ).toVar();
  25959. const x4 = vec3( x2.mul( x2 ) ).toVar();
  25960. 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 ) ) ) );
  25961. } );
  25962. /**
  25963. * AgX tone mapping.
  25964. *
  25965. * @tsl
  25966. * @function
  25967. * @param {Node<vec3>} color - The color that should be tone mapped.
  25968. * @param {Node<float>} exposure - The exposure.
  25969. * @return {Node<vec3>} The tone mapped color.
  25970. */
  25971. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25972. const colortone = vec3( color ).toVar();
  25973. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  25974. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  25975. const AgxMinEv = float( -12.47393 );
  25976. const AgxMaxEv = float( 4.026069 );
  25977. colortone.mulAssign( exposure );
  25978. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  25979. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  25980. colortone.assign( max$1( colortone, 1e-10 ) );
  25981. colortone.assign( log2( colortone ) );
  25982. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  25983. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25984. colortone.assign( agxDefaultContrastApprox( colortone ) );
  25985. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  25986. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  25987. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  25988. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25989. return colortone;
  25990. } ).setLayout( {
  25991. name: 'agxToneMapping',
  25992. type: 'vec3',
  25993. inputs: [
  25994. { name: 'color', type: 'vec3' },
  25995. { name: 'exposure', type: 'float' }
  25996. ]
  25997. } );
  25998. /**
  25999. * Neutral tone mapping.
  26000. *
  26001. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  26002. *
  26003. * @tsl
  26004. * @function
  26005. * @param {Node<vec3>} color - The color that should be tone mapped.
  26006. * @param {Node<float>} exposure - The exposure.
  26007. * @return {Node<vec3>} The tone mapped color.
  26008. */
  26009. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26010. const StartCompression = float( 0.8 - 0.04 );
  26011. const Desaturation = float( 0.15 );
  26012. color = color.mul( exposure );
  26013. const x = min$1( color.r, min$1( color.g, color.b ) );
  26014. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  26015. color.subAssign( offset );
  26016. const peak = max$1( color.r, max$1( color.g, color.b ) );
  26017. If( peak.lessThan( StartCompression ), () => {
  26018. return color;
  26019. } );
  26020. const d = sub( 1, StartCompression );
  26021. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  26022. color.mulAssign( newPeak.div( peak ) );
  26023. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  26024. return mix( color, vec3( newPeak ), g );
  26025. } ).setLayout( {
  26026. name: 'neutralToneMapping',
  26027. type: 'vec3',
  26028. inputs: [
  26029. { name: 'color', type: 'vec3' },
  26030. { name: 'exposure', type: 'float' }
  26031. ]
  26032. } );
  26033. /**
  26034. * This class represents native code sections. It is the base
  26035. * class for modules like {@link FunctionNode} which allows to implement
  26036. * functions with native shader languages.
  26037. *
  26038. * @augments Node
  26039. */
  26040. class CodeNode extends Node {
  26041. static get type() {
  26042. return 'CodeNode';
  26043. }
  26044. /**
  26045. * Constructs a new code node.
  26046. *
  26047. * @param {string} [code=''] - The native code.
  26048. * @param {Array<Node>} [includes=[]] - An array of includes.
  26049. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26050. */
  26051. constructor( code = '', includes = [], language = '' ) {
  26052. super( 'code' );
  26053. /**
  26054. * This flag can be used for type testing.
  26055. *
  26056. * @type {boolean}
  26057. * @readonly
  26058. * @default true
  26059. */
  26060. this.isCodeNode = true;
  26061. /**
  26062. * This flag is used for global cache.
  26063. *
  26064. * @type {boolean}
  26065. * @default true
  26066. */
  26067. this.global = true;
  26068. /**
  26069. * The native code.
  26070. *
  26071. * @type {string}
  26072. * @default ''
  26073. */
  26074. this.code = code;
  26075. /**
  26076. * An array of includes
  26077. *
  26078. * @type {Array<Node>}
  26079. * @default []
  26080. */
  26081. this.includes = includes;
  26082. /**
  26083. * The used language.
  26084. *
  26085. * @type {('js'|'wgsl'|'glsl')}
  26086. * @default ''
  26087. */
  26088. this.language = language;
  26089. }
  26090. /**
  26091. * Sets the includes of this code node.
  26092. *
  26093. * @param {Array<Node>} includes - The includes to set.
  26094. * @return {CodeNode} A reference to this node.
  26095. */
  26096. setIncludes( includes ) {
  26097. this.includes = includes;
  26098. return this;
  26099. }
  26100. /**
  26101. * Returns the includes of this code node.
  26102. *
  26103. * @param {NodeBuilder} builder - The current node builder.
  26104. * @return {Array<Node>} The includes.
  26105. */
  26106. getIncludes( /*builder*/ ) {
  26107. return this.includes;
  26108. }
  26109. generate( builder ) {
  26110. const includes = this.getIncludes( builder );
  26111. for ( const include of includes ) {
  26112. include.build( builder );
  26113. }
  26114. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  26115. nodeCode.code = this.code;
  26116. return nodeCode.code;
  26117. }
  26118. serialize( data ) {
  26119. super.serialize( data );
  26120. data.code = this.code;
  26121. data.language = this.language;
  26122. }
  26123. deserialize( data ) {
  26124. super.deserialize( data );
  26125. this.code = data.code;
  26126. this.language = data.language;
  26127. }
  26128. }
  26129. /**
  26130. * TSL function for creating a code node.
  26131. *
  26132. * @tsl
  26133. * @function
  26134. * @param {string} [code] - The native code.
  26135. * @param {?Array<Node>} [includes=[]] - An array of includes.
  26136. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26137. * @returns {CodeNode}
  26138. */
  26139. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  26140. /**
  26141. * TSL function for creating a JS code node.
  26142. *
  26143. * @tsl
  26144. * @function
  26145. * @param {string} src - The native code.
  26146. * @param {Array<Node>} includes - An array of includes.
  26147. * @returns {CodeNode}
  26148. */
  26149. const js = ( src, includes ) => code( src, includes, 'js' );
  26150. /**
  26151. * TSL function for creating a WGSL code node.
  26152. *
  26153. * @tsl
  26154. * @function
  26155. * @param {string} src - The native code.
  26156. * @param {Array<Node>} includes - An array of includes.
  26157. * @returns {CodeNode}
  26158. */
  26159. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  26160. /**
  26161. * TSL function for creating a GLSL code node.
  26162. *
  26163. * @tsl
  26164. * @function
  26165. * @param {string} src - The native code.
  26166. * @param {Array<Node>} includes - An array of includes.
  26167. * @returns {CodeNode}
  26168. */
  26169. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  26170. /**
  26171. * This class represents a native shader function. It can be used to implement
  26172. * certain aspects of a node material with native shader code. There are two predefined
  26173. * TSL functions for easier usage.
  26174. *
  26175. * - `wgslFn`: Creates a WGSL function node.
  26176. * - `glslFn`: Creates a GLSL function node.
  26177. *
  26178. * A basic example with one include looks like so:
  26179. *
  26180. * ```js
  26181. * const desaturateWGSLFn = wgslFn( `
  26182. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  26183. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  26184. * return vec3<f32>( dot( lum, color ) );
  26185. * }`
  26186. *);
  26187. * const someWGSLFn = wgslFn( `
  26188. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  26189. * return desaturate( color );
  26190. * }
  26191. * `, [ desaturateWGSLFn ] );
  26192. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  26193. *```
  26194. * @augments CodeNode
  26195. */
  26196. class FunctionNode extends CodeNode {
  26197. static get type() {
  26198. return 'FunctionNode';
  26199. }
  26200. /**
  26201. * Constructs a new function node.
  26202. *
  26203. * @param {string} [code=''] - The native code.
  26204. * @param {Array<Node>} [includes=[]] - An array of includes.
  26205. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26206. */
  26207. constructor( code = '', includes = [], language = '' ) {
  26208. super( code, includes, language );
  26209. }
  26210. /**
  26211. * Returns the type of this function node.
  26212. *
  26213. * @param {NodeBuilder} builder - The current node builder.
  26214. * @return {string} The type.
  26215. */
  26216. getNodeType( builder ) {
  26217. return this.getNodeFunction( builder ).type;
  26218. }
  26219. /**
  26220. * Returns the type of a member of this function node.
  26221. *
  26222. * @param {NodeBuilder} builder - The current node builder.
  26223. * @param {string} name - The name of the member.
  26224. * @return {string} The type of the member.
  26225. */
  26226. getMemberType( builder, name ) {
  26227. const type = this.getNodeType( builder );
  26228. const structType = builder.getStructTypeNode( type );
  26229. return structType.getMemberType( builder, name );
  26230. }
  26231. /**
  26232. * Returns the inputs of this function node.
  26233. *
  26234. * @param {NodeBuilder} builder - The current node builder.
  26235. * @return {Array<NodeFunctionInput>} The inputs.
  26236. */
  26237. getInputs( builder ) {
  26238. return this.getNodeFunction( builder ).inputs;
  26239. }
  26240. /**
  26241. * Returns the node function for this function node.
  26242. *
  26243. * @param {NodeBuilder} builder - The current node builder.
  26244. * @return {NodeFunction} The node function.
  26245. */
  26246. getNodeFunction( builder ) {
  26247. const nodeData = builder.getDataFromNode( this );
  26248. let nodeFunction = nodeData.nodeFunction;
  26249. if ( nodeFunction === undefined ) {
  26250. nodeFunction = builder.parser.parseFunction( this.code );
  26251. nodeData.nodeFunction = nodeFunction;
  26252. }
  26253. return nodeFunction;
  26254. }
  26255. generate( builder, output ) {
  26256. super.generate( builder );
  26257. const nodeFunction = this.getNodeFunction( builder );
  26258. const name = nodeFunction.name;
  26259. const type = nodeFunction.type;
  26260. const nodeCode = builder.getCodeFromNode( this, type );
  26261. if ( name !== '' ) {
  26262. // use a custom property name
  26263. nodeCode.name = name;
  26264. }
  26265. const propertyName = builder.getPropertyName( nodeCode );
  26266. const code = this.getNodeFunction( builder ).getCode( propertyName );
  26267. nodeCode.code = code + '\n';
  26268. if ( output === 'property' ) {
  26269. return propertyName;
  26270. } else {
  26271. return builder.format( `${ propertyName }()`, type, output );
  26272. }
  26273. }
  26274. }
  26275. const nativeFn = ( code, includes = [], language = '' ) => {
  26276. for ( let i = 0; i < includes.length; i ++ ) {
  26277. const include = includes[ i ];
  26278. // TSL Function: glslFn, wgslFn
  26279. if ( typeof include === 'function' ) {
  26280. includes[ i ] = include.functionNode;
  26281. }
  26282. }
  26283. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  26284. const fn = ( ...params ) => functionNode.call( ...params );
  26285. fn.functionNode = functionNode;
  26286. return fn;
  26287. };
  26288. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  26289. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  26290. /**
  26291. * `ScriptableNode` uses this class to manage script inputs and outputs.
  26292. *
  26293. * @augments Node
  26294. */
  26295. class ScriptableValueNode extends Node {
  26296. static get type() {
  26297. return 'ScriptableValueNode';
  26298. }
  26299. /**
  26300. * Constructs a new scriptable node.
  26301. *
  26302. * @param {any} [value=null] - The value.
  26303. */
  26304. constructor( value = null ) {
  26305. super();
  26306. /**
  26307. * A reference to the value.
  26308. *
  26309. * @private
  26310. * @default null
  26311. */
  26312. this._value = value;
  26313. /**
  26314. * Depending on the type of `_value`, this property might cache parsed data.
  26315. *
  26316. * @private
  26317. * @default null
  26318. */
  26319. this._cache = null;
  26320. /**
  26321. * If this node represents an input, this property represents the input type.
  26322. *
  26323. * @type {?string}
  26324. * @default null
  26325. */
  26326. this.inputType = null;
  26327. /**
  26328. * If this node represents an output, this property represents the output type.
  26329. *
  26330. * @type {?string}
  26331. * @default null
  26332. */
  26333. this.outputType = null;
  26334. /**
  26335. * An event dispatcher for managing events.
  26336. *
  26337. * @type {EventDispatcher}
  26338. */
  26339. this.events = new EventDispatcher();
  26340. /**
  26341. * This flag can be used for type testing.
  26342. *
  26343. * @type {boolean}
  26344. * @readonly
  26345. * @default true
  26346. */
  26347. this.isScriptableValueNode = true;
  26348. }
  26349. /**
  26350. * Whether this node represents an output or not.
  26351. *
  26352. * @type {boolean}
  26353. * @readonly
  26354. * @default true
  26355. */
  26356. get isScriptableOutputNode() {
  26357. return this.outputType !== null;
  26358. }
  26359. set value( val ) {
  26360. if ( this._value === val ) return;
  26361. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  26362. URL.revokeObjectURL( this._cache );
  26363. this._cache = null;
  26364. }
  26365. this._value = val;
  26366. this.events.dispatchEvent( { type: 'change' } );
  26367. this.refresh();
  26368. }
  26369. /**
  26370. * The node's value.
  26371. *
  26372. * @type {any}
  26373. */
  26374. get value() {
  26375. return this._value;
  26376. }
  26377. /**
  26378. * Dispatches the `refresh` event.
  26379. */
  26380. refresh() {
  26381. this.events.dispatchEvent( { type: 'refresh' } );
  26382. }
  26383. /**
  26384. * The `value` property usually represents a node or even binary data in form of array buffers.
  26385. * In this case, this method tries to return the actual value behind the complex type.
  26386. *
  26387. * @return {any} The value.
  26388. */
  26389. getValue() {
  26390. const value = this.value;
  26391. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  26392. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  26393. } else if ( value && value.value !== null && value.value !== undefined && (
  26394. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  26395. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  26396. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  26397. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  26398. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  26399. ( this.inputType === 'Color' && value.value.isColor ) ||
  26400. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  26401. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  26402. ) ) {
  26403. return value.value;
  26404. }
  26405. return this._cache || value;
  26406. }
  26407. /**
  26408. * Overwritten since the node type is inferred from the value.
  26409. *
  26410. * @param {NodeBuilder} builder - The current node builder.
  26411. * @return {string} The node type.
  26412. */
  26413. getNodeType( builder ) {
  26414. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  26415. }
  26416. setup() {
  26417. return this.value && this.value.isNode ? this.value : float();
  26418. }
  26419. serialize( data ) {
  26420. super.serialize( data );
  26421. if ( this.value !== null ) {
  26422. if ( this.inputType === 'ArrayBuffer' ) {
  26423. data.value = arrayBufferToBase64( this.value );
  26424. } else {
  26425. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  26426. }
  26427. } else {
  26428. data.value = null;
  26429. }
  26430. data.inputType = this.inputType;
  26431. data.outputType = this.outputType;
  26432. }
  26433. deserialize( data ) {
  26434. super.deserialize( data );
  26435. let value = null;
  26436. if ( data.value !== null ) {
  26437. if ( data.inputType === 'ArrayBuffer' ) {
  26438. value = base64ToArrayBuffer( data.value );
  26439. } else if ( data.inputType === 'Texture' ) {
  26440. value = data.meta.textures[ data.value ];
  26441. } else {
  26442. value = data.meta.nodes[ data.value ] || null;
  26443. }
  26444. }
  26445. this.value = value;
  26446. this.inputType = data.inputType;
  26447. this.outputType = data.outputType;
  26448. }
  26449. }
  26450. /**
  26451. * TSL function for creating a scriptable value node.
  26452. *
  26453. * @tsl
  26454. * @function
  26455. * @param {any} [value] - The value.
  26456. * @returns {ScriptableValueNode}
  26457. */
  26458. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  26459. /**
  26460. * A Map-like data structure for managing resources of scriptable nodes.
  26461. *
  26462. * @augments Map
  26463. */
  26464. class Resources extends Map {
  26465. get( key, callback = null, ...params ) {
  26466. if ( this.has( key ) ) return super.get( key );
  26467. if ( callback !== null ) {
  26468. const value = callback( ...params );
  26469. this.set( key, value );
  26470. return value;
  26471. }
  26472. }
  26473. }
  26474. class Parameters {
  26475. constructor( scriptableNode ) {
  26476. this.scriptableNode = scriptableNode;
  26477. }
  26478. get parameters() {
  26479. return this.scriptableNode.parameters;
  26480. }
  26481. get layout() {
  26482. return this.scriptableNode.getLayout();
  26483. }
  26484. getInputLayout( id ) {
  26485. return this.scriptableNode.getInputLayout( id );
  26486. }
  26487. get( name ) {
  26488. const param = this.parameters[ name ];
  26489. const value = param ? param.getValue() : null;
  26490. return value;
  26491. }
  26492. }
  26493. /**
  26494. * Defines the resources (e.g. namespaces) of scriptable nodes.
  26495. *
  26496. * @type {Resources}
  26497. */
  26498. const ScriptableNodeResources = new Resources();
  26499. /**
  26500. * This type of node allows to implement nodes with custom scripts. The script
  26501. * section is represented as an instance of `CodeNode` written with JavaScript.
  26502. * The script itself must adhere to a specific structure.
  26503. *
  26504. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  26505. * - layout: The layout object defines the script's interface (inputs and outputs).
  26506. *
  26507. * ```js
  26508. * ScriptableNodeResources.set( 'TSL', TSL );
  26509. *
  26510. * const scriptableNode = scriptable( js( `
  26511. * layout = {
  26512. * outputType: 'node',
  26513. * elements: [
  26514. * { name: 'source', inputType: 'node' },
  26515. * ]
  26516. * };
  26517. *
  26518. * const { mul, oscSine } = TSL;
  26519. *
  26520. * function main() {
  26521. * const source = parameters.get( 'source' ) || float();
  26522. * return mul( source, oscSine() ) );
  26523. * }
  26524. *
  26525. * ` ) );
  26526. *
  26527. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  26528. *
  26529. * const material = new THREE.MeshBasicNodeMaterial();
  26530. * material.colorNode = scriptableNode;
  26531. * ```
  26532. *
  26533. * @augments Node
  26534. */
  26535. class ScriptableNode extends Node {
  26536. static get type() {
  26537. return 'ScriptableNode';
  26538. }
  26539. /**
  26540. * Constructs a new scriptable node.
  26541. *
  26542. * @param {?CodeNode} [codeNode=null] - The code node.
  26543. * @param {Object} [parameters={}] - The parameters definition.
  26544. */
  26545. constructor( codeNode = null, parameters = {} ) {
  26546. super();
  26547. /**
  26548. * The code node.
  26549. *
  26550. * @type {?CodeNode}
  26551. * @default null
  26552. */
  26553. this.codeNode = codeNode;
  26554. /**
  26555. * The parameters definition.
  26556. *
  26557. * @type {Object}
  26558. * @default {}
  26559. */
  26560. this.parameters = parameters;
  26561. this._local = new Resources();
  26562. this._output = scriptableValue( null );
  26563. this._outputs = {};
  26564. this._source = this.source;
  26565. this._method = null;
  26566. this._object = null;
  26567. this._value = null;
  26568. this._needsOutputUpdate = true;
  26569. this.onRefresh = this.onRefresh.bind( this );
  26570. /**
  26571. * This flag can be used for type testing.
  26572. *
  26573. * @type {boolean}
  26574. * @readonly
  26575. * @default true
  26576. */
  26577. this.isScriptableNode = true;
  26578. }
  26579. /**
  26580. * The source code of the scriptable node.
  26581. *
  26582. * @type {string}
  26583. */
  26584. get source() {
  26585. return this.codeNode ? this.codeNode.code : '';
  26586. }
  26587. /**
  26588. * Sets the reference of a local script variable.
  26589. *
  26590. * @param {string} name - The variable name.
  26591. * @param {Object} value - The reference to set.
  26592. * @return {Resources} The resource map
  26593. */
  26594. setLocal( name, value ) {
  26595. return this._local.set( name, value );
  26596. }
  26597. /**
  26598. * Gets the value of a local script variable.
  26599. *
  26600. * @param {string} name - The variable name.
  26601. * @return {Object} The value.
  26602. */
  26603. getLocal( name ) {
  26604. return this._local.get( name );
  26605. }
  26606. /**
  26607. * Event listener for the `refresh` event.
  26608. */
  26609. onRefresh() {
  26610. this._refresh();
  26611. }
  26612. /**
  26613. * Returns an input from the layout with the given id/name.
  26614. *
  26615. * @param {string} id - The id/name of the input.
  26616. * @return {Object} The element entry.
  26617. */
  26618. getInputLayout( id ) {
  26619. for ( const element of this.getLayout() ) {
  26620. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  26621. return element;
  26622. }
  26623. }
  26624. }
  26625. /**
  26626. * Returns an output from the layout with the given id/name.
  26627. *
  26628. * @param {string} id - The id/name of the output.
  26629. * @return {Object} The element entry.
  26630. */
  26631. getOutputLayout( id ) {
  26632. for ( const element of this.getLayout() ) {
  26633. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  26634. return element;
  26635. }
  26636. }
  26637. }
  26638. /**
  26639. * Defines a script output for the given name and value.
  26640. *
  26641. * @param {string} name - The name of the output.
  26642. * @param {Node} value - The node value.
  26643. * @return {ScriptableNode} A reference to this node.
  26644. */
  26645. setOutput( name, value ) {
  26646. const outputs = this._outputs;
  26647. if ( outputs[ name ] === undefined ) {
  26648. outputs[ name ] = scriptableValue( value );
  26649. } else {
  26650. outputs[ name ].value = value;
  26651. }
  26652. return this;
  26653. }
  26654. /**
  26655. * Returns a script output for the given name.
  26656. *
  26657. * @param {string} name - The name of the output.
  26658. * @return {ScriptableValueNode} The node value.
  26659. */
  26660. getOutput( name ) {
  26661. return this._outputs[ name ];
  26662. }
  26663. /**
  26664. * Returns a parameter for the given name
  26665. *
  26666. * @param {string} name - The name of the parameter.
  26667. * @return {ScriptableValueNode} The node value.
  26668. */
  26669. getParameter( name ) {
  26670. return this.parameters[ name ];
  26671. }
  26672. /**
  26673. * Sets a value for the given parameter name.
  26674. *
  26675. * @param {string} name - The parameter name.
  26676. * @param {any} value - The parameter value.
  26677. * @return {ScriptableNode} A reference to this node.
  26678. */
  26679. setParameter( name, value ) {
  26680. const parameters = this.parameters;
  26681. if ( value && value.isScriptableNode ) {
  26682. this.deleteParameter( name );
  26683. parameters[ name ] = value;
  26684. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  26685. } else if ( value && value.isScriptableValueNode ) {
  26686. this.deleteParameter( name );
  26687. parameters[ name ] = value;
  26688. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26689. } else if ( parameters[ name ] === undefined ) {
  26690. parameters[ name ] = scriptableValue( value );
  26691. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26692. } else {
  26693. parameters[ name ].value = value;
  26694. }
  26695. return this;
  26696. }
  26697. /**
  26698. * Returns the value of this node which is the value of
  26699. * the default output.
  26700. *
  26701. * @return {Node} The value.
  26702. */
  26703. getValue() {
  26704. return this.getDefaultOutput().getValue();
  26705. }
  26706. /**
  26707. * Deletes a parameter from the script.
  26708. *
  26709. * @param {string} name - The parameter to remove.
  26710. * @return {ScriptableNode} A reference to this node.
  26711. */
  26712. deleteParameter( name ) {
  26713. let valueNode = this.parameters[ name ];
  26714. if ( valueNode ) {
  26715. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26716. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  26717. }
  26718. return this;
  26719. }
  26720. /**
  26721. * Deletes all parameters from the script.
  26722. *
  26723. * @return {ScriptableNode} A reference to this node.
  26724. */
  26725. clearParameters() {
  26726. for ( const name of Object.keys( this.parameters ) ) {
  26727. this.deleteParameter( name );
  26728. }
  26729. this.needsUpdate = true;
  26730. return this;
  26731. }
  26732. /**
  26733. * Calls a function from the script.
  26734. *
  26735. * @param {string} name - The function name.
  26736. * @param {...any} params - A list of parameters.
  26737. * @return {any} The result of the function call.
  26738. */
  26739. call( name, ...params ) {
  26740. const object = this.getObject();
  26741. const method = object[ name ];
  26742. if ( typeof method === 'function' ) {
  26743. return method( ...params );
  26744. }
  26745. }
  26746. /**
  26747. * Asynchronously calls a function from the script.
  26748. *
  26749. * @param {string} name - The function name.
  26750. * @param {...any} params - A list of parameters.
  26751. * @return {Promise<any>} The result of the function call.
  26752. */
  26753. async callAsync( name, ...params ) {
  26754. const object = this.getObject();
  26755. const method = object[ name ];
  26756. if ( typeof method === 'function' ) {
  26757. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  26758. }
  26759. }
  26760. /**
  26761. * Overwritten since the node types is inferred from the script's output.
  26762. *
  26763. * @param {NodeBuilder} builder - The current node builder
  26764. * @return {string} The node type.
  26765. */
  26766. getNodeType( builder ) {
  26767. return this.getDefaultOutputNode().getNodeType( builder );
  26768. }
  26769. /**
  26770. * Refreshes the script node.
  26771. *
  26772. * @param {?string} [output=null] - An optional output.
  26773. */
  26774. refresh( output = null ) {
  26775. if ( output !== null ) {
  26776. this.getOutput( output ).refresh();
  26777. } else {
  26778. this._refresh();
  26779. }
  26780. }
  26781. /**
  26782. * Returns an object representation of the script.
  26783. *
  26784. * @return {Object} The result object.
  26785. */
  26786. getObject() {
  26787. if ( this.needsUpdate ) this.dispose();
  26788. if ( this._object !== null ) return this._object;
  26789. //
  26790. const refresh = () => this.refresh();
  26791. const setOutput = ( id, value ) => this.setOutput( id, value );
  26792. const parameters = new Parameters( this );
  26793. const THREE = ScriptableNodeResources.get( 'THREE' );
  26794. const TSL = ScriptableNodeResources.get( 'TSL' );
  26795. const method = this.getMethod();
  26796. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  26797. this._object = method( ...params );
  26798. const layout = this._object.layout;
  26799. if ( layout ) {
  26800. if ( layout.cache === false ) {
  26801. this._local.clear();
  26802. }
  26803. // default output
  26804. this._output.outputType = layout.outputType || null;
  26805. if ( Array.isArray( layout.elements ) ) {
  26806. for ( const element of layout.elements ) {
  26807. const id = element.id || element.name;
  26808. if ( element.inputType ) {
  26809. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  26810. this.getParameter( id ).inputType = element.inputType;
  26811. }
  26812. if ( element.outputType ) {
  26813. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  26814. this.getOutput( id ).outputType = element.outputType;
  26815. }
  26816. }
  26817. }
  26818. }
  26819. return this._object;
  26820. }
  26821. deserialize( data ) {
  26822. super.deserialize( data );
  26823. for ( const name in this.parameters ) {
  26824. let valueNode = this.parameters[ name ];
  26825. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26826. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  26827. }
  26828. }
  26829. /**
  26830. * Returns the layout of the script.
  26831. *
  26832. * @return {Object} The script's layout.
  26833. */
  26834. getLayout() {
  26835. return this.getObject().layout;
  26836. }
  26837. /**
  26838. * Returns default node output of the script.
  26839. *
  26840. * @return {Node} The default node output.
  26841. */
  26842. getDefaultOutputNode() {
  26843. const output = this.getDefaultOutput().value;
  26844. if ( output && output.isNode ) {
  26845. return output;
  26846. }
  26847. return float();
  26848. }
  26849. /**
  26850. * Returns default output of the script.
  26851. *
  26852. * @return {ScriptableValueNode} The default output.
  26853. */
  26854. getDefaultOutput() {
  26855. return this._exec()._output;
  26856. }
  26857. /**
  26858. * Returns a function created from the node's script.
  26859. *
  26860. * @return {Function} The function representing the node's code.
  26861. */
  26862. getMethod() {
  26863. if ( this.needsUpdate ) this.dispose();
  26864. if ( this._method !== null ) return this._method;
  26865. //
  26866. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  26867. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  26868. const properties = interfaceProps.join( ', ' );
  26869. const declarations = 'var ' + properties + '; var output = {};\n';
  26870. const returns = '\nreturn { ...output, ' + properties + ' };';
  26871. const code = declarations + this.codeNode.code + returns;
  26872. //
  26873. this._method = new Function( ...parametersProps, code );
  26874. return this._method;
  26875. }
  26876. /**
  26877. * Frees all internal resources.
  26878. */
  26879. dispose() {
  26880. if ( this._method === null ) return;
  26881. if ( this._object && typeof this._object.dispose === 'function' ) {
  26882. this._object.dispose();
  26883. }
  26884. this._method = null;
  26885. this._object = null;
  26886. this._source = null;
  26887. this._value = null;
  26888. this._needsOutputUpdate = true;
  26889. this._output.value = null;
  26890. this._outputs = {};
  26891. }
  26892. setup() {
  26893. return this.getDefaultOutputNode();
  26894. }
  26895. getCacheKey( force ) {
  26896. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  26897. for ( const param in this.parameters ) {
  26898. values.push( this.parameters[ param ].getCacheKey( force ) );
  26899. }
  26900. return hashArray( values );
  26901. }
  26902. set needsUpdate( value ) {
  26903. if ( value === true ) this.dispose();
  26904. }
  26905. get needsUpdate() {
  26906. return this.source !== this._source;
  26907. }
  26908. /**
  26909. * Executes the `main` function of the script.
  26910. *
  26911. * @private
  26912. * @return {ScriptableNode} A reference to this node.
  26913. */
  26914. _exec() {
  26915. if ( this.codeNode === null ) return this;
  26916. if ( this._needsOutputUpdate === true ) {
  26917. this._value = this.call( 'main' );
  26918. this._needsOutputUpdate = false;
  26919. }
  26920. this._output.value = this._value;
  26921. return this;
  26922. }
  26923. /**
  26924. * Executes the refresh.
  26925. *
  26926. * @private
  26927. */
  26928. _refresh() {
  26929. this.needsUpdate = true;
  26930. this._exec();
  26931. this._output.refresh();
  26932. }
  26933. }
  26934. /**
  26935. * TSL function for creating a scriptable node.
  26936. *
  26937. * @tsl
  26938. * @function
  26939. * @param {CodeNode} [codeNode] - The code node.
  26940. * @param {?Object} [parameters={}] - The parameters definition.
  26941. * @returns {ScriptableNode}
  26942. */
  26943. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  26944. /**
  26945. * Returns a node that represents the `z` coordinate in view space
  26946. * for the current fragment. It's a different representation of the
  26947. * default depth value.
  26948. *
  26949. * This value can be part of a computation that defines how the fog
  26950. * density increases when moving away from the camera.
  26951. *
  26952. * @param {NodeBuilder} builder - The current node builder.
  26953. * @return {Node} The viewZ node.
  26954. */
  26955. function getViewZNode( builder ) {
  26956. let viewZ;
  26957. const getViewZ = builder.context.getViewZ;
  26958. if ( getViewZ !== undefined ) {
  26959. viewZ = getViewZ( this );
  26960. }
  26961. return ( viewZ || positionView.z ).negate();
  26962. }
  26963. /**
  26964. * Constructs a new range factor node.
  26965. *
  26966. * @tsl
  26967. * @function
  26968. * @param {Node} near - Defines the near value.
  26969. * @param {Node} far - Defines the far value.
  26970. */
  26971. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  26972. const viewZ = getViewZNode( builder );
  26973. return smoothstep( near, far, viewZ );
  26974. } );
  26975. /**
  26976. * Represents an exponential squared fog. This type of fog gives
  26977. * a clear view near the camera and a faster than exponentially
  26978. * densening fog farther from the camera.
  26979. *
  26980. * @tsl
  26981. * @function
  26982. * @param {Node} density - Defines the fog density.
  26983. */
  26984. const densityFogFactor = Fn( ( [ density ], builder ) => {
  26985. const viewZ = getViewZNode( builder );
  26986. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  26987. } );
  26988. /**
  26989. * This class can be used to configure a fog for the scene.
  26990. * Nodes of this type are assigned to `Scene.fogNode`.
  26991. *
  26992. * @tsl
  26993. * @function
  26994. * @param {Node} color - Defines the color of the fog.
  26995. * @param {Node} factor - Defines how the fog is factored in the scene.
  26996. */
  26997. const fog = Fn( ( [ color, factor ] ) => {
  26998. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  26999. } );
  27000. // Deprecated
  27001. /**
  27002. * @tsl
  27003. * @function
  27004. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  27005. *
  27006. * @param {Node} color
  27007. * @param {Node} near
  27008. * @param {Node} far
  27009. * @returns {Function}
  27010. */
  27011. function rangeFog( color, near, far ) { // @deprecated, r171
  27012. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  27013. return fog( color, rangeFogFactor( near, far ) );
  27014. }
  27015. /**
  27016. * @tsl
  27017. * @function
  27018. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  27019. *
  27020. * @param {Node} color
  27021. * @param {Node} density
  27022. * @returns {Function}
  27023. */
  27024. function densityFog( color, density ) { // @deprecated, r171
  27025. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  27026. return fog( color, densityFogFactor( density ) );
  27027. }
  27028. let min = null;
  27029. let max = null;
  27030. /**
  27031. * `RangeNode` generates random instanced attribute data in a defined range.
  27032. * An exemplary use case for this utility node is to generate random per-instance
  27033. * colors:
  27034. * ```js
  27035. * const material = new MeshBasicNodeMaterial();
  27036. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  27037. * const mesh = new InstancedMesh( geometry, material, count );
  27038. * ```
  27039. * @augments Node
  27040. */
  27041. class RangeNode extends Node {
  27042. static get type() {
  27043. return 'RangeNode';
  27044. }
  27045. /**
  27046. * Constructs a new range node.
  27047. *
  27048. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27049. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27050. */
  27051. constructor( minNode = float(), maxNode = float() ) {
  27052. super();
  27053. /**
  27054. * A node defining the lower bound of the range.
  27055. *
  27056. * @type {Node<any>}
  27057. * @default float()
  27058. */
  27059. this.minNode = minNode;
  27060. /**
  27061. * A node defining the upper bound of the range.
  27062. *
  27063. * @type {Node<any>}
  27064. * @default float()
  27065. */
  27066. this.maxNode = maxNode;
  27067. }
  27068. /**
  27069. * Returns the vector length which is computed based on the range definition.
  27070. *
  27071. * @param {NodeBuilder} builder - The current node builder.
  27072. * @return {number} The vector length.
  27073. */
  27074. getVectorLength( builder ) {
  27075. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  27076. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  27077. return minLength > maxLength ? minLength : maxLength;
  27078. }
  27079. /**
  27080. * This method is overwritten since the node type is inferred from range definition.
  27081. *
  27082. * @param {NodeBuilder} builder - The current node builder.
  27083. * @return {string} The node type.
  27084. */
  27085. getNodeType( builder ) {
  27086. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  27087. }
  27088. setup( builder ) {
  27089. const object = builder.object;
  27090. let output = null;
  27091. if ( object.count > 1 ) {
  27092. const minValue = this.minNode.value;
  27093. const maxValue = this.maxNode.value;
  27094. const minLength = builder.getTypeLength( getValueType( minValue ) );
  27095. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  27096. min = min || new Vector4();
  27097. max = max || new Vector4();
  27098. min.setScalar( 0 );
  27099. max.setScalar( 0 );
  27100. if ( minLength === 1 ) min.setScalar( minValue );
  27101. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  27102. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  27103. if ( maxLength === 1 ) max.setScalar( maxValue );
  27104. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  27105. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  27106. const stride = 4;
  27107. const length = stride * object.count;
  27108. const array = new Float32Array( length );
  27109. for ( let i = 0; i < length; i ++ ) {
  27110. const index = i % stride;
  27111. const minElementValue = min.getComponent( index );
  27112. const maxElementValue = max.getComponent( index );
  27113. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  27114. }
  27115. const nodeType = this.getNodeType( builder );
  27116. if ( object.count <= 4096 ) {
  27117. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  27118. } else {
  27119. // TODO: Improve anonymous buffer attribute creation removing this part
  27120. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  27121. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  27122. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  27123. }
  27124. } else {
  27125. output = float( 0 );
  27126. }
  27127. return output;
  27128. }
  27129. }
  27130. /**
  27131. * TSL function for creating a range node.
  27132. *
  27133. * @tsl
  27134. * @function
  27135. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27136. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27137. * @returns {RangeNode}
  27138. */
  27139. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  27140. /**
  27141. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  27142. * about the currently running dispatch and/or the device it is running on.
  27143. *
  27144. * This node can only be used with a WebGPU backend.
  27145. *
  27146. * @augments Node
  27147. */
  27148. class ComputeBuiltinNode extends Node {
  27149. static get type() {
  27150. return 'ComputeBuiltinNode';
  27151. }
  27152. /**
  27153. * Constructs a new compute builtin node.
  27154. *
  27155. * @param {string} builtinName - The built-in name.
  27156. * @param {string} nodeType - The node type.
  27157. */
  27158. constructor( builtinName, nodeType ) {
  27159. super( nodeType );
  27160. /**
  27161. * The built-in name.
  27162. *
  27163. * @private
  27164. * @type {string}
  27165. */
  27166. this._builtinName = builtinName;
  27167. }
  27168. /**
  27169. * This method is overwritten since hash is derived from the built-in name.
  27170. *
  27171. * @param {NodeBuilder} builder - The current node builder.
  27172. * @return {string} The hash.
  27173. */
  27174. getHash( builder ) {
  27175. return this.getBuiltinName( builder );
  27176. }
  27177. /**
  27178. * This method is overwritten since the node type is simply derived from `nodeType`..
  27179. *
  27180. * @param {NodeBuilder} builder - The current node builder.
  27181. * @return {string} The node type.
  27182. */
  27183. getNodeType( /*builder*/ ) {
  27184. return this.nodeType;
  27185. }
  27186. /**
  27187. * Sets the builtin name.
  27188. *
  27189. * @param {string} builtinName - The built-in name.
  27190. * @return {ComputeBuiltinNode} A reference to this node.
  27191. */
  27192. setBuiltinName( builtinName ) {
  27193. this._builtinName = builtinName;
  27194. return this;
  27195. }
  27196. /**
  27197. * Returns the builtin name.
  27198. *
  27199. * @param {NodeBuilder} builder - The current node builder.
  27200. * @return {string} The builtin name.
  27201. */
  27202. getBuiltinName( /*builder*/ ) {
  27203. return this._builtinName;
  27204. }
  27205. /**
  27206. * Whether the current node builder has the builtin or not.
  27207. *
  27208. * @param {NodeBuilder} builder - The current node builder.
  27209. * @return {boolean} Whether the builder has the builtin or not.
  27210. */
  27211. hasBuiltin( builder ) {
  27212. return builder.hasBuiltin( this._builtinName );
  27213. }
  27214. generate( builder, output ) {
  27215. const builtinName = this.getBuiltinName( builder );
  27216. const nodeType = this.getNodeType( builder );
  27217. if ( builder.shaderStage === 'compute' ) {
  27218. return builder.format( builtinName, nodeType, output );
  27219. } else {
  27220. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  27221. return builder.generateConst( nodeType );
  27222. }
  27223. }
  27224. serialize( data ) {
  27225. super.serialize( data );
  27226. data.global = this.global;
  27227. data._builtinName = this._builtinName;
  27228. }
  27229. deserialize( data ) {
  27230. super.deserialize( data );
  27231. this.global = data.global;
  27232. this._builtinName = data._builtinName;
  27233. }
  27234. }
  27235. /**
  27236. * TSL function for creating a compute builtin node.
  27237. *
  27238. * @tsl
  27239. * @function
  27240. * @param {string} name - The built-in name.
  27241. * @param {string} nodeType - The node type.
  27242. * @returns {ComputeBuiltinNode}
  27243. */
  27244. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  27245. /**
  27246. * Represents the number of workgroups dispatched by the compute shader.
  27247. * ```js
  27248. * // Run 512 invocations/threads with a workgroup size of 128.
  27249. * const computeFn = Fn(() => {
  27250. *
  27251. * // numWorkgroups.x = 4
  27252. * storageBuffer.element(0).assign(numWorkgroups.x)
  27253. *
  27254. * })().compute(512, [128]);
  27255. *
  27256. * // Run 512 invocations/threads with the default workgroup size of 64.
  27257. * const computeFn = Fn(() => {
  27258. *
  27259. * // numWorkgroups.x = 8
  27260. * storageBuffer.element(0).assign(numWorkgroups.x)
  27261. *
  27262. * })().compute(512);
  27263. * ```
  27264. *
  27265. * @tsl
  27266. * @type {ComputeBuiltinNode<uvec3>}
  27267. */
  27268. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  27269. /**
  27270. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  27271. * ```js
  27272. * // Execute 12 compute threads with a workgroup size of 3.
  27273. * const computeFn = Fn( () => {
  27274. *
  27275. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  27276. *
  27277. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  27278. *
  27279. * } ).Else( () => {
  27280. *
  27281. * storageBuffer.element( instanceIndex ).assign( 0 );
  27282. *
  27283. * } );
  27284. *
  27285. * } )().compute( 12, [ 3 ] );
  27286. *
  27287. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  27288. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  27289. * ```
  27290. *
  27291. * @tsl
  27292. * @type {ComputeBuiltinNode<uvec3>}
  27293. */
  27294. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  27295. /**
  27296. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  27297. *
  27298. * @tsl
  27299. * @type {ComputeBuiltinNode<uvec3>}
  27300. */
  27301. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  27302. /**
  27303. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  27304. *
  27305. * @tsl
  27306. * @type {ComputeBuiltinNode<uvec3>}
  27307. */
  27308. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  27309. /**
  27310. * A device dependent variable that exposes the size of the current invocation's subgroup.
  27311. *
  27312. * @tsl
  27313. * @type {ComputeBuiltinNode<uint>}
  27314. */
  27315. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  27316. /**
  27317. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  27318. *
  27319. * This node can only be used with a WebGPU backend.
  27320. *
  27321. * @augments Node
  27322. */
  27323. class BarrierNode extends Node {
  27324. /**
  27325. * Constructs a new barrier node.
  27326. *
  27327. * @param {string} scope - The scope defines the behavior of the node.
  27328. */
  27329. constructor( scope ) {
  27330. super();
  27331. this.scope = scope;
  27332. }
  27333. generate( builder ) {
  27334. const { scope } = this;
  27335. const { renderer } = builder;
  27336. if ( renderer.backend.isWebGLBackend === true ) {
  27337. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  27338. } else {
  27339. builder.addLineFlowCode( `${scope}Barrier()`, this );
  27340. }
  27341. }
  27342. }
  27343. /**
  27344. * TSL function for creating a barrier node.
  27345. *
  27346. * @tsl
  27347. * @function
  27348. * @param {string} scope - The scope defines the behavior of the node..
  27349. * @returns {BarrierNode}
  27350. */
  27351. const barrier = nodeProxy( BarrierNode );
  27352. /**
  27353. * TSL function for creating a workgroup barrier. All compute shader
  27354. * invocations must wait for each invocation within a workgroup to
  27355. * complete before the barrier can be surpassed.
  27356. *
  27357. * @tsl
  27358. * @function
  27359. * @returns {BarrierNode}
  27360. */
  27361. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  27362. /**
  27363. * TSL function for creating a storage barrier. All invocations must
  27364. * wait for each access to variables within the 'storage' address space
  27365. * to complete before the barrier can be passed.
  27366. *
  27367. * @tsl
  27368. * @function
  27369. * @returns {BarrierNode}
  27370. */
  27371. const storageBarrier = () => barrier( 'storage' ).toStack();
  27372. /**
  27373. * TSL function for creating a texture barrier. All invocations must
  27374. * wait for each access to variables within the 'texture' address space
  27375. * to complete before the barrier can be passed.
  27376. *
  27377. * @tsl
  27378. * @function
  27379. * @returns {BarrierNode}
  27380. */
  27381. const textureBarrier = () => barrier( 'texture' ).toStack();
  27382. /**
  27383. * Represents an element of a 'workgroup' scoped buffer.
  27384. *
  27385. * @augments ArrayElementNode
  27386. */
  27387. class WorkgroupInfoElementNode extends ArrayElementNode {
  27388. /**
  27389. * Constructs a new workgroup info element node.
  27390. *
  27391. * @param {Node} workgroupInfoNode - The workgroup info node.
  27392. * @param {Node} indexNode - The index node that defines the element access.
  27393. */
  27394. constructor( workgroupInfoNode, indexNode ) {
  27395. super( workgroupInfoNode, indexNode );
  27396. /**
  27397. * This flag can be used for type testing.
  27398. *
  27399. * @type {boolean}
  27400. * @readonly
  27401. * @default true
  27402. */
  27403. this.isWorkgroupInfoElementNode = true;
  27404. }
  27405. generate( builder, output ) {
  27406. let snippet;
  27407. const isAssignContext = builder.context.assign;
  27408. snippet = super.generate( builder );
  27409. if ( isAssignContext !== true ) {
  27410. const type = this.getNodeType( builder );
  27411. snippet = builder.format( snippet, type, output );
  27412. }
  27413. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  27414. return snippet;
  27415. }
  27416. }
  27417. /**
  27418. * A node allowing the user to create a 'workgroup' scoped buffer within the
  27419. * context of a compute shader. Typically, workgroup scoped buffers are
  27420. * created to hold data that is transferred from a global storage scope into
  27421. * a local workgroup scope. For invocations within a workgroup, data
  27422. * access speeds on 'workgroup' scoped buffers can be significantly faster
  27423. * than similar access operations on globally accessible storage buffers.
  27424. *
  27425. * This node can only be used with a WebGPU backend.
  27426. *
  27427. * @augments Node
  27428. */
  27429. class WorkgroupInfoNode extends Node {
  27430. /**
  27431. * Constructs a new buffer scoped to type scope.
  27432. *
  27433. * @param {string} scope - TODO.
  27434. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  27435. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  27436. */
  27437. constructor( scope, bufferType, bufferCount = 0 ) {
  27438. super( bufferType );
  27439. /**
  27440. * The buffer type.
  27441. *
  27442. * @type {string}
  27443. */
  27444. this.bufferType = bufferType;
  27445. /**
  27446. * The buffer count.
  27447. *
  27448. * @type {number}
  27449. * @default 0
  27450. */
  27451. this.bufferCount = bufferCount;
  27452. /**
  27453. * This flag can be used for type testing.
  27454. *
  27455. * @type {boolean}
  27456. * @readonly
  27457. * @default true
  27458. */
  27459. this.isWorkgroupInfoNode = true;
  27460. /**
  27461. * The data type of the array buffer.
  27462. *
  27463. * @type {string}
  27464. */
  27465. this.elementType = bufferType;
  27466. /**
  27467. * TODO.
  27468. *
  27469. * @type {string}
  27470. */
  27471. this.scope = scope;
  27472. /**
  27473. * The name of the workgroup scoped buffer.
  27474. *
  27475. * @type {string}
  27476. * @default ''
  27477. */
  27478. this.name = '';
  27479. }
  27480. /**
  27481. * Sets the name of this node.
  27482. *
  27483. * @param {string} name - The name to set.
  27484. * @return {WorkgroupInfoNode} A reference to this node.
  27485. */
  27486. setName( name ) {
  27487. this.name = name;
  27488. return this;
  27489. }
  27490. /**
  27491. * Sets the name/label of this node.
  27492. *
  27493. * @deprecated
  27494. * @param {string} name - The name to set.
  27495. * @return {WorkgroupInfoNode} A reference to this node.
  27496. */
  27497. label( name ) {
  27498. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  27499. return this.setName( name );
  27500. }
  27501. /**
  27502. * Sets the scope of this node.
  27503. *
  27504. * @param {string} scope - The scope to set.
  27505. * @return {WorkgroupInfoNode} A reference to this node.
  27506. */
  27507. setScope( scope ) {
  27508. this.scope = scope;
  27509. return this;
  27510. }
  27511. /**
  27512. * The data type of the array buffer.
  27513. *
  27514. * @return {string} The element type.
  27515. */
  27516. getElementType() {
  27517. return this.elementType;
  27518. }
  27519. /**
  27520. * Overwrites the default implementation since the input type
  27521. * is inferred from the scope.
  27522. *
  27523. * @param {NodeBuilder} builder - The current node builder.
  27524. * @return {string} The input type.
  27525. */
  27526. getInputType( /*builder*/ ) {
  27527. return `${this.scope}Array`;
  27528. }
  27529. /**
  27530. * This method can be used to access elements via an index node.
  27531. *
  27532. * @param {IndexNode} indexNode - indexNode.
  27533. * @return {WorkgroupInfoElementNode} A reference to an element.
  27534. */
  27535. element( indexNode ) {
  27536. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  27537. }
  27538. generate( builder ) {
  27539. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  27540. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  27541. }
  27542. }
  27543. /**
  27544. * TSL function for creating a workgroup info node.
  27545. * Creates a new 'workgroup' scoped array buffer.
  27546. *
  27547. * @tsl
  27548. * @function
  27549. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  27550. * @param {number} [count=0] - The number of elements in the buffer.
  27551. * @returns {WorkgroupInfoNode}
  27552. */
  27553. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  27554. /**
  27555. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  27556. * within a shader. In an atomic function, any modification to an atomic variable will
  27557. * occur as an indivisible step with a defined order relative to other modifications.
  27558. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  27559. * atomic operations will not interfere with each other.
  27560. *
  27561. * This node can only be used with a WebGPU backend.
  27562. *
  27563. * @augments Node
  27564. */
  27565. class AtomicFunctionNode extends Node {
  27566. static get type() {
  27567. return 'AtomicFunctionNode';
  27568. }
  27569. /**
  27570. * Constructs a new atomic function node.
  27571. *
  27572. * @param {string} method - The signature of the atomic function to construct.
  27573. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27574. * @param {Node} valueNode - The value that mutates the atomic variable.
  27575. */
  27576. constructor( method, pointerNode, valueNode ) {
  27577. super( 'uint' );
  27578. /**
  27579. * The signature of the atomic function to construct.
  27580. *
  27581. * @type {string}
  27582. */
  27583. this.method = method;
  27584. /**
  27585. * An atomic variable or element of an atomic buffer.
  27586. *
  27587. * @type {Node}
  27588. */
  27589. this.pointerNode = pointerNode;
  27590. /**
  27591. * A value that modifies the atomic variable.
  27592. *
  27593. * @type {Node}
  27594. */
  27595. this.valueNode = valueNode;
  27596. /**
  27597. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  27598. *
  27599. * @type {boolean}
  27600. * @default true
  27601. */
  27602. this.parents = true;
  27603. }
  27604. /**
  27605. * Overwrites the default implementation to return the type of
  27606. * the pointer node.
  27607. *
  27608. * @param {NodeBuilder} builder - The current node builder.
  27609. * @return {string} The input type.
  27610. */
  27611. getInputType( builder ) {
  27612. return this.pointerNode.getNodeType( builder );
  27613. }
  27614. /**
  27615. * Overwritten since the node type is inferred from the input type.
  27616. *
  27617. * @param {NodeBuilder} builder - The current node builder.
  27618. * @return {string} The node type.
  27619. */
  27620. getNodeType( builder ) {
  27621. return this.getInputType( builder );
  27622. }
  27623. generate( builder ) {
  27624. const properties = builder.getNodeProperties( this );
  27625. const parents = properties.parents;
  27626. const method = this.method;
  27627. const type = this.getNodeType( builder );
  27628. const inputType = this.getInputType( builder );
  27629. const a = this.pointerNode;
  27630. const b = this.valueNode;
  27631. const params = [];
  27632. params.push( `&${ a.build( builder, inputType ) }` );
  27633. if ( b !== null ) {
  27634. params.push( b.build( builder, inputType ) );
  27635. }
  27636. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  27637. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  27638. if ( isVoid ) {
  27639. builder.addLineFlowCode( methodSnippet, this );
  27640. } else {
  27641. if ( properties.constNode === undefined ) {
  27642. properties.constNode = expression( methodSnippet, type ).toConst();
  27643. }
  27644. return properties.constNode.build( builder );
  27645. }
  27646. }
  27647. }
  27648. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  27649. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  27650. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  27651. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  27652. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  27653. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  27654. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  27655. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  27656. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  27657. /**
  27658. * TSL function for creating an atomic function node.
  27659. *
  27660. * @tsl
  27661. * @function
  27662. * @param {string} method - The signature of the atomic function to construct.
  27663. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27664. * @param {Node} valueNode - The value that mutates the atomic variable.
  27665. * @returns {AtomicFunctionNode}
  27666. */
  27667. const atomicNode = nodeProxy( AtomicFunctionNode );
  27668. /**
  27669. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  27670. *
  27671. * @tsl
  27672. * @function
  27673. * @param {string} method - The signature of the atomic function to construct.
  27674. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27675. * @param {Node} valueNode - The value that mutates the atomic variable.
  27676. * @returns {AtomicFunctionNode}
  27677. */
  27678. const atomicFunc = ( method, pointerNode, valueNode ) => {
  27679. return atomicNode( method, pointerNode, valueNode ).toStack();
  27680. };
  27681. /**
  27682. * Loads the value stored in the atomic variable.
  27683. *
  27684. * @tsl
  27685. * @function
  27686. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27687. * @returns {AtomicFunctionNode}
  27688. */
  27689. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  27690. /**
  27691. * Stores a value in the atomic variable.
  27692. *
  27693. * @tsl
  27694. * @function
  27695. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27696. * @param {Node} valueNode - The value that mutates the atomic variable.
  27697. * @returns {AtomicFunctionNode}
  27698. */
  27699. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  27700. /**
  27701. * Increments the value stored in the atomic variable.
  27702. *
  27703. * @tsl
  27704. * @function
  27705. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27706. * @param {Node} valueNode - The value that mutates the atomic variable.
  27707. * @returns {AtomicFunctionNode}
  27708. */
  27709. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  27710. /**
  27711. * Decrements the value stored in the atomic variable.
  27712. *
  27713. * @tsl
  27714. * @function
  27715. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27716. * @param {Node} valueNode - The value that mutates the atomic variable.
  27717. * @returns {AtomicFunctionNode}
  27718. */
  27719. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  27720. /**
  27721. * Stores in an atomic variable the maximum between its current value and a parameter.
  27722. *
  27723. * @tsl
  27724. * @function
  27725. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27726. * @param {Node} valueNode - The value that mutates the atomic variable.
  27727. * @returns {AtomicFunctionNode}
  27728. */
  27729. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  27730. /**
  27731. * Stores in an atomic variable the minimum between its current value and a parameter.
  27732. *
  27733. * @tsl
  27734. * @function
  27735. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27736. * @param {Node} valueNode - The value that mutates the atomic variable.
  27737. * @returns {AtomicFunctionNode}
  27738. */
  27739. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  27740. /**
  27741. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  27742. *
  27743. * @tsl
  27744. * @function
  27745. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27746. * @param {Node} valueNode - The value that mutates the atomic variable.
  27747. * @returns {AtomicFunctionNode}
  27748. */
  27749. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  27750. /**
  27751. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  27752. *
  27753. * @tsl
  27754. * @function
  27755. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27756. * @param {Node} valueNode - The value that mutates the atomic variable.
  27757. * @returns {AtomicFunctionNode}
  27758. */
  27759. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  27760. /**
  27761. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  27762. *
  27763. * @tsl
  27764. * @function
  27765. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27766. * @param {Node} valueNode - The value that mutates the atomic variable.
  27767. * @returns {AtomicFunctionNode}
  27768. */
  27769. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  27770. /**
  27771. * This class represents a set of built in WGSL shader functions that sync
  27772. * synchronously execute an operation across a subgroup, or 'warp', of compute
  27773. * or fragment shader invocations within a workgroup. Typically, these functions
  27774. * will synchronously execute an operation using data from all active invocations
  27775. * within the subgroup, then broadcast that result to all active invocations. In
  27776. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  27777. * (DirectX/HLSL) or warp intrinsics (CUDA).
  27778. *
  27779. * @augments TempNode
  27780. */
  27781. class SubgroupFunctionNode extends TempNode {
  27782. static get type() {
  27783. return 'SubgroupFunctionNode';
  27784. }
  27785. /**
  27786. * Constructs a new function node.
  27787. *
  27788. * @param {string} method - The subgroup/wave intrinsic method to construct.
  27789. * @param {Node} [aNode=null] - The method's first argument.
  27790. * @param {Node} [bNode=null] - The method's second argument.
  27791. */
  27792. constructor( method, aNode = null, bNode = null ) {
  27793. super();
  27794. /**
  27795. * The subgroup/wave intrinsic method to construct.
  27796. *
  27797. * @type {String}
  27798. */
  27799. this.method = method;
  27800. /**
  27801. * The method's first argument.
  27802. *
  27803. * @type {Node}
  27804. */
  27805. this.aNode = aNode;
  27806. /**
  27807. * The method's second argument.
  27808. *
  27809. * @type {Node}
  27810. */
  27811. this.bNode = bNode;
  27812. }
  27813. getInputType( builder ) {
  27814. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  27815. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  27816. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  27817. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  27818. if ( aLen > bLen ) {
  27819. return aType;
  27820. } else {
  27821. return bType;
  27822. }
  27823. }
  27824. getNodeType( builder ) {
  27825. const method = this.method;
  27826. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  27827. return 'bool';
  27828. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  27829. return 'uvec4';
  27830. } else {
  27831. return this.getInputType( builder );
  27832. }
  27833. }
  27834. generate( builder, output ) {
  27835. const method = this.method;
  27836. const type = this.getNodeType( builder );
  27837. const inputType = this.getInputType( builder );
  27838. const a = this.aNode;
  27839. const b = this.bNode;
  27840. const params = [];
  27841. if (
  27842. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  27843. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  27844. method === SubgroupFunctionNode.QUAD_BROADCAST
  27845. ) {
  27846. const bType = b.getNodeType( builder );
  27847. params.push(
  27848. a.build( builder, type ),
  27849. b.build( builder, bType === 'float' ? 'int' : type )
  27850. );
  27851. } else if (
  27852. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  27853. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  27854. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  27855. ) {
  27856. params.push(
  27857. a.build( builder, type ),
  27858. b.build( builder, 'uint' )
  27859. );
  27860. } else {
  27861. if ( a !== null ) params.push( a.build( builder, inputType ) );
  27862. if ( b !== null ) params.push( b.build( builder, inputType ) );
  27863. }
  27864. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  27865. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  27866. }
  27867. serialize( data ) {
  27868. super.serialize( data );
  27869. data.method = this.method;
  27870. }
  27871. deserialize( data ) {
  27872. super.deserialize( data );
  27873. this.method = data.method;
  27874. }
  27875. }
  27876. // 0 inputs
  27877. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  27878. // 1 input
  27879. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  27880. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  27881. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  27882. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  27883. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  27884. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  27885. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  27886. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  27887. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  27888. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  27889. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  27890. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  27891. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  27892. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  27893. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  27894. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  27895. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  27896. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  27897. // 2 inputs
  27898. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  27899. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  27900. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  27901. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  27902. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  27903. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  27904. /**
  27905. * Returns true if this invocation has the lowest subgroup_invocation_id
  27906. * among active invocations in the subgroup.
  27907. *
  27908. * @method
  27909. * @return {bool} The result of the computation.
  27910. */
  27911. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  27912. /**
  27913. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  27914. * is 1 if pred is true for that active invocation and 0 otherwise.
  27915. *
  27916. * @method
  27917. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  27918. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  27919. */
  27920. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  27921. /**
  27922. * A reduction that adds e among all active invocations and returns that result.
  27923. *
  27924. * @method
  27925. * @param {number} e - The value provided to the reduction by the current invocation.
  27926. * @return {number} The accumulated result of the reduction operation.
  27927. */
  27928. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  27929. /**
  27930. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  27931. *
  27932. * @method
  27933. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  27934. * @return {number} The accumulated result of the inclusive scan operation.
  27935. */
  27936. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  27937. /**
  27938. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  27939. *
  27940. * @method
  27941. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  27942. * @return {number} The accumulated result of the exclusive scan operation.
  27943. */
  27944. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  27945. /**
  27946. * A reduction that multiplies e among all active invocations and returns that result.
  27947. *
  27948. * @method
  27949. * @param {number} e - The value provided to the reduction by the current invocation.
  27950. * @return {number} The accumulated result of the reduction operation.
  27951. */
  27952. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  27953. /**
  27954. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  27955. *
  27956. * @method
  27957. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  27958. * @return {number} The accumulated result of the inclusive scan operation.
  27959. */
  27960. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  27961. /**
  27962. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  27963. *
  27964. * @method
  27965. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  27966. * @return {number} The accumulated result of the exclusive scan operation.
  27967. */
  27968. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  27969. /**
  27970. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  27971. *
  27972. * @method
  27973. * @param {number} e - The value provided to the reduction by the current invocation.
  27974. * @return {number} The result of the reduction operation.
  27975. */
  27976. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  27977. /**
  27978. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  27979. *
  27980. * @method
  27981. * @param {number} e - The value provided to the reduction by the current invocation.
  27982. * @return {number} The result of the reduction operation.
  27983. */
  27984. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  27985. /**
  27986. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  27987. *
  27988. * @method
  27989. * @param {number} e - The value provided to the reduction by the current invocation.
  27990. * @return {number} The result of the reduction operation.
  27991. */
  27992. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  27993. /**
  27994. * A reduction that performs a min of e among all active invocations and returns that result.
  27995. *
  27996. * @method
  27997. * @param {number} e - The value provided to the reduction by the current invocation.
  27998. * @return {number} The result of the reduction operation.
  27999. */
  28000. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  28001. /**
  28002. * A reduction that performs a max of e among all active invocations and returns that result.
  28003. *
  28004. * @method
  28005. * @param {number} e - The value provided to the reduction by the current invocation.
  28006. * @return {number} The result of the reduction operation.
  28007. */
  28008. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  28009. /**
  28010. * Returns true if e is true for all active invocations in the subgroup.
  28011. *
  28012. * @method
  28013. * @return {bool} The result of the computation.
  28014. */
  28015. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  28016. /**
  28017. * Returns true if e is true for any active invocation in the subgroup
  28018. *
  28019. * @method
  28020. * @return {bool} The result of the computation.
  28021. */
  28022. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  28023. /**
  28024. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  28025. *
  28026. * @method
  28027. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  28028. * @param {number} id - The subgroup invocation to broadcast from.
  28029. * @return {number} The broadcast value.
  28030. */
  28031. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  28032. /**
  28033. * Swaps e between invocations in the quad in the X direction.
  28034. *
  28035. * @method
  28036. * @param {number} e - The value to swap from the current invocation.
  28037. * @return {number} The value received from the swap operation.
  28038. */
  28039. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  28040. /**
  28041. * Swaps e between invocations in the quad in the Y direction.
  28042. *
  28043. * @method
  28044. * @param {number} e - The value to swap from the current invocation.
  28045. * @return {number} The value received from the swap operation.
  28046. */
  28047. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  28048. /**
  28049. * Swaps e between invocations in the quad diagonally.
  28050. *
  28051. * @method
  28052. * @param {number} e - The value to swap from the current invocation.
  28053. * @return {number} The value received from the swap operation.
  28054. */
  28055. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  28056. /**
  28057. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  28058. *
  28059. * @method
  28060. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  28061. * @param {number} id - The subgroup invocation to broadcast from.
  28062. * @return {number} The broadcast value.
  28063. */
  28064. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  28065. /**
  28066. * Returns v from the active invocation whose subgroup_invocation_id matches id
  28067. *
  28068. * @method
  28069. * @param {number} v - The value to return from subgroup invocation id^mask.
  28070. * @param {number} id - The subgroup invocation which returns the value v.
  28071. * @return {number} The broadcast value.
  28072. */
  28073. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  28074. /**
  28075. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  28076. *
  28077. * @method
  28078. * @param {number} v - The value to return from subgroup invocation id^mask.
  28079. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  28080. * @return {number} The broadcast value.
  28081. */
  28082. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).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 in.
  28089. * @return {number} The broadcast value.
  28090. */
  28091. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  28092. /**
  28093. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  28094. *
  28095. * @method
  28096. * @param {number} v - The value to return from subgroup invocation id^mask.
  28097. * @param {number} delta - A value that offsets the current subgroup invocation.
  28098. * @return {number} The broadcast value.
  28099. */
  28100. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  28101. /**
  28102. * Broadcasts e from the quad invocation with id equal to id.
  28103. *
  28104. * @method
  28105. * @param {number} e - The value to broadcast.
  28106. * @return {number} The broadcast value.
  28107. */
  28108. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  28109. let uniformsLib;
  28110. function getLightData( light ) {
  28111. uniformsLib = uniformsLib || new WeakMap();
  28112. let uniforms = uniformsLib.get( light );
  28113. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  28114. return uniforms;
  28115. }
  28116. /**
  28117. * TSL function for getting a shadow matrix uniform node for the given light.
  28118. *
  28119. * @tsl
  28120. * @function
  28121. * @param {Light} light -The light source.
  28122. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  28123. */
  28124. function lightShadowMatrix( light ) {
  28125. const data = getLightData( light );
  28126. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  28127. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  28128. light.shadow.updateMatrices( light );
  28129. }
  28130. return light.shadow.matrix;
  28131. } ) );
  28132. }
  28133. /**
  28134. * TSL function for getting projected uv coordinates for the given light.
  28135. * Relevant when using maps with spot lights.
  28136. *
  28137. * @tsl
  28138. * @function
  28139. * @param {Light} light -The light source.
  28140. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  28141. * @returns {Node<vec3>} The projected uvs.
  28142. */
  28143. function lightProjectionUV( light, position = positionWorld ) {
  28144. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  28145. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  28146. return projectionUV;
  28147. }
  28148. /**
  28149. * TSL function for getting the position in world space for the given light.
  28150. *
  28151. * @tsl
  28152. * @function
  28153. * @param {Light} light -The light source.
  28154. * @returns {UniformNode<vec3>} The light's position in world space.
  28155. */
  28156. function lightPosition( light ) {
  28157. const data = getLightData( light );
  28158. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  28159. }
  28160. /**
  28161. * TSL function for getting the light target position in world space for the given light.
  28162. *
  28163. * @tsl
  28164. * @function
  28165. * @param {Light} light -The light source.
  28166. * @returns {UniformNode<vec3>} The light target position in world space.
  28167. */
  28168. function lightTargetPosition( light ) {
  28169. const data = getLightData( light );
  28170. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  28171. }
  28172. /**
  28173. * TSL function for getting the position in view space for the given light.
  28174. *
  28175. * @tsl
  28176. * @function
  28177. * @param {Light} light - The light source.
  28178. * @returns {UniformNode<vec3>} The light's position in view space.
  28179. */
  28180. function lightViewPosition( light ) {
  28181. const data = getLightData( light );
  28182. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  28183. self.value = self.value || new Vector3();
  28184. self.value.setFromMatrixPosition( light.matrixWorld );
  28185. self.value.applyMatrix4( camera.matrixWorldInverse );
  28186. } ) );
  28187. }
  28188. /**
  28189. * TSL function for getting the light target direction for the given light.
  28190. *
  28191. * @tsl
  28192. * @function
  28193. * @param {Light} light -The light source.
  28194. * @returns {Node<vec3>} The light's target direction.
  28195. */
  28196. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  28197. const sortLights = ( lights ) => {
  28198. return lights.sort( ( a, b ) => a.id - b.id );
  28199. };
  28200. const getLightNodeById = ( id, lightNodes ) => {
  28201. for ( const lightNode of lightNodes ) {
  28202. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  28203. return lightNode;
  28204. }
  28205. }
  28206. return null;
  28207. };
  28208. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  28209. const _hashData = [];
  28210. /**
  28211. * This node represents the scene's lighting and manages the lighting model's life cycle
  28212. * for the current build 3D object. It is responsible for computing the total outgoing
  28213. * light in a given lighting context.
  28214. *
  28215. * @augments Node
  28216. */
  28217. class LightsNode extends Node {
  28218. static get type() {
  28219. return 'LightsNode';
  28220. }
  28221. /**
  28222. * Constructs a new lights node.
  28223. */
  28224. constructor() {
  28225. super( 'vec3' );
  28226. /**
  28227. * A node representing the total diffuse light.
  28228. *
  28229. * @type {Node<vec3>}
  28230. */
  28231. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  28232. /**
  28233. * A node representing the total specular light.
  28234. *
  28235. * @type {Node<vec3>}
  28236. */
  28237. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  28238. /**
  28239. * A node representing the outgoing light.
  28240. *
  28241. * @type {Node<vec3>}
  28242. */
  28243. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  28244. /**
  28245. * An array representing the lights in the scene.
  28246. *
  28247. * @private
  28248. * @type {Array<Light>}
  28249. */
  28250. this._lights = [];
  28251. /**
  28252. * For each light in the scene, this node will create a
  28253. * corresponding light node.
  28254. *
  28255. * @private
  28256. * @type {?Array<LightingNode>}
  28257. * @default null
  28258. */
  28259. this._lightNodes = null;
  28260. /**
  28261. * A hash for identifying the current light nodes setup.
  28262. *
  28263. * @private
  28264. * @type {?string}
  28265. * @default null
  28266. */
  28267. this._lightNodesHash = null;
  28268. /**
  28269. * `LightsNode` sets this property to `true` by default.
  28270. *
  28271. * @type {boolean}
  28272. * @default true
  28273. */
  28274. this.global = true;
  28275. }
  28276. /**
  28277. * Overwrites the default {@link Node#customCacheKey} implementation by including
  28278. * light data into the cache key.
  28279. *
  28280. * @return {number} The custom cache key.
  28281. */
  28282. customCacheKey() {
  28283. const lights = this._lights;
  28284. for ( let i = 0; i < lights.length; i ++ ) {
  28285. const light = lights[ i ];
  28286. _hashData.push( light.id );
  28287. _hashData.push( light.castShadow ? 1 : 0 );
  28288. if ( light.isSpotLight === true ) {
  28289. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  28290. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  28291. _hashData.push( hashMap, hashColorNode );
  28292. }
  28293. }
  28294. const cacheKey = hashArray( _hashData );
  28295. _hashData.length = 0;
  28296. return cacheKey;
  28297. }
  28298. /**
  28299. * Computes a hash value for identifying the current light nodes setup.
  28300. *
  28301. * @param {NodeBuilder} builder - A reference to the current node builder.
  28302. * @return {string} The computed hash.
  28303. */
  28304. getHash( builder ) {
  28305. if ( this._lightNodesHash === null ) {
  28306. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28307. const hash = [];
  28308. for ( const lightNode of this._lightNodes ) {
  28309. hash.push( lightNode.getSelf().getHash() );
  28310. }
  28311. this._lightNodesHash = 'lights-' + hash.join( ',' );
  28312. }
  28313. return this._lightNodesHash;
  28314. }
  28315. analyze( builder ) {
  28316. const properties = builder.getNodeProperties( this );
  28317. for ( const node of properties.nodes ) {
  28318. node.build( builder );
  28319. }
  28320. properties.outputNode.build( builder );
  28321. }
  28322. /**
  28323. * Creates lighting nodes for each scene light. This makes it possible to further
  28324. * process lights in the node system.
  28325. *
  28326. * @param {NodeBuilder} builder - A reference to the current node builder.
  28327. */
  28328. setupLightsNode( builder ) {
  28329. const lightNodes = [];
  28330. const previousLightNodes = this._lightNodes;
  28331. const lights = sortLights( this._lights );
  28332. const nodeLibrary = builder.renderer.library;
  28333. for ( const light of lights ) {
  28334. if ( light.isNode ) {
  28335. lightNodes.push( nodeObject( light ) );
  28336. } else {
  28337. let lightNode = null;
  28338. if ( previousLightNodes !== null ) {
  28339. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  28340. }
  28341. if ( lightNode === null ) {
  28342. // find the corresponding node type for a given light
  28343. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  28344. if ( lightNodeClass === null ) {
  28345. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  28346. continue;
  28347. }
  28348. let lightNode = null;
  28349. if ( ! _lightsNodeRef.has( light ) ) {
  28350. lightNode = nodeObject( new lightNodeClass( light ) );
  28351. _lightsNodeRef.set( light, lightNode );
  28352. } else {
  28353. lightNode = _lightsNodeRef.get( light );
  28354. }
  28355. lightNodes.push( lightNode );
  28356. }
  28357. }
  28358. }
  28359. this._lightNodes = lightNodes;
  28360. }
  28361. /**
  28362. * Sets up a direct light in the lighting model.
  28363. *
  28364. * @param {Object} builder - The builder object containing the context and stack.
  28365. * @param {Object} lightNode - The light node.
  28366. * @param {Object} lightData - The light object containing color and direction properties.
  28367. */
  28368. setupDirectLight( builder, lightNode, lightData ) {
  28369. const { lightingModel, reflectedLight } = builder.context;
  28370. lightingModel.direct( {
  28371. ...lightData,
  28372. lightNode,
  28373. reflectedLight
  28374. }, builder );
  28375. }
  28376. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  28377. const { lightingModel, reflectedLight } = builder.context;
  28378. lightingModel.directRectArea( {
  28379. ...lightData,
  28380. lightNode,
  28381. reflectedLight
  28382. }, builder );
  28383. }
  28384. /**
  28385. * Setups the internal lights by building all respective
  28386. * light nodes.
  28387. *
  28388. * @param {NodeBuilder} builder - A reference to the current node builder.
  28389. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  28390. */
  28391. setupLights( builder, lightNodes ) {
  28392. for ( const lightNode of lightNodes ) {
  28393. lightNode.build( builder );
  28394. }
  28395. }
  28396. getLightNodes( builder ) {
  28397. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28398. return this._lightNodes;
  28399. }
  28400. /**
  28401. * The implementation makes sure that for each light in the scene
  28402. * there is a corresponding light node. By building the light nodes
  28403. * and evaluating the lighting model the outgoing light is computed.
  28404. *
  28405. * @param {NodeBuilder} builder - A reference to the current node builder.
  28406. * @return {Node<vec3>} A node representing the outgoing light.
  28407. */
  28408. setup( builder ) {
  28409. const currentLightsNode = builder.lightsNode;
  28410. builder.lightsNode = this;
  28411. //
  28412. let outgoingLightNode = this.outgoingLightNode;
  28413. const context = builder.context;
  28414. const lightingModel = context.lightingModel;
  28415. const properties = builder.getNodeProperties( this );
  28416. if ( lightingModel ) {
  28417. const { totalDiffuseNode, totalSpecularNode } = this;
  28418. context.outgoingLight = outgoingLightNode;
  28419. const stack = builder.addStack();
  28420. //
  28421. properties.nodes = stack.nodes;
  28422. //
  28423. lightingModel.start( builder );
  28424. //
  28425. const { backdrop, backdropAlpha } = context;
  28426. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  28427. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  28428. if ( backdrop !== null ) {
  28429. if ( backdropAlpha !== null ) {
  28430. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  28431. } else {
  28432. totalDiffuse = vec3( backdrop );
  28433. }
  28434. context.material.transparent = true;
  28435. }
  28436. totalDiffuseNode.assign( totalDiffuse );
  28437. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  28438. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  28439. //
  28440. lightingModel.finish( builder );
  28441. //
  28442. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  28443. } else {
  28444. properties.nodes = [];
  28445. }
  28446. //
  28447. builder.lightsNode = currentLightsNode;
  28448. return outgoingLightNode;
  28449. }
  28450. /**
  28451. * Configures this node with an array of lights.
  28452. *
  28453. * @param {Array<Light>} lights - An array of lights.
  28454. * @return {LightsNode} A reference to this node.
  28455. */
  28456. setLights( lights ) {
  28457. this._lights = lights;
  28458. this._lightNodes = null;
  28459. this._lightNodesHash = null;
  28460. return this;
  28461. }
  28462. /**
  28463. * Returns an array of the scene's lights.
  28464. *
  28465. * @return {Array<Light>} The scene's lights.
  28466. */
  28467. getLights() {
  28468. return this._lights;
  28469. }
  28470. /**
  28471. * Whether the scene has lights or not.
  28472. *
  28473. * @type {boolean}
  28474. */
  28475. get hasLights() {
  28476. return this._lights.length > 0;
  28477. }
  28478. }
  28479. /**
  28480. * TSL function for creating an instance of `LightsNode` and configuring
  28481. * it with the given array of lights.
  28482. *
  28483. * @tsl
  28484. * @function
  28485. * @param {Array<Light>} lights - An array of lights.
  28486. * @return {LightsNode} The created lights node.
  28487. */
  28488. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  28489. /**
  28490. * Base class for all shadow nodes.
  28491. *
  28492. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  28493. * Lighting nodes might share the same shadow node type or use specific ones depending on
  28494. * their requirements.
  28495. *
  28496. * @augments Node
  28497. */
  28498. class ShadowBaseNode extends Node {
  28499. static get type() {
  28500. return 'ShadowBaseNode';
  28501. }
  28502. /**
  28503. * Constructs a new shadow base node.
  28504. *
  28505. * @param {Light} light - The shadow casting light.
  28506. */
  28507. constructor( light ) {
  28508. super();
  28509. /**
  28510. * The shadow casting light.
  28511. *
  28512. * @type {Light}
  28513. */
  28514. this.light = light;
  28515. /**
  28516. * Overwritten since shadows are updated by default per render.
  28517. *
  28518. * @type {string}
  28519. * @default 'render'
  28520. */
  28521. this.updateBeforeType = NodeUpdateType.RENDER;
  28522. /**
  28523. * This flag can be used for type testing.
  28524. *
  28525. * @type {boolean}
  28526. * @readonly
  28527. * @default true
  28528. */
  28529. this.isShadowBaseNode = true;
  28530. }
  28531. /**
  28532. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  28533. *
  28534. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  28535. */
  28536. setupShadowPosition( { context, material } ) {
  28537. // Use assign inside an Fn()
  28538. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  28539. }
  28540. }
  28541. /**
  28542. * TSL object that represents the vertex position in world space during the shadow pass.
  28543. *
  28544. * @tsl
  28545. * @type {Node<vec3>}
  28546. */
  28547. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  28548. /**
  28549. * Saves the state of the given renderer and stores it into the given state object.
  28550. *
  28551. * If not state object is provided, the function creates one.
  28552. *
  28553. * @function
  28554. * @param {Renderer} renderer - The renderer.
  28555. * @param {Object} [state={}] - The state.
  28556. * @return {Object} The state.
  28557. */
  28558. function saveRendererState( renderer, state = {} ) {
  28559. state.toneMapping = renderer.toneMapping;
  28560. state.toneMappingExposure = renderer.toneMappingExposure;
  28561. state.outputColorSpace = renderer.outputColorSpace;
  28562. state.renderTarget = renderer.getRenderTarget();
  28563. state.activeCubeFace = renderer.getActiveCubeFace();
  28564. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  28565. state.renderObjectFunction = renderer.getRenderObjectFunction();
  28566. state.pixelRatio = renderer.getPixelRatio();
  28567. state.mrt = renderer.getMRT();
  28568. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  28569. state.clearAlpha = renderer.getClearAlpha();
  28570. state.autoClear = renderer.autoClear;
  28571. state.scissorTest = renderer.getScissorTest();
  28572. return state;
  28573. }
  28574. /**
  28575. * Saves the state of the given renderer and stores it into the given state object.
  28576. * Besides, the function also resets the state of the renderer to its default values.
  28577. *
  28578. * If not state object is provided, the function creates one.
  28579. *
  28580. * @function
  28581. * @param {Renderer} renderer - The renderer.
  28582. * @param {Object} [state={}] - The state.
  28583. * @return {Object} The state.
  28584. */
  28585. function resetRendererState( renderer, state ) {
  28586. state = saveRendererState( renderer, state );
  28587. renderer.setMRT( null );
  28588. renderer.setRenderObjectFunction( null );
  28589. renderer.setClearColor( 0x000000, 1 );
  28590. renderer.autoClear = true;
  28591. return state;
  28592. }
  28593. /**
  28594. * Restores the state of the given renderer from the given state object.
  28595. *
  28596. * @function
  28597. * @param {Renderer} renderer - The renderer.
  28598. * @param {Object} state - The state to restore.
  28599. */
  28600. function restoreRendererState( renderer, state ) {
  28601. renderer.toneMapping = state.toneMapping;
  28602. renderer.toneMappingExposure = state.toneMappingExposure;
  28603. renderer.outputColorSpace = state.outputColorSpace;
  28604. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  28605. renderer.setRenderObjectFunction( state.renderObjectFunction );
  28606. renderer.setPixelRatio( state.pixelRatio );
  28607. renderer.setMRT( state.mrt );
  28608. renderer.setClearColor( state.clearColor, state.clearAlpha );
  28609. renderer.autoClear = state.autoClear;
  28610. renderer.setScissorTest( state.scissorTest );
  28611. }
  28612. /**
  28613. * Saves the state of the given scene and stores it into the given state object.
  28614. *
  28615. * If not state object is provided, the function creates one.
  28616. *
  28617. * @function
  28618. * @param {Scene} scene - The scene.
  28619. * @param {Object} [state={}] - The state.
  28620. * @return {Object} The state.
  28621. */
  28622. function saveSceneState( scene, state = {} ) {
  28623. state.background = scene.background;
  28624. state.backgroundNode = scene.backgroundNode;
  28625. state.overrideMaterial = scene.overrideMaterial;
  28626. return state;
  28627. }
  28628. /**
  28629. * Saves the state of the given scene and stores it into the given state object.
  28630. * Besides, the function also resets the state of the scene to its default values.
  28631. *
  28632. * If not state object is provided, the function creates one.
  28633. *
  28634. * @function
  28635. * @param {Scene} scene - The scene.
  28636. * @param {Object} [state={}] - The state.
  28637. * @return {Object} The state.
  28638. */
  28639. function resetSceneState( scene, state ) {
  28640. state = saveSceneState( scene, state );
  28641. scene.background = null;
  28642. scene.backgroundNode = null;
  28643. scene.overrideMaterial = null;
  28644. return state;
  28645. }
  28646. /**
  28647. * Restores the state of the given scene from the given state object.
  28648. *
  28649. * @function
  28650. * @param {Scene} scene - The scene.
  28651. * @param {Object} state - The state to restore.
  28652. */
  28653. function restoreSceneState( scene, state ) {
  28654. scene.background = state.background;
  28655. scene.backgroundNode = state.backgroundNode;
  28656. scene.overrideMaterial = state.overrideMaterial;
  28657. }
  28658. /**
  28659. * Saves the state of the given renderer and scene and stores it into the given state object.
  28660. *
  28661. * If not state object is provided, the function creates one.
  28662. *
  28663. * @function
  28664. * @param {Renderer} renderer - The renderer.
  28665. * @param {Scene} scene - The scene.
  28666. * @param {Object} [state={}] - The state.
  28667. * @return {Object} The state.
  28668. */
  28669. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  28670. state = saveRendererState( renderer, state );
  28671. state = saveSceneState( scene, state );
  28672. return state;
  28673. }
  28674. /**
  28675. * Saves the state of the given renderer and scene and stores it into the given state object.
  28676. * Besides, the function also resets the state of the renderer and scene to its default values.
  28677. *
  28678. * If not state object is provided, the function creates one.
  28679. *
  28680. * @function
  28681. * @param {Renderer} renderer - The renderer.
  28682. * @param {Scene} scene - The scene.
  28683. * @param {Object} [state={}] - The state.
  28684. * @return {Object} The state.
  28685. */
  28686. function resetRendererAndSceneState( renderer, scene, state ) {
  28687. state = resetRendererState( renderer, state );
  28688. state = resetSceneState( scene, state );
  28689. return state;
  28690. }
  28691. /**
  28692. * Restores the state of the given renderer and scene from the given state object.
  28693. *
  28694. * @function
  28695. * @param {Renderer} renderer - The renderer.
  28696. * @param {Scene} scene - The scene.
  28697. * @param {Object} state - The state to restore.
  28698. */
  28699. function restoreRendererAndSceneState( renderer, scene, state ) {
  28700. restoreRendererState( renderer, state );
  28701. restoreSceneState( scene, state );
  28702. }
  28703. var RendererUtils = /*#__PURE__*/Object.freeze({
  28704. __proto__: null,
  28705. resetRendererAndSceneState: resetRendererAndSceneState,
  28706. resetRendererState: resetRendererState,
  28707. resetSceneState: resetSceneState,
  28708. restoreRendererAndSceneState: restoreRendererAndSceneState,
  28709. restoreRendererState: restoreRendererState,
  28710. restoreSceneState: restoreSceneState,
  28711. saveRendererAndSceneState: saveRendererAndSceneState,
  28712. saveRendererState: saveRendererState,
  28713. saveSceneState: saveSceneState
  28714. });
  28715. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  28716. /**
  28717. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  28718. * with a binary `[0,1]` result.
  28719. *
  28720. * @method
  28721. * @param {Object} inputs - The input parameter object.
  28722. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28723. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28724. * @return {Node<float>} The filtering result.
  28725. */
  28726. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  28727. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  28728. if ( depthTexture.isArrayTexture ) {
  28729. basic = basic.depth( depthLayer );
  28730. }
  28731. return basic.compare( shadowCoord.z );
  28732. } );
  28733. /**
  28734. * A shadow filtering function performing PCF filtering.
  28735. *
  28736. * @method
  28737. * @param {Object} inputs - The input parameter object.
  28738. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28739. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28740. * @param {LightShadow} inputs.shadow - The light shadow.
  28741. * @return {Node<float>} The filtering result.
  28742. */
  28743. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  28744. const depthCompare = ( uv, compare ) => {
  28745. let depth = texture( depthTexture, uv );
  28746. if ( depthTexture.isArrayTexture ) {
  28747. depth = depth.depth( depthLayer );
  28748. }
  28749. return depth.compare( compare );
  28750. };
  28751. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28752. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28753. const texelSize = vec2( 1 ).div( mapSize );
  28754. const dx0 = texelSize.x.negate().mul( radius );
  28755. const dy0 = texelSize.y.negate().mul( radius );
  28756. const dx1 = texelSize.x.mul( radius );
  28757. const dy1 = texelSize.y.mul( radius );
  28758. const dx2 = dx0.div( 2 );
  28759. const dy2 = dy0.div( 2 );
  28760. const dx3 = dx1.div( 2 );
  28761. const dy3 = dy1.div( 2 );
  28762. return add(
  28763. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  28764. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  28765. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  28766. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  28767. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  28768. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  28769. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  28770. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  28771. depthCompare( shadowCoord.xy, shadowCoord.z ),
  28772. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  28773. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  28774. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  28775. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  28776. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  28777. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  28778. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  28779. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  28780. ).mul( 1 / 17 );
  28781. } );
  28782. /**
  28783. * A shadow filtering function performing PCF soft filtering.
  28784. *
  28785. * @method
  28786. * @param {Object} inputs - The input parameter object.
  28787. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28788. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28789. * @param {LightShadow} inputs.shadow - The light shadow.
  28790. * @return {Node<float>} The filtering result.
  28791. */
  28792. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  28793. const depthCompare = ( uv, compare ) => {
  28794. let depth = texture( depthTexture, uv );
  28795. if ( depthTexture.isArrayTexture ) {
  28796. depth = depth.depth( depthLayer );
  28797. }
  28798. return depth.compare( compare );
  28799. };
  28800. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28801. const texelSize = vec2( 1 ).div( mapSize );
  28802. const dx = texelSize.x;
  28803. const dy = texelSize.y;
  28804. const uv = shadowCoord.xy;
  28805. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  28806. uv.subAssign( f.mul( texelSize ) );
  28807. return add(
  28808. depthCompare( uv, shadowCoord.z ),
  28809. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  28810. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  28811. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  28812. mix(
  28813. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  28814. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  28815. f.x
  28816. ),
  28817. mix(
  28818. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  28819. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  28820. f.x
  28821. ),
  28822. mix(
  28823. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  28824. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  28825. f.y
  28826. ),
  28827. mix(
  28828. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  28829. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  28830. f.y
  28831. ),
  28832. mix(
  28833. mix(
  28834. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  28835. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  28836. f.x
  28837. ),
  28838. mix(
  28839. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  28840. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  28841. f.x
  28842. ),
  28843. f.y
  28844. )
  28845. ).mul( 1 / 9 );
  28846. } );
  28847. /**
  28848. * A shadow filtering function performing VSM filtering.
  28849. *
  28850. * @method
  28851. * @param {Object} inputs - The input parameter object.
  28852. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28853. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28854. * @return {Node<float>} The filtering result.
  28855. */
  28856. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  28857. const occlusion = float( 1 ).toVar();
  28858. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  28859. if ( depthTexture.isArrayTexture ) {
  28860. distribution = distribution.depth( depthLayer );
  28861. }
  28862. distribution = distribution.rg;
  28863. const hardShadow = step( shadowCoord.z, distribution.x );
  28864. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  28865. const distance = shadowCoord.z.sub( distribution.x );
  28866. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  28867. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  28868. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  28869. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  28870. } );
  28871. return occlusion;
  28872. } );
  28873. //
  28874. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  28875. let dist = positionWorld.sub( position ).length();
  28876. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  28877. dist = dist.saturate(); // clamp to [ 0, 1 ]
  28878. return dist;
  28879. } );
  28880. const linearShadowDistance = ( light ) => {
  28881. const camera = light.shadow.camera;
  28882. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  28883. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  28884. const referencePosition = objectPosition( light );
  28885. return linearDistance( referencePosition, nearDistance, farDistance );
  28886. };
  28887. /**
  28888. * Retrieves or creates a shadow material for the given light source.
  28889. *
  28890. * This function checks if a shadow material already exists for the provided light.
  28891. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  28892. * in the `shadowMaterialLib` for future use.
  28893. *
  28894. * @param {Light} light - The light source for which the shadow material is needed.
  28895. * If the light is a point light, a depth node is calculated
  28896. * using the linear shadow distance.
  28897. * @returns {NodeMaterial} The shadow material associated with the given light.
  28898. */
  28899. const getShadowMaterial = ( light ) => {
  28900. let material = shadowMaterialLib.get( light );
  28901. if ( material === undefined ) {
  28902. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  28903. material = new NodeMaterial();
  28904. material.colorNode = vec4( 0, 0, 0, 1 );
  28905. material.depthNode = depthNode;
  28906. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  28907. material.name = 'ShadowMaterial';
  28908. material.fog = false;
  28909. shadowMaterialLib.set( light, material );
  28910. }
  28911. return material;
  28912. };
  28913. //
  28914. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  28915. const _shadowRenderObjectKeys = [];
  28916. /**
  28917. * Creates a function to render shadow objects in a scene.
  28918. *
  28919. * @param {Renderer} renderer - The renderer.
  28920. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  28921. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  28922. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  28923. * @return {Function} A function that renders shadow objects.
  28924. *
  28925. * The returned function has the following parameters:
  28926. * @param {Object3D} object - The 3D object to render.
  28927. * @param {Scene} scene - The scene containing the object.
  28928. * @param {Camera} _camera - The camera used for rendering.
  28929. * @param {BufferGeometry} geometry - The geometry of the object.
  28930. * @param {Material} material - The material of the object.
  28931. * @param {Group} group - The group the object belongs to.
  28932. * @param {...any} params - Additional parameters for rendering.
  28933. */
  28934. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  28935. _shadowRenderObjectKeys[ 0 ] = renderer;
  28936. _shadowRenderObjectKeys[ 1 ] = shadow;
  28937. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  28938. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  28939. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  28940. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  28941. if ( useVelocity ) {
  28942. getDataFromObject( object ).useVelocity = true;
  28943. }
  28944. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  28945. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  28946. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  28947. }
  28948. };
  28949. renderObjectFunction.shadowType = shadowType;
  28950. renderObjectFunction.useVelocity = useVelocity;
  28951. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  28952. }
  28953. _shadowRenderObjectKeys[ 0 ] = null;
  28954. _shadowRenderObjectKeys[ 1 ] = null;
  28955. return renderObjectFunction;
  28956. };
  28957. /**
  28958. * Represents the shader code for the first VSM render pass.
  28959. *
  28960. * @method
  28961. * @param {Object} inputs - The input parameter object.
  28962. * @param {Node<float>} inputs.samples - The number of samples
  28963. * @param {Node<float>} inputs.radius - The radius.
  28964. * @param {Node<float>} inputs.size - The size.
  28965. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  28966. * @return {Node<vec2>} The VSM output.
  28967. */
  28968. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  28969. const mean = float( 0 ).toVar( 'meanVertical' );
  28970. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  28971. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  28972. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  28973. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  28974. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  28975. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  28976. if ( shadowPass.value.isArrayTexture ) {
  28977. depth = depth.depth( depthLayer );
  28978. }
  28979. depth = depth.x;
  28980. mean.addAssign( depth );
  28981. squaredMean.addAssign( depth.mul( depth ) );
  28982. } );
  28983. mean.divAssign( samples );
  28984. squaredMean.divAssign( samples );
  28985. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  28986. return vec2( mean, std_dev );
  28987. } );
  28988. /**
  28989. * Represents the shader code for the second VSM render pass.
  28990. *
  28991. * @method
  28992. * @param {Object} inputs - The input parameter object.
  28993. * @param {Node<float>} inputs.samples - The number of samples
  28994. * @param {Node<float>} inputs.radius - The radius.
  28995. * @param {Node<float>} inputs.size - The size.
  28996. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  28997. * @return {Node<vec2>} The VSM output.
  28998. */
  28999. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29000. const mean = float( 0 ).toVar( 'meanHorizontal' );
  29001. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  29002. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29003. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29004. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29005. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29006. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  29007. if ( shadowPass.value.isArrayTexture ) {
  29008. distribution = distribution.depth( depthLayer );
  29009. }
  29010. mean.addAssign( distribution.x );
  29011. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  29012. } );
  29013. mean.divAssign( samples );
  29014. squaredMean.divAssign( samples );
  29015. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29016. return vec2( mean, std_dev );
  29017. } );
  29018. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  29019. //
  29020. let _rendererState;
  29021. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  29022. /**
  29023. * Represents the default shadow implementation for lighting nodes.
  29024. *
  29025. * @augments ShadowBaseNode
  29026. */
  29027. class ShadowNode extends ShadowBaseNode {
  29028. static get type() {
  29029. return 'ShadowNode';
  29030. }
  29031. /**
  29032. * Constructs a new shadow node.
  29033. *
  29034. * @param {Light} light - The shadow casting light.
  29035. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  29036. */
  29037. constructor( light, shadow = null ) {
  29038. super( light );
  29039. /**
  29040. * The light shadow which defines the properties light's
  29041. * shadow.
  29042. *
  29043. * @type {?LightShadow}
  29044. * @default null
  29045. */
  29046. this.shadow = shadow || light.shadow;
  29047. /**
  29048. * A reference to the shadow map which is a render target.
  29049. *
  29050. * @type {?RenderTarget}
  29051. * @default null
  29052. */
  29053. this.shadowMap = null;
  29054. /**
  29055. * Only relevant for VSM shadows. Render target for the
  29056. * first VSM render pass.
  29057. *
  29058. * @type {?RenderTarget}
  29059. * @default null
  29060. */
  29061. this.vsmShadowMapVertical = null;
  29062. /**
  29063. * Only relevant for VSM shadows. Render target for the
  29064. * second VSM render pass.
  29065. *
  29066. * @type {?RenderTarget}
  29067. * @default null
  29068. */
  29069. this.vsmShadowMapHorizontal = null;
  29070. /**
  29071. * Only relevant for VSM shadows. Node material which
  29072. * is used to render the first VSM pass.
  29073. *
  29074. * @type {?NodeMaterial}
  29075. * @default null
  29076. */
  29077. this.vsmMaterialVertical = null;
  29078. /**
  29079. * Only relevant for VSM shadows. Node material which
  29080. * is used to render the second VSM pass.
  29081. *
  29082. * @type {?NodeMaterial}
  29083. * @default null
  29084. */
  29085. this.vsmMaterialHorizontal = null;
  29086. /**
  29087. * A reference to the output node which defines the
  29088. * final result of this shadow node.
  29089. *
  29090. * @type {?Node}
  29091. * @private
  29092. * @default null
  29093. */
  29094. this._node = null;
  29095. this._cameraFrameId = new WeakMap();
  29096. /**
  29097. * This flag can be used for type testing.
  29098. *
  29099. * @type {boolean}
  29100. * @readonly
  29101. * @default true
  29102. */
  29103. this.isShadowNode = true;
  29104. /**
  29105. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  29106. *
  29107. * @type {number}
  29108. * @readonly
  29109. * @default true
  29110. */
  29111. this.depthLayer = 0;
  29112. }
  29113. /**
  29114. * Setups the shadow filtering.
  29115. *
  29116. * @param {NodeBuilder} builder - A reference to the current node builder.
  29117. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29118. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29119. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29120. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29121. * @param {LightShadow} inputs.shadow - The light shadow.
  29122. * @return {Node<float>} The result node of the shadow filtering.
  29123. */
  29124. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  29125. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  29126. .and( shadowCoord.x.lessThanEqual( 1 ) )
  29127. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  29128. .and( shadowCoord.y.lessThanEqual( 1 ) )
  29129. .and( shadowCoord.z.lessThanEqual( 1 ) );
  29130. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  29131. return frustumTest.select( shadowNode, float( 1 ) );
  29132. }
  29133. /**
  29134. * Setups the shadow coordinates.
  29135. *
  29136. * @param {NodeBuilder} builder - A reference to the current node builder.
  29137. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29138. * @return {Node<vec3>} The shadow coordinates.
  29139. */
  29140. setupShadowCoord( builder, shadowPosition ) {
  29141. const { shadow } = this;
  29142. const { renderer } = builder;
  29143. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29144. let shadowCoord = shadowPosition;
  29145. let coordZ;
  29146. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  29147. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  29148. coordZ = shadowCoord.z;
  29149. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  29150. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  29151. }
  29152. } else {
  29153. const w = shadowCoord.w;
  29154. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  29155. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  29156. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  29157. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  29158. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  29159. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  29160. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  29161. }
  29162. shadowCoord = vec3(
  29163. shadowCoord.x,
  29164. shadowCoord.y.oneMinus(), // follow webgpu standards
  29165. coordZ.add( bias )
  29166. );
  29167. return shadowCoord;
  29168. }
  29169. /**
  29170. * Returns the shadow filtering function for the given shadow type.
  29171. *
  29172. * @param {number} type - The shadow type.
  29173. * @return {Function} The filtering function.
  29174. */
  29175. getShadowFilterFn( type ) {
  29176. return _shadowFilterLib[ type ];
  29177. }
  29178. setupRenderTarget( shadow, builder ) {
  29179. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  29180. depthTexture.name = 'ShadowDepthTexture';
  29181. depthTexture.compareFunction = LessCompare;
  29182. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  29183. shadowMap.texture.name = 'ShadowMap';
  29184. shadowMap.texture.type = shadow.mapType;
  29185. shadowMap.depthTexture = depthTexture;
  29186. return { shadowMap, depthTexture };
  29187. }
  29188. /**
  29189. * Setups the shadow output node.
  29190. *
  29191. * @param {NodeBuilder} builder - A reference to the current node builder.
  29192. * @return {Node<vec3>} The shadow output node.
  29193. */
  29194. setupShadow( builder ) {
  29195. const { renderer } = builder;
  29196. const { light, shadow } = this;
  29197. const shadowMapType = renderer.shadowMap.type;
  29198. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  29199. shadow.camera.updateProjectionMatrix();
  29200. // VSM
  29201. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29202. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  29203. if ( shadowMap.depth > 1 ) {
  29204. if ( ! shadowMap._vsmShadowMapVertical ) {
  29205. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29206. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  29207. }
  29208. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  29209. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  29210. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29211. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  29212. }
  29213. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  29214. } else {
  29215. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29216. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29217. }
  29218. let shadowPassVertical = texture( depthTexture );
  29219. if ( depthTexture.isArrayTexture ) {
  29220. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  29221. }
  29222. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  29223. if ( depthTexture.isArrayTexture ) {
  29224. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  29225. }
  29226. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  29227. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29228. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29229. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  29230. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29231. material.name = 'VSMVertical';
  29232. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  29233. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29234. material.name = 'VSMHorizontal';
  29235. }
  29236. //
  29237. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  29238. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  29239. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  29240. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  29241. //
  29242. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  29243. if ( filterFn === null ) {
  29244. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  29245. }
  29246. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  29247. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  29248. let shadowColor = texture( shadowMap.texture, shadowCoord );
  29249. if ( depthTexture.isArrayTexture ) {
  29250. shadowColor = shadowColor.depth( this.depthLayer );
  29251. }
  29252. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  29253. this.shadowMap = shadowMap;
  29254. this.shadow.map = shadowMap;
  29255. return shadowOutput;
  29256. }
  29257. /**
  29258. * The implementation performs the setup of the output node. An output is only
  29259. * produces if shadow mapping is globally enabled in the renderer.
  29260. *
  29261. * @param {NodeBuilder} builder - A reference to the current node builder.
  29262. * @return {ShaderCallNodeInternal} The output node.
  29263. */
  29264. setup( builder ) {
  29265. if ( builder.renderer.shadowMap.enabled === false ) return;
  29266. return Fn( () => {
  29267. let node = this._node;
  29268. this.setupShadowPosition( builder );
  29269. if ( node === null ) {
  29270. this._node = node = this.setupShadow( builder );
  29271. }
  29272. if ( builder.material.shadowNode ) { // @deprecated, r171
  29273. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  29274. }
  29275. if ( builder.material.receivedShadowNode ) {
  29276. node = builder.material.receivedShadowNode( node );
  29277. }
  29278. return node;
  29279. } )();
  29280. }
  29281. /**
  29282. * Renders the shadow. The logic of this function could be included
  29283. * into {@link ShadowNode#updateShadow} however more specialized shadow
  29284. * nodes might require a custom shadow map rendering. By having a
  29285. * dedicated method, it's easier to overwrite the default behavior.
  29286. *
  29287. * @param {NodeFrame} frame - A reference to the current node frame.
  29288. */
  29289. renderShadow( frame ) {
  29290. const { shadow, shadowMap, light } = this;
  29291. const { renderer, scene } = frame;
  29292. shadow.updateMatrices( light );
  29293. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  29294. renderer.render( scene, shadow.camera );
  29295. }
  29296. /**
  29297. * Updates the shadow.
  29298. *
  29299. * @param {NodeFrame} frame - A reference to the current node frame.
  29300. */
  29301. updateShadow( frame ) {
  29302. const { shadowMap, light, shadow } = this;
  29303. const { renderer, scene, camera } = frame;
  29304. const shadowType = renderer.shadowMap.type;
  29305. const depthVersion = shadowMap.depthTexture.version;
  29306. this._depthVersionCached = depthVersion;
  29307. const _shadowCameraLayer = shadow.camera.layers.mask;
  29308. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  29309. shadow.camera.layers.mask = camera.layers.mask;
  29310. }
  29311. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  29312. const currentMRT = renderer.getMRT();
  29313. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  29314. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  29315. scene.overrideMaterial = getShadowMaterial( light );
  29316. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  29317. renderer.setClearColor( 0x000000, 0 );
  29318. renderer.setRenderTarget( shadowMap );
  29319. this.renderShadow( frame );
  29320. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  29321. // vsm blur pass
  29322. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29323. this.vsmPass( renderer );
  29324. }
  29325. shadow.camera.layers.mask = _shadowCameraLayer;
  29326. restoreRendererAndSceneState( renderer, scene, _rendererState );
  29327. }
  29328. /**
  29329. * For VSM additional render passes are required.
  29330. *
  29331. * @param {Renderer} renderer - A reference to the current renderer.
  29332. */
  29333. vsmPass( renderer ) {
  29334. const { shadow } = this;
  29335. const depth = this.shadowMap.depth;
  29336. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29337. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29338. renderer.setRenderTarget( this.vsmShadowMapVertical );
  29339. _quadMesh.material = this.vsmMaterialVertical;
  29340. _quadMesh.render( renderer );
  29341. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  29342. _quadMesh.material = this.vsmMaterialHorizontal;
  29343. _quadMesh.render( renderer );
  29344. }
  29345. /**
  29346. * Frees the internal resources of this shadow node.
  29347. */
  29348. dispose() {
  29349. this.shadowMap.dispose();
  29350. this.shadowMap = null;
  29351. if ( this.vsmShadowMapVertical !== null ) {
  29352. this.vsmShadowMapVertical.dispose();
  29353. this.vsmShadowMapVertical = null;
  29354. this.vsmMaterialVertical.dispose();
  29355. this.vsmMaterialVertical = null;
  29356. }
  29357. if ( this.vsmShadowMapHorizontal !== null ) {
  29358. this.vsmShadowMapHorizontal.dispose();
  29359. this.vsmShadowMapHorizontal = null;
  29360. this.vsmMaterialHorizontal.dispose();
  29361. this.vsmMaterialHorizontal = null;
  29362. }
  29363. super.dispose();
  29364. }
  29365. /**
  29366. * The implementation performs the update of the shadow map if necessary.
  29367. *
  29368. * @param {NodeFrame} frame - A reference to the current node frame.
  29369. */
  29370. updateBefore( frame ) {
  29371. const { shadow } = this;
  29372. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  29373. if ( needsUpdate ) {
  29374. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  29375. needsUpdate = false;
  29376. }
  29377. this._cameraFrameId[ frame.camera ] = frame.frameId;
  29378. }
  29379. if ( needsUpdate ) {
  29380. this.updateShadow( frame );
  29381. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  29382. shadow.needsUpdate = false;
  29383. }
  29384. }
  29385. }
  29386. }
  29387. /**
  29388. * TSL function for creating an instance of `ShadowNode`.
  29389. *
  29390. * @tsl
  29391. * @function
  29392. * @param {Light} light - The shadow casting light.
  29393. * @param {?LightShadow} [shadow] - The light shadow.
  29394. * @return {ShadowNode} The created shadow node.
  29395. */
  29396. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  29397. const _clearColor$1 = /*@__PURE__*/ new Color();
  29398. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  29399. // vector suitable for 2D texture mapping. This code uses the following layout for the
  29400. // 2D texture:
  29401. //
  29402. // xzXZ
  29403. // y Y
  29404. //
  29405. // Y - Positive y direction
  29406. // y - Negative y direction
  29407. // X - Positive x direction
  29408. // x - Negative x direction
  29409. // Z - Positive z direction
  29410. // z - Negative z direction
  29411. //
  29412. // Source and test bed:
  29413. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  29414. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  29415. const v = pos.toVar();
  29416. // Number of texels to avoid at the edge of each square
  29417. const absV = abs( v );
  29418. // Intersect unit cube
  29419. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  29420. absV.mulAssign( scaleToCube );
  29421. // Apply scale to avoid seams
  29422. // two texels less per square (one texel will do for NEAREST)
  29423. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  29424. // Unwrap
  29425. // space: -1 ... 1 range for each square
  29426. //
  29427. // #X## dim := ( 4 , 2 )
  29428. // # # center := ( 1 , 1 )
  29429. const planar = vec2( v.xy ).toVar();
  29430. const almostATexel = texelSizeY.mul( 1.5 );
  29431. const almostOne = almostATexel.oneMinus();
  29432. If( absV.z.greaterThanEqual( almostOne ), () => {
  29433. If( v.z.greaterThan( 0.0 ), () => {
  29434. planar.x.assign( sub( 4.0, v.x ) );
  29435. } );
  29436. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  29437. const signX = sign( v.x );
  29438. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  29439. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  29440. const signY = sign( v.y );
  29441. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  29442. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  29443. } );
  29444. // Transform to UV space
  29445. // scale := 0.5 / dim
  29446. // translate := ( center + 0.5 ) / dim
  29447. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  29448. } ).setLayout( {
  29449. name: 'cubeToUV',
  29450. type: 'vec2',
  29451. inputs: [
  29452. { name: 'pos', type: 'vec3' },
  29453. { name: 'texelSizeY', type: 'float' }
  29454. ]
  29455. } );
  29456. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  29457. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  29458. } );
  29459. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  29460. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29461. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  29462. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  29463. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  29464. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  29465. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  29466. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  29467. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  29468. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  29469. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  29470. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  29471. .mul( 1.0 / 9.0 );
  29472. } );
  29473. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  29474. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  29475. // the vector from the light to the world-space position of the fragment.
  29476. const lightToPosition = shadowCoord.xyz.toVar();
  29477. const lightToPositionLength = lightToPosition.length();
  29478. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  29479. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  29480. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29481. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  29482. const result = float( 1.0 ).toVar();
  29483. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  29484. // dp = normalized distance from light to fragment position
  29485. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  29486. dp.addAssign( bias );
  29487. // bd3D = base direction 3D
  29488. const bd3D = lightToPosition.normalize();
  29489. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  29490. // percentage-closer filtering
  29491. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  29492. } );
  29493. return result;
  29494. } );
  29495. const _viewport = /*@__PURE__*/ new Vector4();
  29496. const _viewportSize = /*@__PURE__*/ new Vector2();
  29497. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  29498. /**
  29499. * Represents the shadow implementation for point light nodes.
  29500. *
  29501. * @augments ShadowNode
  29502. */
  29503. class PointShadowNode extends ShadowNode {
  29504. static get type() {
  29505. return 'PointShadowNode';
  29506. }
  29507. /**
  29508. * Constructs a new point shadow node.
  29509. *
  29510. * @param {PointLight} light - The shadow casting point light.
  29511. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  29512. */
  29513. constructor( light, shadow = null ) {
  29514. super( light, shadow );
  29515. }
  29516. /**
  29517. * Overwrites the default implementation to return point light shadow specific
  29518. * filtering functions.
  29519. *
  29520. * @param {number} type - The shadow type.
  29521. * @return {Function} The filtering function.
  29522. */
  29523. getShadowFilterFn( type ) {
  29524. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  29525. }
  29526. /**
  29527. * Overwrites the default implementation so the unaltered shadow position is used.
  29528. *
  29529. * @param {NodeBuilder} builder - A reference to the current node builder.
  29530. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29531. * @return {Node<vec3>} The shadow coordinates.
  29532. */
  29533. setupShadowCoord( builder, shadowPosition ) {
  29534. return shadowPosition;
  29535. }
  29536. /**
  29537. * Overwrites the default implementation to only use point light specific
  29538. * shadow filter functions.
  29539. *
  29540. * @param {NodeBuilder} builder - A reference to the current node builder.
  29541. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29542. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29543. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  29544. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29545. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29546. * @param {LightShadow} inputs.shadow - The light shadow.
  29547. * @return {Node<float>} The result node of the shadow filtering.
  29548. */
  29549. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  29550. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  29551. }
  29552. /**
  29553. * Overwrites the default implementation with point light specific
  29554. * rendering code.
  29555. *
  29556. * @param {NodeFrame} frame - A reference to the current node frame.
  29557. */
  29558. renderShadow( frame ) {
  29559. const { shadow, shadowMap, light } = this;
  29560. const { renderer, scene } = frame;
  29561. const shadowFrameExtents = shadow.getFrameExtents();
  29562. _shadowMapSize.copy( shadow.mapSize );
  29563. _shadowMapSize.multiply( shadowFrameExtents );
  29564. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  29565. _viewportSize.copy( shadow.mapSize );
  29566. //
  29567. const previousAutoClear = renderer.autoClear;
  29568. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  29569. const previousClearAlpha = renderer.getClearAlpha();
  29570. renderer.autoClear = false;
  29571. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  29572. renderer.clear();
  29573. const viewportCount = shadow.getViewportCount();
  29574. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  29575. const viewport = shadow.getViewport( vp );
  29576. const x = _viewportSize.x * viewport.x;
  29577. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  29578. _viewport.set(
  29579. x,
  29580. y,
  29581. _viewportSize.x * viewport.z,
  29582. _viewportSize.y * viewport.w
  29583. );
  29584. shadowMap.viewport.copy( _viewport );
  29585. shadow.updateMatrices( light, vp );
  29586. renderer.render( scene, shadow.camera );
  29587. }
  29588. //
  29589. renderer.autoClear = previousAutoClear;
  29590. renderer.setClearColor( previousClearColor, previousClearAlpha );
  29591. }
  29592. }
  29593. /**
  29594. * TSL function for creating an instance of `PointShadowNode`.
  29595. *
  29596. * @tsl
  29597. * @function
  29598. * @param {PointLight} light - The shadow casting point light.
  29599. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  29600. * @return {PointShadowNode} The created point shadow node.
  29601. */
  29602. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  29603. /**
  29604. * Base class for analytic light nodes.
  29605. *
  29606. * @augments LightingNode
  29607. */
  29608. class AnalyticLightNode extends LightingNode {
  29609. static get type() {
  29610. return 'AnalyticLightNode';
  29611. }
  29612. /**
  29613. * Constructs a new analytic light node.
  29614. *
  29615. * @param {?Light} [light=null] - The light source.
  29616. */
  29617. constructor( light = null ) {
  29618. super();
  29619. /**
  29620. * The light source.
  29621. *
  29622. * @type {?Light}
  29623. * @default null
  29624. */
  29625. this.light = light;
  29626. /**
  29627. * The light's color value.
  29628. *
  29629. * @type {Color}
  29630. */
  29631. this.color = new Color();
  29632. /**
  29633. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  29634. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  29635. *
  29636. * @type {Node}
  29637. */
  29638. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  29639. /**
  29640. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  29641. * The final color node is represented by a different node when using shadows.
  29642. *
  29643. * @type {?Node}
  29644. * @default null
  29645. */
  29646. this.baseColorNode = null;
  29647. /**
  29648. * Represents the light's shadow.
  29649. *
  29650. * @type {?ShadowNode}
  29651. * @default null
  29652. */
  29653. this.shadowNode = null;
  29654. /**
  29655. * Represents the light's shadow color.
  29656. *
  29657. * @type {?Node}
  29658. * @default null
  29659. */
  29660. this.shadowColorNode = null;
  29661. /**
  29662. * This flag can be used for type testing.
  29663. *
  29664. * @type {boolean}
  29665. * @readonly
  29666. * @default true
  29667. */
  29668. this.isAnalyticLightNode = true;
  29669. /**
  29670. * Overwritten since analytic light nodes are updated
  29671. * once per frame.
  29672. *
  29673. * @type {string}
  29674. * @default 'frame'
  29675. */
  29676. this.updateType = NodeUpdateType.FRAME;
  29677. }
  29678. getHash() {
  29679. return this.light.uuid;
  29680. }
  29681. /**
  29682. * Returns a node representing a direction vector which points from the current
  29683. * position in view space to the light's position in view space.
  29684. *
  29685. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29686. * @return {Node<vec3>} The light vector node.
  29687. */
  29688. getLightVector( builder ) {
  29689. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  29690. }
  29691. /**
  29692. * Sets up the direct lighting for the analytic light node.
  29693. *
  29694. * @abstract
  29695. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29696. * @return {Object|undefined} The direct light data (color and direction).
  29697. */
  29698. setupDirect( /*builder*/ ) { }
  29699. /**
  29700. * Sets up the direct rect area lighting for the analytic light node.
  29701. *
  29702. * @abstract
  29703. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29704. * @return {Object|undefined} The direct rect area light data.
  29705. */
  29706. setupDirectRectArea( /*builder*/ ) { }
  29707. /**
  29708. * Setups the shadow node for this light. The method exists so concrete light classes
  29709. * can setup different types of shadow nodes.
  29710. *
  29711. * @return {ShadowNode} The created shadow node.
  29712. */
  29713. setupShadowNode() {
  29714. return shadow( this.light );
  29715. }
  29716. /**
  29717. * Setups the shadow for this light. This method is only executed if the light
  29718. * cast shadows and the current build object receives shadows. It incorporates
  29719. * shadows into the lighting computation.
  29720. *
  29721. * @param {NodeBuilder} builder - The current node builder.
  29722. */
  29723. setupShadow( builder ) {
  29724. const { renderer } = builder;
  29725. if ( renderer.shadowMap.enabled === false ) return;
  29726. let shadowColorNode = this.shadowColorNode;
  29727. if ( shadowColorNode === null ) {
  29728. const customShadowNode = this.light.shadow.shadowNode;
  29729. let shadowNode;
  29730. if ( customShadowNode !== undefined ) {
  29731. shadowNode = nodeObject( customShadowNode );
  29732. } else {
  29733. shadowNode = this.setupShadowNode();
  29734. }
  29735. this.shadowNode = shadowNode;
  29736. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  29737. this.baseColorNode = this.colorNode;
  29738. }
  29739. //
  29740. this.colorNode = shadowColorNode;
  29741. }
  29742. /**
  29743. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  29744. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  29745. * invocate the respective interface methods.
  29746. *
  29747. * @param {NodeBuilder} builder - The current node builder.
  29748. */
  29749. setup( builder ) {
  29750. this.colorNode = this.baseColorNode || this.colorNode;
  29751. if ( this.light.castShadow ) {
  29752. if ( builder.object.receiveShadow ) {
  29753. this.setupShadow( builder );
  29754. }
  29755. } else if ( this.shadowNode !== null ) {
  29756. this.shadowNode.dispose();
  29757. this.shadowNode = null;
  29758. this.shadowColorNode = null;
  29759. }
  29760. const directLightData = this.setupDirect( builder );
  29761. const directRectAreaLightData = this.setupDirectRectArea( builder );
  29762. if ( directLightData ) {
  29763. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  29764. }
  29765. if ( directRectAreaLightData ) {
  29766. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  29767. }
  29768. }
  29769. /**
  29770. * The update method is used to update light uniforms per frame.
  29771. * Potentially overwritten in concrete light nodes to update light
  29772. * specific uniforms.
  29773. *
  29774. * @param {NodeFrame} frame - A reference to the current node frame.
  29775. */
  29776. update( /*frame*/ ) {
  29777. const { light } = this;
  29778. this.color.copy( light.color ).multiplyScalar( light.intensity );
  29779. }
  29780. }
  29781. /**
  29782. * Represents a `discard` shader operation in TSL.
  29783. *
  29784. * @method
  29785. * @param {Object} inputs - The input parameter object.
  29786. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  29787. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  29788. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  29789. * @return {Node<float>} The distance falloff.
  29790. */
  29791. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  29792. // based upon Frostbite 3 Moving to Physically-based Rendering
  29793. // page 32, equation 26: E[window1]
  29794. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29795. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  29796. return cutoffDistance.greaterThan( 0 ).select(
  29797. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  29798. distanceFalloff
  29799. );
  29800. } ); // validated
  29801. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  29802. const lightDirection = lightVector.normalize();
  29803. const lightDistance = lightVector.length();
  29804. const attenuation = getDistanceAttenuation( {
  29805. lightDistance,
  29806. cutoffDistance,
  29807. decayExponent
  29808. } );
  29809. const lightColor = color.mul( attenuation );
  29810. return { lightDirection, lightColor };
  29811. };
  29812. /**
  29813. * Module for representing point lights as nodes.
  29814. *
  29815. * @augments AnalyticLightNode
  29816. */
  29817. class PointLightNode extends AnalyticLightNode {
  29818. static get type() {
  29819. return 'PointLightNode';
  29820. }
  29821. /**
  29822. * Constructs a new point light node.
  29823. *
  29824. * @param {?PointLight} [light=null] - The point light source.
  29825. */
  29826. constructor( light = null ) {
  29827. super( light );
  29828. /**
  29829. * Uniform node representing the cutoff distance.
  29830. *
  29831. * @type {UniformNode<float>}
  29832. */
  29833. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  29834. /**
  29835. * Uniform node representing the decay exponent.
  29836. *
  29837. * @type {UniformNode<float>}
  29838. */
  29839. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  29840. }
  29841. /**
  29842. * Overwritten to updated point light specific uniforms.
  29843. *
  29844. * @param {NodeFrame} frame - A reference to the current node frame.
  29845. */
  29846. update( frame ) {
  29847. const { light } = this;
  29848. super.update( frame );
  29849. this.cutoffDistanceNode.value = light.distance;
  29850. this.decayExponentNode.value = light.decay;
  29851. }
  29852. /**
  29853. * Overwritten to setup point light specific shadow.
  29854. *
  29855. * @return {PointShadowNode}
  29856. */
  29857. setupShadowNode() {
  29858. return pointShadow( this.light );
  29859. }
  29860. setupDirect( builder ) {
  29861. return directPointLight( {
  29862. color: this.colorNode,
  29863. lightVector: this.getLightVector( builder ),
  29864. cutoffDistance: this.cutoffDistanceNode,
  29865. decayExponent: this.decayExponentNode
  29866. } );
  29867. }
  29868. }
  29869. /**
  29870. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  29871. *
  29872. * @tsl
  29873. * @function
  29874. * @param {Node<vec2>} coord - The uv coordinates.
  29875. * @return {Node<float>} The result data.
  29876. */
  29877. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  29878. const uv = coord.mul( 2.0 );
  29879. const cx = uv.x.floor();
  29880. const cy = uv.y.floor();
  29881. const result = cx.add( cy ).mod( 2.0 );
  29882. return result.sign();
  29883. } );
  29884. /**
  29885. * Generates a circle based on the uv coordinates.
  29886. *
  29887. * @tsl
  29888. * @function
  29889. * @param {Node<vec2>} coord - The uv to generate the circle.
  29890. * @return {Node<float>} The circle shape.
  29891. */
  29892. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  29893. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  29894. let alpha;
  29895. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  29896. const dlen = float( len2.fwidth() ).toVar();
  29897. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  29898. } else {
  29899. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  29900. }
  29901. return alpha;
  29902. } );
  29903. // Three.js Transpiler
  29904. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  29905. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  29906. const f = float( f_immutable ).toVar();
  29907. const t = float( t_immutable ).toVar();
  29908. const b = bool( b_immutable ).toVar();
  29909. return select( b, t, f );
  29910. } ).setLayout( {
  29911. name: 'mx_select',
  29912. type: 'float',
  29913. inputs: [
  29914. { name: 'b', type: 'bool' },
  29915. { name: 't', type: 'float' },
  29916. { name: 'f', type: 'float' }
  29917. ]
  29918. } );
  29919. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  29920. const b = bool( b_immutable ).toVar();
  29921. const val = float( val_immutable ).toVar();
  29922. return select( b, val.negate(), val );
  29923. } ).setLayout( {
  29924. name: 'mx_negate_if',
  29925. type: 'float',
  29926. inputs: [
  29927. { name: 'val', type: 'float' },
  29928. { name: 'b', type: 'bool' }
  29929. ]
  29930. } );
  29931. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29932. const x = float( x_immutable ).toVar();
  29933. return int( floor( x ) );
  29934. } ).setLayout( {
  29935. name: 'mx_floor',
  29936. type: 'int',
  29937. inputs: [
  29938. { name: 'x', type: 'float' }
  29939. ]
  29940. } );
  29941. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  29942. const x = float( x_immutable ).toVar();
  29943. i.assign( mx_floor( x ) );
  29944. return x.sub( float( i ) );
  29945. } );
  29946. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  29947. const t = float( t_immutable ).toVar();
  29948. const s = float( s_immutable ).toVar();
  29949. const v3 = float( v3_immutable ).toVar();
  29950. const v2 = float( v2_immutable ).toVar();
  29951. const v1 = float( v1_immutable ).toVar();
  29952. const v0 = float( v0_immutable ).toVar();
  29953. const s1 = float( sub( 1.0, s ) ).toVar();
  29954. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29955. } ).setLayout( {
  29956. name: 'mx_bilerp_0',
  29957. type: 'float',
  29958. inputs: [
  29959. { name: 'v0', type: 'float' },
  29960. { name: 'v1', type: 'float' },
  29961. { name: 'v2', type: 'float' },
  29962. { name: 'v3', type: 'float' },
  29963. { name: 's', type: 'float' },
  29964. { name: 't', type: 'float' }
  29965. ]
  29966. } );
  29967. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  29968. const t = float( t_immutable ).toVar();
  29969. const s = float( s_immutable ).toVar();
  29970. const v3 = vec3( v3_immutable ).toVar();
  29971. const v2 = vec3( v2_immutable ).toVar();
  29972. const v1 = vec3( v1_immutable ).toVar();
  29973. const v0 = vec3( v0_immutable ).toVar();
  29974. const s1 = float( sub( 1.0, s ) ).toVar();
  29975. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29976. } ).setLayout( {
  29977. name: 'mx_bilerp_1',
  29978. type: 'vec3',
  29979. inputs: [
  29980. { name: 'v0', type: 'vec3' },
  29981. { name: 'v1', type: 'vec3' },
  29982. { name: 'v2', type: 'vec3' },
  29983. { name: 'v3', type: 'vec3' },
  29984. { name: 's', type: 'float' },
  29985. { name: 't', type: 'float' }
  29986. ]
  29987. } );
  29988. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  29989. 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 ] ) => {
  29990. const r = float( r_immutable ).toVar();
  29991. const t = float( t_immutable ).toVar();
  29992. const s = float( s_immutable ).toVar();
  29993. const v7 = float( v7_immutable ).toVar();
  29994. const v6 = float( v6_immutable ).toVar();
  29995. const v5 = float( v5_immutable ).toVar();
  29996. const v4 = float( v4_immutable ).toVar();
  29997. const v3 = float( v3_immutable ).toVar();
  29998. const v2 = float( v2_immutable ).toVar();
  29999. const v1 = float( v1_immutable ).toVar();
  30000. const v0 = float( v0_immutable ).toVar();
  30001. const s1 = float( sub( 1.0, s ) ).toVar();
  30002. const t1 = float( sub( 1.0, t ) ).toVar();
  30003. const r1 = float( sub( 1.0, r ) ).toVar();
  30004. 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 ) ) ) ) ) );
  30005. } ).setLayout( {
  30006. name: 'mx_trilerp_0',
  30007. type: 'float',
  30008. inputs: [
  30009. { name: 'v0', type: 'float' },
  30010. { name: 'v1', type: 'float' },
  30011. { name: 'v2', type: 'float' },
  30012. { name: 'v3', type: 'float' },
  30013. { name: 'v4', type: 'float' },
  30014. { name: 'v5', type: 'float' },
  30015. { name: 'v6', type: 'float' },
  30016. { name: 'v7', type: 'float' },
  30017. { name: 's', type: 'float' },
  30018. { name: 't', type: 'float' },
  30019. { name: 'r', type: 'float' }
  30020. ]
  30021. } );
  30022. 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 ] ) => {
  30023. const r = float( r_immutable ).toVar();
  30024. const t = float( t_immutable ).toVar();
  30025. const s = float( s_immutable ).toVar();
  30026. const v7 = vec3( v7_immutable ).toVar();
  30027. const v6 = vec3( v6_immutable ).toVar();
  30028. const v5 = vec3( v5_immutable ).toVar();
  30029. const v4 = vec3( v4_immutable ).toVar();
  30030. const v3 = vec3( v3_immutable ).toVar();
  30031. const v2 = vec3( v2_immutable ).toVar();
  30032. const v1 = vec3( v1_immutable ).toVar();
  30033. const v0 = vec3( v0_immutable ).toVar();
  30034. const s1 = float( sub( 1.0, s ) ).toVar();
  30035. const t1 = float( sub( 1.0, t ) ).toVar();
  30036. const r1 = float( sub( 1.0, r ) ).toVar();
  30037. 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 ) ) ) ) ) );
  30038. } ).setLayout( {
  30039. name: 'mx_trilerp_1',
  30040. type: 'vec3',
  30041. inputs: [
  30042. { name: 'v0', type: 'vec3' },
  30043. { name: 'v1', type: 'vec3' },
  30044. { name: 'v2', type: 'vec3' },
  30045. { name: 'v3', type: 'vec3' },
  30046. { name: 'v4', type: 'vec3' },
  30047. { name: 'v5', type: 'vec3' },
  30048. { name: 'v6', type: 'vec3' },
  30049. { name: 'v7', type: 'vec3' },
  30050. { name: 's', type: 'float' },
  30051. { name: 't', type: 'float' },
  30052. { name: 'r', type: 'float' }
  30053. ]
  30054. } );
  30055. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  30056. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30057. const y = float( y_immutable ).toVar();
  30058. const x = float( x_immutable ).toVar();
  30059. const hash = uint( hash_immutable ).toVar();
  30060. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  30061. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  30062. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  30063. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30064. } ).setLayout( {
  30065. name: 'mx_gradient_float_0',
  30066. type: 'float',
  30067. inputs: [
  30068. { name: 'hash', type: 'uint' },
  30069. { name: 'x', type: 'float' },
  30070. { name: 'y', type: 'float' }
  30071. ]
  30072. } );
  30073. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30074. const z = float( z_immutable ).toVar();
  30075. const y = float( y_immutable ).toVar();
  30076. const x = float( x_immutable ).toVar();
  30077. const hash = uint( hash_immutable ).toVar();
  30078. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  30079. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  30080. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  30081. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30082. } ).setLayout( {
  30083. name: 'mx_gradient_float_1',
  30084. type: 'float',
  30085. inputs: [
  30086. { name: 'hash', type: 'uint' },
  30087. { name: 'x', type: 'float' },
  30088. { name: 'y', type: 'float' },
  30089. { name: 'z', type: 'float' }
  30090. ]
  30091. } );
  30092. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  30093. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30094. const y = float( y_immutable ).toVar();
  30095. const x = float( x_immutable ).toVar();
  30096. const hash = uvec3( hash_immutable ).toVar();
  30097. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  30098. } ).setLayout( {
  30099. name: 'mx_gradient_vec3_0',
  30100. type: 'vec3',
  30101. inputs: [
  30102. { name: 'hash', type: 'uvec3' },
  30103. { name: 'x', type: 'float' },
  30104. { name: 'y', type: 'float' }
  30105. ]
  30106. } );
  30107. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30108. const z = float( z_immutable ).toVar();
  30109. const y = float( y_immutable ).toVar();
  30110. const x = float( x_immutable ).toVar();
  30111. const hash = uvec3( hash_immutable ).toVar();
  30112. 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 ) );
  30113. } ).setLayout( {
  30114. name: 'mx_gradient_vec3_1',
  30115. type: 'vec3',
  30116. inputs: [
  30117. { name: 'hash', type: 'uvec3' },
  30118. { name: 'x', type: 'float' },
  30119. { name: 'y', type: 'float' },
  30120. { name: 'z', type: 'float' }
  30121. ]
  30122. } );
  30123. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  30124. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30125. const v = float( v_immutable ).toVar();
  30126. return mul( 0.6616, v );
  30127. } ).setLayout( {
  30128. name: 'mx_gradient_scale2d_0',
  30129. type: 'float',
  30130. inputs: [
  30131. { name: 'v', type: 'float' }
  30132. ]
  30133. } );
  30134. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30135. const v = float( v_immutable ).toVar();
  30136. return mul( 0.9820, v );
  30137. } ).setLayout( {
  30138. name: 'mx_gradient_scale3d_0',
  30139. type: 'float',
  30140. inputs: [
  30141. { name: 'v', type: 'float' }
  30142. ]
  30143. } );
  30144. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30145. const v = vec3( v_immutable ).toVar();
  30146. return mul( 0.6616, v );
  30147. } ).setLayout( {
  30148. name: 'mx_gradient_scale2d_1',
  30149. type: 'vec3',
  30150. inputs: [
  30151. { name: 'v', type: 'vec3' }
  30152. ]
  30153. } );
  30154. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  30155. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30156. const v = vec3( v_immutable ).toVar();
  30157. return mul( 0.9820, v );
  30158. } ).setLayout( {
  30159. name: 'mx_gradient_scale3d_1',
  30160. type: 'vec3',
  30161. inputs: [
  30162. { name: 'v', type: 'vec3' }
  30163. ]
  30164. } );
  30165. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  30166. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  30167. const k = int( k_immutable ).toVar();
  30168. const x = uint( x_immutable ).toVar();
  30169. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  30170. } ).setLayout( {
  30171. name: 'mx_rotl32',
  30172. type: 'uint',
  30173. inputs: [
  30174. { name: 'x', type: 'uint' },
  30175. { name: 'k', type: 'int' }
  30176. ]
  30177. } );
  30178. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  30179. a.subAssign( c );
  30180. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  30181. c.addAssign( b );
  30182. b.subAssign( a );
  30183. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  30184. a.addAssign( c );
  30185. c.subAssign( b );
  30186. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  30187. b.addAssign( a );
  30188. a.subAssign( c );
  30189. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  30190. c.addAssign( b );
  30191. b.subAssign( a );
  30192. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  30193. a.addAssign( c );
  30194. c.subAssign( b );
  30195. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  30196. b.addAssign( a );
  30197. } );
  30198. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  30199. const c = uint( c_immutable ).toVar();
  30200. const b = uint( b_immutable ).toVar();
  30201. const a = uint( a_immutable ).toVar();
  30202. c.bitXorAssign( b );
  30203. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  30204. a.bitXorAssign( c );
  30205. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  30206. b.bitXorAssign( a );
  30207. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  30208. c.bitXorAssign( b );
  30209. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  30210. a.bitXorAssign( c );
  30211. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  30212. b.bitXorAssign( a );
  30213. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  30214. c.bitXorAssign( b );
  30215. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  30216. return c;
  30217. } ).setLayout( {
  30218. name: 'mx_bjfinal',
  30219. type: 'uint',
  30220. inputs: [
  30221. { name: 'a', type: 'uint' },
  30222. { name: 'b', type: 'uint' },
  30223. { name: 'c', type: 'uint' }
  30224. ]
  30225. } );
  30226. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  30227. const bits = uint( bits_immutable ).toVar();
  30228. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  30229. } ).setLayout( {
  30230. name: 'mx_bits_to_01',
  30231. type: 'float',
  30232. inputs: [
  30233. { name: 'bits', type: 'uint' }
  30234. ]
  30235. } );
  30236. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  30237. const t = float( t_immutable ).toVar();
  30238. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  30239. } ).setLayout( {
  30240. name: 'mx_fade',
  30241. type: 'float',
  30242. inputs: [
  30243. { name: 't', type: 'float' }
  30244. ]
  30245. } );
  30246. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30247. const x = int( x_immutable ).toVar();
  30248. const len = uint( uint( 1 ) ).toVar();
  30249. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  30250. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  30251. } ).setLayout( {
  30252. name: 'mx_hash_int_0',
  30253. type: 'uint',
  30254. inputs: [
  30255. { name: 'x', type: 'int' }
  30256. ]
  30257. } );
  30258. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30259. const y = int( y_immutable ).toVar();
  30260. const x = int( x_immutable ).toVar();
  30261. const len = uint( uint( 2 ) ).toVar();
  30262. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30263. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30264. a.addAssign( uint( x ) );
  30265. b.addAssign( uint( y ) );
  30266. return mx_bjfinal( a, b, c );
  30267. } ).setLayout( {
  30268. name: 'mx_hash_int_1',
  30269. type: 'uint',
  30270. inputs: [
  30271. { name: 'x', type: 'int' },
  30272. { name: 'y', type: 'int' }
  30273. ]
  30274. } );
  30275. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30276. const z = int( z_immutable ).toVar();
  30277. const y = int( y_immutable ).toVar();
  30278. const x = int( x_immutable ).toVar();
  30279. const len = uint( uint( 3 ) ).toVar();
  30280. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30281. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30282. a.addAssign( uint( x ) );
  30283. b.addAssign( uint( y ) );
  30284. c.addAssign( uint( z ) );
  30285. return mx_bjfinal( a, b, c );
  30286. } ).setLayout( {
  30287. name: 'mx_hash_int_2',
  30288. type: 'uint',
  30289. inputs: [
  30290. { name: 'x', type: 'int' },
  30291. { name: 'y', type: 'int' },
  30292. { name: 'z', type: 'int' }
  30293. ]
  30294. } );
  30295. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  30296. const xx = int( xx_immutable ).toVar();
  30297. const z = int( z_immutable ).toVar();
  30298. const y = int( y_immutable ).toVar();
  30299. const x = int( x_immutable ).toVar();
  30300. const len = uint( uint( 4 ) ).toVar();
  30301. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30302. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30303. a.addAssign( uint( x ) );
  30304. b.addAssign( uint( y ) );
  30305. c.addAssign( uint( z ) );
  30306. mx_bjmix( a, b, c );
  30307. a.addAssign( uint( xx ) );
  30308. return mx_bjfinal( a, b, c );
  30309. } ).setLayout( {
  30310. name: 'mx_hash_int_3',
  30311. type: 'uint',
  30312. inputs: [
  30313. { name: 'x', type: 'int' },
  30314. { name: 'y', type: 'int' },
  30315. { name: 'z', type: 'int' },
  30316. { name: 'xx', type: 'int' }
  30317. ]
  30318. } );
  30319. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  30320. const yy = int( yy_immutable ).toVar();
  30321. const xx = int( xx_immutable ).toVar();
  30322. const z = int( z_immutable ).toVar();
  30323. const y = int( y_immutable ).toVar();
  30324. const x = int( x_immutable ).toVar();
  30325. const len = uint( uint( 5 ) ).toVar();
  30326. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30327. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30328. a.addAssign( uint( x ) );
  30329. b.addAssign( uint( y ) );
  30330. c.addAssign( uint( z ) );
  30331. mx_bjmix( a, b, c );
  30332. a.addAssign( uint( xx ) );
  30333. b.addAssign( uint( yy ) );
  30334. return mx_bjfinal( a, b, c );
  30335. } ).setLayout( {
  30336. name: 'mx_hash_int_4',
  30337. type: 'uint',
  30338. inputs: [
  30339. { name: 'x', type: 'int' },
  30340. { name: 'y', type: 'int' },
  30341. { name: 'z', type: 'int' },
  30342. { name: 'xx', type: 'int' },
  30343. { name: 'yy', type: 'int' }
  30344. ]
  30345. } );
  30346. 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 ] );
  30347. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30348. const y = int( y_immutable ).toVar();
  30349. const x = int( x_immutable ).toVar();
  30350. const h = uint( mx_hash_int( x, y ) ).toVar();
  30351. const result = uvec3().toVar();
  30352. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30353. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30354. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30355. return result;
  30356. } ).setLayout( {
  30357. name: 'mx_hash_vec3_0',
  30358. type: 'uvec3',
  30359. inputs: [
  30360. { name: 'x', type: 'int' },
  30361. { name: 'y', type: 'int' }
  30362. ]
  30363. } );
  30364. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30365. const z = int( z_immutable ).toVar();
  30366. const y = int( y_immutable ).toVar();
  30367. const x = int( x_immutable ).toVar();
  30368. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  30369. const result = uvec3().toVar();
  30370. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30371. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30372. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30373. return result;
  30374. } ).setLayout( {
  30375. name: 'mx_hash_vec3_1',
  30376. type: 'uvec3',
  30377. inputs: [
  30378. { name: 'x', type: 'int' },
  30379. { name: 'y', type: 'int' },
  30380. { name: 'z', type: 'int' }
  30381. ]
  30382. } );
  30383. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  30384. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30385. const p = vec2( p_immutable ).toVar();
  30386. const X = int().toVar(), Y = int().toVar();
  30387. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30388. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30389. const u = float( mx_fade( fx ) ).toVar();
  30390. const v = float( mx_fade( fy ) ).toVar();
  30391. 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();
  30392. return mx_gradient_scale2d( result );
  30393. } ).setLayout( {
  30394. name: 'mx_perlin_noise_float_0',
  30395. type: 'float',
  30396. inputs: [
  30397. { name: 'p', type: 'vec2' }
  30398. ]
  30399. } );
  30400. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30401. const p = vec3( p_immutable ).toVar();
  30402. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30403. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30404. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30405. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  30406. const u = float( mx_fade( fx ) ).toVar();
  30407. const v = float( mx_fade( fy ) ).toVar();
  30408. const w = float( mx_fade( fz ) ).toVar();
  30409. 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();
  30410. return mx_gradient_scale3d( result );
  30411. } ).setLayout( {
  30412. name: 'mx_perlin_noise_float_1',
  30413. type: 'float',
  30414. inputs: [
  30415. { name: 'p', type: 'vec3' }
  30416. ]
  30417. } );
  30418. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  30419. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30420. const p = vec2( p_immutable ).toVar();
  30421. const X = int().toVar(), Y = int().toVar();
  30422. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30423. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30424. const u = float( mx_fade( fx ) ).toVar();
  30425. const v = float( mx_fade( fy ) ).toVar();
  30426. 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();
  30427. return mx_gradient_scale2d( result );
  30428. } ).setLayout( {
  30429. name: 'mx_perlin_noise_vec3_0',
  30430. type: 'vec3',
  30431. inputs: [
  30432. { name: 'p', type: 'vec2' }
  30433. ]
  30434. } );
  30435. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30436. const p = vec3( p_immutable ).toVar();
  30437. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30438. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30439. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30440. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  30441. const u = float( mx_fade( fx ) ).toVar();
  30442. const v = float( mx_fade( fy ) ).toVar();
  30443. const w = float( mx_fade( fz ) ).toVar();
  30444. 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();
  30445. return mx_gradient_scale3d( result );
  30446. } ).setLayout( {
  30447. name: 'mx_perlin_noise_vec3_1',
  30448. type: 'vec3',
  30449. inputs: [
  30450. { name: 'p', type: 'vec3' }
  30451. ]
  30452. } );
  30453. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  30454. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30455. const p = float( p_immutable ).toVar();
  30456. const ix = int( mx_floor( p ) ).toVar();
  30457. return mx_bits_to_01( mx_hash_int( ix ) );
  30458. } ).setLayout( {
  30459. name: 'mx_cell_noise_float_0',
  30460. type: 'float',
  30461. inputs: [
  30462. { name: 'p', type: 'float' }
  30463. ]
  30464. } );
  30465. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30466. const p = vec2( p_immutable ).toVar();
  30467. const ix = int( mx_floor( p.x ) ).toVar();
  30468. const iy = int( mx_floor( p.y ) ).toVar();
  30469. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  30470. } ).setLayout( {
  30471. name: 'mx_cell_noise_float_1',
  30472. type: 'float',
  30473. inputs: [
  30474. { name: 'p', type: 'vec2' }
  30475. ]
  30476. } );
  30477. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30478. const p = vec3( p_immutable ).toVar();
  30479. const ix = int( mx_floor( p.x ) ).toVar();
  30480. const iy = int( mx_floor( p.y ) ).toVar();
  30481. const iz = int( mx_floor( p.z ) ).toVar();
  30482. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  30483. } ).setLayout( {
  30484. name: 'mx_cell_noise_float_2',
  30485. type: 'float',
  30486. inputs: [
  30487. { name: 'p', type: 'vec3' }
  30488. ]
  30489. } );
  30490. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30491. const p = vec4( p_immutable ).toVar();
  30492. const ix = int( mx_floor( p.x ) ).toVar();
  30493. const iy = int( mx_floor( p.y ) ).toVar();
  30494. const iz = int( mx_floor( p.z ) ).toVar();
  30495. const iw = int( mx_floor( p.w ) ).toVar();
  30496. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  30497. } ).setLayout( {
  30498. name: 'mx_cell_noise_float_3',
  30499. type: 'float',
  30500. inputs: [
  30501. { name: 'p', type: 'vec4' }
  30502. ]
  30503. } );
  30504. 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 ] );
  30505. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30506. const p = float( p_immutable ).toVar();
  30507. const ix = int( mx_floor( p ) ).toVar();
  30508. 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 ) ) ) );
  30509. } ).setLayout( {
  30510. name: 'mx_cell_noise_vec3_0',
  30511. type: 'vec3',
  30512. inputs: [
  30513. { name: 'p', type: 'float' }
  30514. ]
  30515. } );
  30516. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30517. const p = vec2( p_immutable ).toVar();
  30518. const ix = int( mx_floor( p.x ) ).toVar();
  30519. const iy = int( mx_floor( p.y ) ).toVar();
  30520. 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 ) ) ) );
  30521. } ).setLayout( {
  30522. name: 'mx_cell_noise_vec3_1',
  30523. type: 'vec3',
  30524. inputs: [
  30525. { name: 'p', type: 'vec2' }
  30526. ]
  30527. } );
  30528. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30529. const p = vec3( p_immutable ).toVar();
  30530. const ix = int( mx_floor( p.x ) ).toVar();
  30531. const iy = int( mx_floor( p.y ) ).toVar();
  30532. const iz = int( mx_floor( p.z ) ).toVar();
  30533. 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 ) ) ) );
  30534. } ).setLayout( {
  30535. name: 'mx_cell_noise_vec3_2',
  30536. type: 'vec3',
  30537. inputs: [
  30538. { name: 'p', type: 'vec3' }
  30539. ]
  30540. } );
  30541. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30542. const p = vec4( p_immutable ).toVar();
  30543. const ix = int( mx_floor( p.x ) ).toVar();
  30544. const iy = int( mx_floor( p.y ) ).toVar();
  30545. const iz = int( mx_floor( p.z ) ).toVar();
  30546. const iw = int( mx_floor( p.w ) ).toVar();
  30547. 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 ) ) ) );
  30548. } ).setLayout( {
  30549. name: 'mx_cell_noise_vec3_3',
  30550. type: 'vec3',
  30551. inputs: [
  30552. { name: 'p', type: 'vec4' }
  30553. ]
  30554. } );
  30555. 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 ] );
  30556. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30557. const diminish = float( diminish_immutable ).toVar();
  30558. const lacunarity = float( lacunarity_immutable ).toVar();
  30559. const octaves = int( octaves_immutable ).toVar();
  30560. const p = vec3( p_immutable ).toVar();
  30561. const result = float( 0.0 ).toVar();
  30562. const amplitude = float( 1.0 ).toVar();
  30563. Loop( octaves, () => {
  30564. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  30565. amplitude.mulAssign( diminish );
  30566. p.mulAssign( lacunarity );
  30567. } );
  30568. return result;
  30569. } ).setLayout( {
  30570. name: 'mx_fractal_noise_float',
  30571. type: 'float',
  30572. inputs: [
  30573. { name: 'p', type: 'vec3' },
  30574. { name: 'octaves', type: 'int' },
  30575. { name: 'lacunarity', type: 'float' },
  30576. { name: 'diminish', type: 'float' }
  30577. ]
  30578. } );
  30579. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30580. const diminish = float( diminish_immutable ).toVar();
  30581. const lacunarity = float( lacunarity_immutable ).toVar();
  30582. const octaves = int( octaves_immutable ).toVar();
  30583. const p = vec3( p_immutable ).toVar();
  30584. const result = vec3( 0.0 ).toVar();
  30585. const amplitude = float( 1.0 ).toVar();
  30586. Loop( octaves, () => {
  30587. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  30588. amplitude.mulAssign( diminish );
  30589. p.mulAssign( lacunarity );
  30590. } );
  30591. return result;
  30592. } ).setLayout( {
  30593. name: 'mx_fractal_noise_vec3',
  30594. type: 'vec3',
  30595. inputs: [
  30596. { name: 'p', type: 'vec3' },
  30597. { name: 'octaves', type: 'int' },
  30598. { name: 'lacunarity', type: 'float' },
  30599. { name: 'diminish', type: 'float' }
  30600. ]
  30601. } );
  30602. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30603. const diminish = float( diminish_immutable ).toVar();
  30604. const lacunarity = float( lacunarity_immutable ).toVar();
  30605. const octaves = int( octaves_immutable ).toVar();
  30606. const p = vec3( p_immutable ).toVar();
  30607. 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 ) );
  30608. } ).setLayout( {
  30609. name: 'mx_fractal_noise_vec2',
  30610. type: 'vec2',
  30611. inputs: [
  30612. { name: 'p', type: 'vec3' },
  30613. { name: 'octaves', type: 'int' },
  30614. { name: 'lacunarity', type: 'float' },
  30615. { name: 'diminish', type: 'float' }
  30616. ]
  30617. } );
  30618. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30619. const diminish = float( diminish_immutable ).toVar();
  30620. const lacunarity = float( lacunarity_immutable ).toVar();
  30621. const octaves = int( octaves_immutable ).toVar();
  30622. const p = vec3( p_immutable ).toVar();
  30623. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  30624. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  30625. return vec4( c, f );
  30626. } ).setLayout( {
  30627. name: 'mx_fractal_noise_vec4',
  30628. type: 'vec4',
  30629. inputs: [
  30630. { name: 'p', type: 'vec3' },
  30631. { name: 'octaves', type: 'int' },
  30632. { name: 'lacunarity', type: 'float' },
  30633. { name: 'diminish', type: 'float' }
  30634. ]
  30635. } );
  30636. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  30637. const metric = int( metric_immutable ).toVar();
  30638. const jitter = float( jitter_immutable ).toVar();
  30639. const yoff = int( yoff_immutable ).toVar();
  30640. const xoff = int( xoff_immutable ).toVar();
  30641. const y = int( y_immutable ).toVar();
  30642. const x = int( x_immutable ).toVar();
  30643. const p = vec2( p_immutable ).toVar();
  30644. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  30645. const off = vec2( tmp.x, tmp.y ).toVar();
  30646. off.subAssign( 0.5 );
  30647. off.mulAssign( jitter );
  30648. off.addAssign( 0.5 );
  30649. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  30650. const diff = vec2( cellpos.sub( p ) ).toVar();
  30651. If( metric.equal( int( 2 ) ), () => {
  30652. return abs( diff.x ).add( abs( diff.y ) );
  30653. } );
  30654. If( metric.equal( int( 3 ) ), () => {
  30655. return max$1( abs( diff.x ), abs( diff.y ) );
  30656. } );
  30657. return dot( diff, diff );
  30658. } ).setLayout( {
  30659. name: 'mx_worley_distance_0',
  30660. type: 'float',
  30661. inputs: [
  30662. { name: 'p', type: 'vec2' },
  30663. { name: 'x', type: 'int' },
  30664. { name: 'y', type: 'int' },
  30665. { name: 'xoff', type: 'int' },
  30666. { name: 'yoff', type: 'int' },
  30667. { name: 'jitter', type: 'float' },
  30668. { name: 'metric', type: 'int' }
  30669. ]
  30670. } );
  30671. 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 ] ) => {
  30672. const metric = int( metric_immutable ).toVar();
  30673. const jitter = float( jitter_immutable ).toVar();
  30674. const zoff = int( zoff_immutable ).toVar();
  30675. const yoff = int( yoff_immutable ).toVar();
  30676. const xoff = int( xoff_immutable ).toVar();
  30677. const z = int( z_immutable ).toVar();
  30678. const y = int( y_immutable ).toVar();
  30679. const x = int( x_immutable ).toVar();
  30680. const p = vec3( p_immutable ).toVar();
  30681. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  30682. off.subAssign( 0.5 );
  30683. off.mulAssign( jitter );
  30684. off.addAssign( 0.5 );
  30685. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  30686. const diff = vec3( cellpos.sub( p ) ).toVar();
  30687. If( metric.equal( int( 2 ) ), () => {
  30688. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  30689. } );
  30690. If( metric.equal( int( 3 ) ), () => {
  30691. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  30692. } );
  30693. return dot( diff, diff );
  30694. } ).setLayout( {
  30695. name: 'mx_worley_distance_1',
  30696. type: 'float',
  30697. inputs: [
  30698. { name: 'p', type: 'vec3' },
  30699. { name: 'x', type: 'int' },
  30700. { name: 'y', type: 'int' },
  30701. { name: 'z', type: 'int' },
  30702. { name: 'xoff', type: 'int' },
  30703. { name: 'yoff', type: 'int' },
  30704. { name: 'zoff', type: 'int' },
  30705. { name: 'jitter', type: 'float' },
  30706. { name: 'metric', type: 'int' }
  30707. ]
  30708. } );
  30709. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  30710. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30711. const metric = int( metric_immutable ).toVar();
  30712. const jitter = float( jitter_immutable ).toVar();
  30713. const p = vec2( p_immutable ).toVar();
  30714. const X = int().toVar(), Y = int().toVar();
  30715. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30716. const sqdist = float( 1e6 ).toVar();
  30717. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30718. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30719. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30720. sqdist.assign( min$1( sqdist, dist ) );
  30721. } );
  30722. } );
  30723. If( metric.equal( int( 0 ) ), () => {
  30724. sqdist.assign( sqrt( sqdist ) );
  30725. } );
  30726. return sqdist;
  30727. } ).setLayout( {
  30728. name: 'mx_worley_noise_float_0',
  30729. type: 'float',
  30730. inputs: [
  30731. { name: 'p', type: 'vec2' },
  30732. { name: 'jitter', type: 'float' },
  30733. { name: 'metric', type: 'int' }
  30734. ]
  30735. } );
  30736. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30737. const metric = int( metric_immutable ).toVar();
  30738. const jitter = float( jitter_immutable ).toVar();
  30739. const p = vec2( p_immutable ).toVar();
  30740. const X = int().toVar(), Y = int().toVar();
  30741. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30742. const sqdist = vec2( 1e6, 1e6 ).toVar();
  30743. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30744. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30745. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30746. If( dist.lessThan( sqdist.x ), () => {
  30747. sqdist.y.assign( sqdist.x );
  30748. sqdist.x.assign( dist );
  30749. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30750. sqdist.y.assign( dist );
  30751. } );
  30752. } );
  30753. } );
  30754. If( metric.equal( int( 0 ) ), () => {
  30755. sqdist.assign( sqrt( sqdist ) );
  30756. } );
  30757. return sqdist;
  30758. } ).setLayout( {
  30759. name: 'mx_worley_noise_vec2_0',
  30760. type: 'vec2',
  30761. inputs: [
  30762. { name: 'p', type: 'vec2' },
  30763. { name: 'jitter', type: 'float' },
  30764. { name: 'metric', type: 'int' }
  30765. ]
  30766. } );
  30767. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30768. const metric = int( metric_immutable ).toVar();
  30769. const jitter = float( jitter_immutable ).toVar();
  30770. const p = vec2( p_immutable ).toVar();
  30771. const X = int().toVar(), Y = int().toVar();
  30772. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30773. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  30774. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30775. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30776. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30777. If( dist.lessThan( sqdist.x ), () => {
  30778. sqdist.z.assign( sqdist.y );
  30779. sqdist.y.assign( sqdist.x );
  30780. sqdist.x.assign( dist );
  30781. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30782. sqdist.z.assign( sqdist.y );
  30783. sqdist.y.assign( dist );
  30784. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  30785. sqdist.z.assign( dist );
  30786. } );
  30787. } );
  30788. } );
  30789. If( metric.equal( int( 0 ) ), () => {
  30790. sqdist.assign( sqrt( sqdist ) );
  30791. } );
  30792. return sqdist;
  30793. } ).setLayout( {
  30794. name: 'mx_worley_noise_vec3_0',
  30795. type: 'vec3',
  30796. inputs: [
  30797. { name: 'p', type: 'vec2' },
  30798. { name: 'jitter', type: 'float' },
  30799. { name: 'metric', type: 'int' }
  30800. ]
  30801. } );
  30802. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30803. const metric = int( metric_immutable ).toVar();
  30804. const jitter = float( jitter_immutable ).toVar();
  30805. const p = vec3( p_immutable ).toVar();
  30806. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30807. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30808. const sqdist = float( 1e6 ).toVar();
  30809. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30810. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30811. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30812. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30813. sqdist.assign( min$1( sqdist, dist ) );
  30814. } );
  30815. } );
  30816. } );
  30817. If( metric.equal( int( 0 ) ), () => {
  30818. sqdist.assign( sqrt( sqdist ) );
  30819. } );
  30820. return sqdist;
  30821. } ).setLayout( {
  30822. name: 'mx_worley_noise_float_1',
  30823. type: 'float',
  30824. inputs: [
  30825. { name: 'p', type: 'vec3' },
  30826. { name: 'jitter', type: 'float' },
  30827. { name: 'metric', type: 'int' }
  30828. ]
  30829. } );
  30830. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  30831. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30832. const metric = int( metric_immutable ).toVar();
  30833. const jitter = float( jitter_immutable ).toVar();
  30834. const p = vec3( p_immutable ).toVar();
  30835. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30836. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30837. const sqdist = vec2( 1e6, 1e6 ).toVar();
  30838. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30839. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30840. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30841. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30842. If( dist.lessThan( sqdist.x ), () => {
  30843. sqdist.y.assign( sqdist.x );
  30844. sqdist.x.assign( dist );
  30845. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30846. sqdist.y.assign( dist );
  30847. } );
  30848. } );
  30849. } );
  30850. } );
  30851. If( metric.equal( int( 0 ) ), () => {
  30852. sqdist.assign( sqrt( sqdist ) );
  30853. } );
  30854. return sqdist;
  30855. } ).setLayout( {
  30856. name: 'mx_worley_noise_vec2_1',
  30857. type: 'vec2',
  30858. inputs: [
  30859. { name: 'p', type: 'vec3' },
  30860. { name: 'jitter', type: 'float' },
  30861. { name: 'metric', type: 'int' }
  30862. ]
  30863. } );
  30864. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  30865. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30866. const metric = int( metric_immutable ).toVar();
  30867. const jitter = float( jitter_immutable ).toVar();
  30868. const p = vec3( p_immutable ).toVar();
  30869. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30870. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30871. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  30872. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30873. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30874. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30875. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30876. If( dist.lessThan( sqdist.x ), () => {
  30877. sqdist.z.assign( sqdist.y );
  30878. sqdist.y.assign( sqdist.x );
  30879. sqdist.x.assign( dist );
  30880. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30881. sqdist.z.assign( sqdist.y );
  30882. sqdist.y.assign( dist );
  30883. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  30884. sqdist.z.assign( dist );
  30885. } );
  30886. } );
  30887. } );
  30888. } );
  30889. If( metric.equal( int( 0 ) ), () => {
  30890. sqdist.assign( sqrt( sqdist ) );
  30891. } );
  30892. return sqdist;
  30893. } ).setLayout( {
  30894. name: 'mx_worley_noise_vec3_1',
  30895. type: 'vec3',
  30896. inputs: [
  30897. { name: 'p', type: 'vec3' },
  30898. { name: 'jitter', type: 'float' },
  30899. { name: 'metric', type: 'int' }
  30900. ]
  30901. } );
  30902. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  30903. // Unified Noise 2D
  30904. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  30905. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  30906. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  30907. octaves_immutable, lacunarity_immutable, diminish_immutable
  30908. ] ) => {
  30909. const noiseType = int( noiseType_immutable ).toVar();
  30910. const texcoord = vec2( texcoord_immutable ).toVar();
  30911. const freq = vec2( freq_immutable ).toVar();
  30912. const offset = vec2( offset_immutable ).toVar();
  30913. const jitter = float( jitter_immutable ).toVar();
  30914. const outmin = float( outmin_immutable ).toVar();
  30915. const outmax = float( outmax_immutable ).toVar();
  30916. const clampoutput = bool( clampoutput_immutable ).toVar();
  30917. const octaves = int( octaves_immutable ).toVar();
  30918. const lacunarity = float( lacunarity_immutable ).toVar();
  30919. const diminish = float( diminish_immutable ).toVar();
  30920. // Compute input position
  30921. const p = texcoord.mul( freq ).add( offset );
  30922. const result = float( 0.0 ).toVar();
  30923. // Perlin
  30924. If( noiseType.equal( int( 0 ) ), () => {
  30925. result.assign( mx_perlin_noise_vec3( p ) );
  30926. } );
  30927. // Cell
  30928. If( noiseType.equal( int( 1 ) ), () => {
  30929. result.assign( mx_cell_noise_vec3( p ) );
  30930. } );
  30931. // Worley (metric=0 = euclidean)
  30932. If( noiseType.equal( int( 2 ) ), () => {
  30933. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  30934. } );
  30935. // Fractal (use vec3(p, 0.0) for 2D input)
  30936. If( noiseType.equal( int( 3 ) ), () => {
  30937. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  30938. } );
  30939. // Remap output to [outmin, outmax]
  30940. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  30941. // Clamp if requested
  30942. If( clampoutput, () => {
  30943. result.assign( clamp( result, outmin, outmax ) );
  30944. } );
  30945. return result;
  30946. } ).setLayout( {
  30947. name: 'mx_unifiednoise2d',
  30948. type: 'float',
  30949. inputs: [
  30950. { name: 'noiseType', type: 'int' },
  30951. { name: 'texcoord', type: 'vec2' },
  30952. { name: 'freq', type: 'vec2' },
  30953. { name: 'offset', type: 'vec2' },
  30954. { name: 'jitter', type: 'float' },
  30955. { name: 'outmin', type: 'float' },
  30956. { name: 'outmax', type: 'float' },
  30957. { name: 'clampoutput', type: 'bool' },
  30958. { name: 'octaves', type: 'int' },
  30959. { name: 'lacunarity', type: 'float' },
  30960. { name: 'diminish', type: 'float' }
  30961. ]
  30962. } );
  30963. // Unified Noise 3D
  30964. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  30965. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  30966. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  30967. octaves_immutable, lacunarity_immutable, diminish_immutable
  30968. ] ) => {
  30969. const noiseType = int( noiseType_immutable ).toVar();
  30970. const position = vec3( position_immutable ).toVar();
  30971. const freq = vec3( freq_immutable ).toVar();
  30972. const offset = vec3( offset_immutable ).toVar();
  30973. const jitter = float( jitter_immutable ).toVar();
  30974. const outmin = float( outmin_immutable ).toVar();
  30975. const outmax = float( outmax_immutable ).toVar();
  30976. const clampoutput = bool( clampoutput_immutable ).toVar();
  30977. const octaves = int( octaves_immutable ).toVar();
  30978. const lacunarity = float( lacunarity_immutable ).toVar();
  30979. const diminish = float( diminish_immutable ).toVar();
  30980. // Compute input position
  30981. const p = position.mul( freq ).add( offset );
  30982. const result = float( 0.0 ).toVar();
  30983. // Perlin
  30984. If( noiseType.equal( int( 0 ) ), () => {
  30985. result.assign( mx_perlin_noise_vec3( p ) );
  30986. } );
  30987. // Cell
  30988. If( noiseType.equal( int( 1 ) ), () => {
  30989. result.assign( mx_cell_noise_vec3( p ) );
  30990. } );
  30991. // Worley (metric=0 = euclidean)
  30992. If( noiseType.equal( int( 2 ) ), () => {
  30993. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  30994. } );
  30995. // Fractal
  30996. If( noiseType.equal( int( 3 ) ), () => {
  30997. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  30998. } );
  30999. // Remap output to [outmin, outmax]
  31000. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31001. // Clamp if requested
  31002. If( clampoutput, () => {
  31003. result.assign( clamp( result, outmin, outmax ) );
  31004. } );
  31005. return result;
  31006. } ).setLayout( {
  31007. name: 'mx_unifiednoise3d',
  31008. type: 'float',
  31009. inputs: [
  31010. { name: 'noiseType', type: 'int' },
  31011. { name: 'position', type: 'vec3' },
  31012. { name: 'freq', type: 'vec3' },
  31013. { name: 'offset', type: 'vec3' },
  31014. { name: 'jitter', type: 'float' },
  31015. { name: 'outmin', type: 'float' },
  31016. { name: 'outmax', type: 'float' },
  31017. { name: 'clampoutput', type: 'bool' },
  31018. { name: 'octaves', type: 'int' },
  31019. { name: 'lacunarity', type: 'float' },
  31020. { name: 'diminish', type: 'float' }
  31021. ]
  31022. } );
  31023. // Three.js Transpiler
  31024. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  31025. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  31026. const s = hsv.y;
  31027. const v = hsv.z;
  31028. const result = vec3().toVar();
  31029. If( s.lessThan( 0.0001 ), () => {
  31030. result.assign( vec3( v, v, v ) );
  31031. } ).Else( () => {
  31032. let h = hsv.x;
  31033. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  31034. const hi = int( trunc( h ) );
  31035. const f = h.sub( float( hi ) );
  31036. const p = v.mul( s.oneMinus() );
  31037. const q = v.mul( s.mul( f ).oneMinus() );
  31038. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  31039. If( hi.equal( int( 0 ) ), () => {
  31040. result.assign( vec3( v, t, p ) );
  31041. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  31042. result.assign( vec3( q, v, p ) );
  31043. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  31044. result.assign( vec3( p, v, t ) );
  31045. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  31046. result.assign( vec3( p, q, v ) );
  31047. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  31048. result.assign( vec3( t, p, v ) );
  31049. } ).Else( () => {
  31050. result.assign( vec3( v, p, q ) );
  31051. } );
  31052. } );
  31053. return result;
  31054. } ).setLayout( {
  31055. name: 'mx_hsvtorgb',
  31056. type: 'vec3',
  31057. inputs: [
  31058. { name: 'hsv', type: 'vec3' }
  31059. ]
  31060. } );
  31061. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  31062. const c = vec3( c_immutable ).toVar();
  31063. const r = float( c.x ).toVar();
  31064. const g = float( c.y ).toVar();
  31065. const b = float( c.z ).toVar();
  31066. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  31067. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  31068. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  31069. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  31070. v.assign( maxcomp );
  31071. If( maxcomp.greaterThan( 0.0 ), () => {
  31072. s.assign( delta.div( maxcomp ) );
  31073. } ).Else( () => {
  31074. s.assign( 0.0 );
  31075. } );
  31076. If( s.lessThanEqual( 0.0 ), () => {
  31077. h.assign( 0.0 );
  31078. } ).Else( () => {
  31079. If( r.greaterThanEqual( maxcomp ), () => {
  31080. h.assign( g.sub( b ).div( delta ) );
  31081. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  31082. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  31083. } ).Else( () => {
  31084. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  31085. } );
  31086. h.mulAssign( 1.0 / 6.0 );
  31087. If( h.lessThan( 0.0 ), () => {
  31088. h.addAssign( 1.0 );
  31089. } );
  31090. } );
  31091. return vec3( h, s, v );
  31092. } ).setLayout( {
  31093. name: 'mx_rgbtohsv',
  31094. type: 'vec3',
  31095. inputs: [
  31096. { name: 'c', type: 'vec3' }
  31097. ]
  31098. } );
  31099. // Three.js Transpiler
  31100. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  31101. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  31102. const color = vec3( color_immutable ).toVar();
  31103. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  31104. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  31105. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  31106. return mix( linSeg, powSeg, isAbove );
  31107. } ).setLayout( {
  31108. name: 'mx_srgb_texture_to_lin_rec709',
  31109. type: 'vec3',
  31110. inputs: [
  31111. { name: 'color', type: 'vec3' }
  31112. ]
  31113. } );
  31114. const mx_aastep = ( threshold, value ) => {
  31115. threshold = float( threshold );
  31116. value = float( value );
  31117. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  31118. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  31119. };
  31120. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  31121. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  31122. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  31123. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  31124. const mx_ramp4 = (
  31125. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  31126. ) => {
  31127. const u = texcoord.x.clamp();
  31128. const v = texcoord.y.clamp();
  31129. const top = mix( valuetl, valuetr, u );
  31130. const bottom = mix( valuebl, valuebr, u );
  31131. return mix( top, bottom, v );
  31132. };
  31133. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  31134. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  31135. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  31136. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  31137. const mx_safepower = ( in1, in2 = 1 ) => {
  31138. in1 = float( in1 );
  31139. return in1.abs().pow( in2 ).mul( in1.sign() );
  31140. };
  31141. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  31142. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31143. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31144. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31145. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  31146. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  31147. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  31148. return noise_vec4.mul( amplitude ).add( pivot );
  31149. };
  31150. 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 );
  31151. 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 );
  31152. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31153. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31154. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31155. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  31156. 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 );
  31157. 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 );
  31158. 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 );
  31159. 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 );
  31160. // === Moved from MaterialXLoader.js ===
  31161. // Math ops
  31162. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  31163. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  31164. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  31165. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  31166. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  31167. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  31168. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  31169. const mx_timer = () => time;
  31170. const mx_frame = () => frameId;
  31171. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  31172. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  31173. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  31174. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  31175. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  31176. const mx_separate = ( in1, channelOrOut = null ) => {
  31177. if ( typeof channelOrOut === 'string' ) {
  31178. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31179. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  31180. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  31181. }
  31182. if ( typeof channelOrOut === 'number' ) {
  31183. return in1.element( channelOrOut );
  31184. }
  31185. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  31186. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31187. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  31188. }
  31189. return in1;
  31190. };
  31191. const mx_place2d = (
  31192. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  31193. ) => {
  31194. let uv = texcoord;
  31195. if ( pivot ) uv = uv.sub( pivot );
  31196. if ( scale ) uv = uv.mul( scale );
  31197. if ( rotate ) {
  31198. const rad = rotate.mul( Math.PI / 180.0 );
  31199. const cosR = rad.cos();
  31200. const sinR = rad.sin();
  31201. uv = vec2(
  31202. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  31203. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  31204. );
  31205. }
  31206. if ( pivot ) uv = uv.add( pivot );
  31207. if ( offset ) uv = uv.add( offset );
  31208. return uv;
  31209. };
  31210. const mx_rotate2d = ( input, amount ) => {
  31211. input = vec2( input );
  31212. amount = float( amount );
  31213. const radians = amount.mul( Math.PI / 180.0 );
  31214. return rotate( input, radians );
  31215. };
  31216. const mx_rotate3d = ( input, amount, axis ) => {
  31217. input = vec3( input );
  31218. amount = float( amount );
  31219. axis = vec3( axis );
  31220. const radians = amount.mul( Math.PI / 180.0 );
  31221. const nAxis = axis.normalize();
  31222. const cosA = radians.cos();
  31223. const sinA = radians.sin();
  31224. const oneMinusCosA = float( 1 ).sub( cosA );
  31225. const rot =
  31226. input.mul( cosA )
  31227. .add( nAxis.cross( input ).mul( sinA ) )
  31228. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  31229. return rot;
  31230. };
  31231. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  31232. input = vec3( input );
  31233. scale = float( scale );
  31234. return bumpMap( input, scale );
  31235. };
  31236. /**
  31237. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  31238. *
  31239. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  31240. *
  31241. * ```js
  31242. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  31243. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  31244. * ```
  31245. *
  31246. * @tsl
  31247. * @function
  31248. * @param {Node<vec3>} normal - The normal to correct.
  31249. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  31250. * @param {Node<vec3>} cubePos - The cube position.
  31251. * @return {Node<vec3>} The parallax corrected normal.
  31252. */
  31253. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  31254. const nDir = normalize( normal ).toVar();
  31255. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31256. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31257. const rbminmax = vec3().toVar();
  31258. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  31259. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  31260. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  31261. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  31262. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  31263. return boxIntersection.sub( cubePos );
  31264. } );
  31265. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  31266. // normal is assumed to have unit length
  31267. const x = normal.x, y = normal.y, z = normal.z;
  31268. // band 0
  31269. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  31270. // band 1
  31271. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  31272. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  31273. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  31274. // band 2
  31275. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  31276. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  31277. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  31278. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  31279. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  31280. return result;
  31281. } );
  31282. // constants
  31283. var TSL = /*#__PURE__*/Object.freeze({
  31284. __proto__: null,
  31285. BRDF_GGX: BRDF_GGX,
  31286. BRDF_Lambert: BRDF_Lambert,
  31287. BasicPointShadowFilter: BasicPointShadowFilter,
  31288. BasicShadowFilter: BasicShadowFilter,
  31289. Break: Break,
  31290. Const: Const,
  31291. Continue: Continue,
  31292. DFGApprox: DFGApprox,
  31293. D_GGX: D_GGX,
  31294. Discard: Discard,
  31295. EPSILON: EPSILON,
  31296. F_Schlick: F_Schlick,
  31297. Fn: Fn,
  31298. INFINITY: INFINITY,
  31299. If: If,
  31300. Loop: Loop,
  31301. NodeAccess: NodeAccess,
  31302. NodeShaderStage: NodeShaderStage,
  31303. NodeType: NodeType,
  31304. NodeUpdateType: NodeUpdateType,
  31305. OnMaterialUpdate: OnMaterialUpdate,
  31306. OnObjectUpdate: OnObjectUpdate,
  31307. PCFShadowFilter: PCFShadowFilter,
  31308. PCFSoftShadowFilter: PCFSoftShadowFilter,
  31309. PI: PI,
  31310. PI2: PI2,
  31311. PointShadowFilter: PointShadowFilter,
  31312. Return: Return,
  31313. Schlick_to_F0: Schlick_to_F0,
  31314. ScriptableNodeResources: ScriptableNodeResources,
  31315. ShaderNode: ShaderNode,
  31316. Stack: Stack,
  31317. Switch: Switch,
  31318. TBNViewMatrix: TBNViewMatrix,
  31319. VSMShadowFilter: VSMShadowFilter,
  31320. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  31321. Var: Var,
  31322. VarIntent: VarIntent,
  31323. abs: abs,
  31324. acesFilmicToneMapping: acesFilmicToneMapping,
  31325. acos: acos,
  31326. add: add,
  31327. addMethodChaining: addMethodChaining,
  31328. addNodeElement: addNodeElement,
  31329. agxToneMapping: agxToneMapping,
  31330. all: all,
  31331. alphaT: alphaT,
  31332. and: and,
  31333. anisotropy: anisotropy,
  31334. anisotropyB: anisotropyB,
  31335. anisotropyT: anisotropyT,
  31336. any: any,
  31337. append: append,
  31338. array: array,
  31339. arrayBuffer: arrayBuffer,
  31340. asin: asin,
  31341. assign: assign,
  31342. atan: atan,
  31343. atan2: atan2,
  31344. atomicAdd: atomicAdd,
  31345. atomicAnd: atomicAnd,
  31346. atomicFunc: atomicFunc,
  31347. atomicLoad: atomicLoad,
  31348. atomicMax: atomicMax,
  31349. atomicMin: atomicMin,
  31350. atomicOr: atomicOr,
  31351. atomicStore: atomicStore,
  31352. atomicSub: atomicSub,
  31353. atomicXor: atomicXor,
  31354. attenuationColor: attenuationColor,
  31355. attenuationDistance: attenuationDistance,
  31356. attribute: attribute,
  31357. attributeArray: attributeArray,
  31358. backgroundBlurriness: backgroundBlurriness,
  31359. backgroundIntensity: backgroundIntensity,
  31360. backgroundRotation: backgroundRotation,
  31361. batch: batch,
  31362. bentNormalView: bentNormalView,
  31363. billboarding: billboarding,
  31364. bitAnd: bitAnd,
  31365. bitNot: bitNot,
  31366. bitOr: bitOr,
  31367. bitXor: bitXor,
  31368. bitangentGeometry: bitangentGeometry,
  31369. bitangentLocal: bitangentLocal,
  31370. bitangentView: bitangentView,
  31371. bitangentWorld: bitangentWorld,
  31372. bitcast: bitcast,
  31373. blendBurn: blendBurn,
  31374. blendColor: blendColor,
  31375. blendDodge: blendDodge,
  31376. blendOverlay: blendOverlay,
  31377. blendScreen: blendScreen,
  31378. blur: blur,
  31379. bool: bool,
  31380. buffer: buffer,
  31381. bufferAttribute: bufferAttribute,
  31382. bumpMap: bumpMap,
  31383. burn: burn,
  31384. bvec2: bvec2,
  31385. bvec3: bvec3,
  31386. bvec4: bvec4,
  31387. bypass: bypass,
  31388. cache: cache,
  31389. call: call,
  31390. cameraFar: cameraFar,
  31391. cameraIndex: cameraIndex,
  31392. cameraNear: cameraNear,
  31393. cameraNormalMatrix: cameraNormalMatrix,
  31394. cameraPosition: cameraPosition,
  31395. cameraProjectionMatrix: cameraProjectionMatrix,
  31396. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  31397. cameraViewMatrix: cameraViewMatrix,
  31398. cameraViewport: cameraViewport,
  31399. cameraWorldMatrix: cameraWorldMatrix,
  31400. cbrt: cbrt,
  31401. cdl: cdl,
  31402. ceil: ceil,
  31403. checker: checker,
  31404. cineonToneMapping: cineonToneMapping,
  31405. clamp: clamp,
  31406. clearcoat: clearcoat,
  31407. clearcoatNormalView: clearcoatNormalView,
  31408. clearcoatRoughness: clearcoatRoughness,
  31409. code: code,
  31410. color: color,
  31411. colorSpaceToWorking: colorSpaceToWorking,
  31412. colorToDirection: colorToDirection,
  31413. compute: compute,
  31414. computeKernel: computeKernel,
  31415. computeSkinning: computeSkinning,
  31416. context: context,
  31417. convert: convert,
  31418. convertColorSpace: convertColorSpace,
  31419. convertToTexture: convertToTexture,
  31420. cos: cos,
  31421. cross: cross,
  31422. cubeTexture: cubeTexture,
  31423. cubeTextureBase: cubeTextureBase,
  31424. cubeToUV: cubeToUV,
  31425. dFdx: dFdx,
  31426. dFdy: dFdy,
  31427. dashSize: dashSize,
  31428. debug: debug,
  31429. decrement: decrement,
  31430. decrementBefore: decrementBefore,
  31431. defaultBuildStages: defaultBuildStages,
  31432. defaultShaderStages: defaultShaderStages,
  31433. defined: defined,
  31434. degrees: degrees,
  31435. deltaTime: deltaTime,
  31436. densityFog: densityFog,
  31437. densityFogFactor: densityFogFactor,
  31438. depth: depth,
  31439. depthPass: depthPass,
  31440. determinant: determinant,
  31441. difference: difference,
  31442. diffuseColor: diffuseColor,
  31443. directPointLight: directPointLight,
  31444. directionToColor: directionToColor,
  31445. directionToFaceDirection: directionToFaceDirection,
  31446. dispersion: dispersion,
  31447. distance: distance,
  31448. div: div,
  31449. dodge: dodge,
  31450. dot: dot,
  31451. drawIndex: drawIndex,
  31452. dynamicBufferAttribute: dynamicBufferAttribute,
  31453. element: element,
  31454. emissive: emissive,
  31455. equal: equal,
  31456. equals: equals,
  31457. equirectUV: equirectUV,
  31458. exp: exp,
  31459. exp2: exp2,
  31460. expression: expression,
  31461. faceDirection: faceDirection,
  31462. faceForward: faceForward,
  31463. faceforward: faceforward,
  31464. float: float,
  31465. floor: floor,
  31466. fog: fog,
  31467. fract: fract,
  31468. frameGroup: frameGroup,
  31469. frameId: frameId,
  31470. frontFacing: frontFacing,
  31471. fwidth: fwidth,
  31472. gain: gain,
  31473. gapSize: gapSize,
  31474. getConstNodeType: getConstNodeType,
  31475. getCurrentStack: getCurrentStack,
  31476. getDirection: getDirection,
  31477. getDistanceAttenuation: getDistanceAttenuation,
  31478. getGeometryRoughness: getGeometryRoughness,
  31479. getNormalFromDepth: getNormalFromDepth,
  31480. getParallaxCorrectNormal: getParallaxCorrectNormal,
  31481. getRoughness: getRoughness,
  31482. getScreenPosition: getScreenPosition,
  31483. getShIrradianceAt: getShIrradianceAt,
  31484. getShadowMaterial: getShadowMaterial,
  31485. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  31486. getTextureIndex: getTextureIndex,
  31487. getViewPosition: getViewPosition,
  31488. globalId: globalId,
  31489. glsl: glsl,
  31490. glslFn: glslFn,
  31491. grayscale: grayscale,
  31492. greaterThan: greaterThan,
  31493. greaterThanEqual: greaterThanEqual,
  31494. hash: hash,
  31495. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  31496. highpModelViewMatrix: highpModelViewMatrix,
  31497. hue: hue,
  31498. increment: increment,
  31499. incrementBefore: incrementBefore,
  31500. instance: instance,
  31501. instanceIndex: instanceIndex,
  31502. instancedArray: instancedArray,
  31503. instancedBufferAttribute: instancedBufferAttribute,
  31504. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  31505. instancedMesh: instancedMesh,
  31506. int: int,
  31507. inverse: inverse,
  31508. inverseSqrt: inverseSqrt,
  31509. inversesqrt: inversesqrt,
  31510. invocationLocalIndex: invocationLocalIndex,
  31511. invocationSubgroupIndex: invocationSubgroupIndex,
  31512. ior: ior,
  31513. iridescence: iridescence,
  31514. iridescenceIOR: iridescenceIOR,
  31515. iridescenceThickness: iridescenceThickness,
  31516. ivec2: ivec2,
  31517. ivec3: ivec3,
  31518. ivec4: ivec4,
  31519. js: js,
  31520. label: label,
  31521. length: length,
  31522. lengthSq: lengthSq,
  31523. lessThan: lessThan,
  31524. lessThanEqual: lessThanEqual,
  31525. lightPosition: lightPosition,
  31526. lightProjectionUV: lightProjectionUV,
  31527. lightShadowMatrix: lightShadowMatrix,
  31528. lightTargetDirection: lightTargetDirection,
  31529. lightTargetPosition: lightTargetPosition,
  31530. lightViewPosition: lightViewPosition,
  31531. lightingContext: lightingContext,
  31532. lights: lights,
  31533. linearDepth: linearDepth,
  31534. linearToneMapping: linearToneMapping,
  31535. localId: localId,
  31536. log: log,
  31537. log2: log2,
  31538. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  31539. luminance: luminance,
  31540. mat2: mat2,
  31541. mat3: mat3,
  31542. mat4: mat4,
  31543. matcapUV: matcapUV,
  31544. materialAO: materialAO,
  31545. materialAlphaTest: materialAlphaTest,
  31546. materialAnisotropy: materialAnisotropy,
  31547. materialAnisotropyVector: materialAnisotropyVector,
  31548. materialAttenuationColor: materialAttenuationColor,
  31549. materialAttenuationDistance: materialAttenuationDistance,
  31550. materialClearcoat: materialClearcoat,
  31551. materialClearcoatNormal: materialClearcoatNormal,
  31552. materialClearcoatRoughness: materialClearcoatRoughness,
  31553. materialColor: materialColor,
  31554. materialDispersion: materialDispersion,
  31555. materialEmissive: materialEmissive,
  31556. materialEnvIntensity: materialEnvIntensity,
  31557. materialEnvRotation: materialEnvRotation,
  31558. materialIOR: materialIOR,
  31559. materialIridescence: materialIridescence,
  31560. materialIridescenceIOR: materialIridescenceIOR,
  31561. materialIridescenceThickness: materialIridescenceThickness,
  31562. materialLightMap: materialLightMap,
  31563. materialLineDashOffset: materialLineDashOffset,
  31564. materialLineDashSize: materialLineDashSize,
  31565. materialLineGapSize: materialLineGapSize,
  31566. materialLineScale: materialLineScale,
  31567. materialLineWidth: materialLineWidth,
  31568. materialMetalness: materialMetalness,
  31569. materialNormal: materialNormal,
  31570. materialOpacity: materialOpacity,
  31571. materialPointSize: materialPointSize,
  31572. materialReference: materialReference,
  31573. materialReflectivity: materialReflectivity,
  31574. materialRefractionRatio: materialRefractionRatio,
  31575. materialRotation: materialRotation,
  31576. materialRoughness: materialRoughness,
  31577. materialSheen: materialSheen,
  31578. materialSheenRoughness: materialSheenRoughness,
  31579. materialShininess: materialShininess,
  31580. materialSpecular: materialSpecular,
  31581. materialSpecularColor: materialSpecularColor,
  31582. materialSpecularIntensity: materialSpecularIntensity,
  31583. materialSpecularStrength: materialSpecularStrength,
  31584. materialThickness: materialThickness,
  31585. materialTransmission: materialTransmission,
  31586. max: max$1,
  31587. maxMipLevel: maxMipLevel,
  31588. mediumpModelViewMatrix: mediumpModelViewMatrix,
  31589. metalness: metalness,
  31590. min: min$1,
  31591. mix: mix,
  31592. mixElement: mixElement,
  31593. mod: mod,
  31594. modInt: modInt,
  31595. modelDirection: modelDirection,
  31596. modelNormalMatrix: modelNormalMatrix,
  31597. modelPosition: modelPosition,
  31598. modelRadius: modelRadius,
  31599. modelScale: modelScale,
  31600. modelViewMatrix: modelViewMatrix,
  31601. modelViewPosition: modelViewPosition,
  31602. modelViewProjection: modelViewProjection,
  31603. modelWorldMatrix: modelWorldMatrix,
  31604. modelWorldMatrixInverse: modelWorldMatrixInverse,
  31605. morphReference: morphReference,
  31606. mrt: mrt,
  31607. mul: mul,
  31608. mx_aastep: mx_aastep,
  31609. mx_add: mx_add,
  31610. mx_atan2: mx_atan2,
  31611. mx_cell_noise_float: mx_cell_noise_float,
  31612. mx_contrast: mx_contrast,
  31613. mx_divide: mx_divide,
  31614. mx_fractal_noise_float: mx_fractal_noise_float,
  31615. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  31616. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  31617. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  31618. mx_frame: mx_frame,
  31619. mx_heighttonormal: mx_heighttonormal,
  31620. mx_hsvtorgb: mx_hsvtorgb,
  31621. mx_ifequal: mx_ifequal,
  31622. mx_ifgreater: mx_ifgreater,
  31623. mx_ifgreatereq: mx_ifgreatereq,
  31624. mx_invert: mx_invert,
  31625. mx_modulo: mx_modulo,
  31626. mx_multiply: mx_multiply,
  31627. mx_noise_float: mx_noise_float,
  31628. mx_noise_vec3: mx_noise_vec3,
  31629. mx_noise_vec4: mx_noise_vec4,
  31630. mx_place2d: mx_place2d,
  31631. mx_power: mx_power,
  31632. mx_ramp4: mx_ramp4,
  31633. mx_ramplr: mx_ramplr,
  31634. mx_ramptb: mx_ramptb,
  31635. mx_rgbtohsv: mx_rgbtohsv,
  31636. mx_rotate2d: mx_rotate2d,
  31637. mx_rotate3d: mx_rotate3d,
  31638. mx_safepower: mx_safepower,
  31639. mx_separate: mx_separate,
  31640. mx_splitlr: mx_splitlr,
  31641. mx_splittb: mx_splittb,
  31642. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  31643. mx_subtract: mx_subtract,
  31644. mx_timer: mx_timer,
  31645. mx_transform_uv: mx_transform_uv,
  31646. mx_unifiednoise2d: mx_unifiednoise2d,
  31647. mx_unifiednoise3d: mx_unifiednoise3d,
  31648. mx_worley_noise_float: mx_worley_noise_float,
  31649. mx_worley_noise_vec2: mx_worley_noise_vec2,
  31650. mx_worley_noise_vec3: mx_worley_noise_vec3,
  31651. negate: negate,
  31652. neutralToneMapping: neutralToneMapping,
  31653. nodeArray: nodeArray,
  31654. nodeImmutable: nodeImmutable,
  31655. nodeObject: nodeObject,
  31656. nodeObjectIntent: nodeObjectIntent,
  31657. nodeObjects: nodeObjects,
  31658. nodeProxy: nodeProxy,
  31659. nodeProxyIntent: nodeProxyIntent,
  31660. normalFlat: normalFlat,
  31661. normalGeometry: normalGeometry,
  31662. normalLocal: normalLocal,
  31663. normalMap: normalMap,
  31664. normalView: normalView,
  31665. normalViewGeometry: normalViewGeometry,
  31666. normalWorld: normalWorld,
  31667. normalWorldGeometry: normalWorldGeometry,
  31668. normalize: normalize,
  31669. not: not,
  31670. notEqual: notEqual,
  31671. numWorkgroups: numWorkgroups,
  31672. objectDirection: objectDirection,
  31673. objectGroup: objectGroup,
  31674. objectPosition: objectPosition,
  31675. objectRadius: objectRadius,
  31676. objectScale: objectScale,
  31677. objectViewPosition: objectViewPosition,
  31678. objectWorldMatrix: objectWorldMatrix,
  31679. oneMinus: oneMinus,
  31680. or: or,
  31681. orthographicDepthToViewZ: orthographicDepthToViewZ,
  31682. oscSawtooth: oscSawtooth,
  31683. oscSine: oscSine,
  31684. oscSquare: oscSquare,
  31685. oscTriangle: oscTriangle,
  31686. output: output,
  31687. outputStruct: outputStruct,
  31688. overlay: overlay,
  31689. overloadingFn: overloadingFn,
  31690. parabola: parabola,
  31691. parallaxDirection: parallaxDirection,
  31692. parallaxUV: parallaxUV,
  31693. parameter: parameter,
  31694. pass: pass,
  31695. passTexture: passTexture,
  31696. pcurve: pcurve,
  31697. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  31698. pmremTexture: pmremTexture,
  31699. pointShadow: pointShadow,
  31700. pointUV: pointUV,
  31701. pointWidth: pointWidth,
  31702. positionGeometry: positionGeometry,
  31703. positionLocal: positionLocal,
  31704. positionPrevious: positionPrevious,
  31705. positionView: positionView,
  31706. positionViewDirection: positionViewDirection,
  31707. positionWorld: positionWorld,
  31708. positionWorldDirection: positionWorldDirection,
  31709. posterize: posterize,
  31710. pow: pow,
  31711. pow2: pow2,
  31712. pow3: pow3,
  31713. pow4: pow4,
  31714. premultiplyAlpha: premultiplyAlpha,
  31715. property: property,
  31716. quadBroadcast: quadBroadcast,
  31717. quadSwapDiagonal: quadSwapDiagonal,
  31718. quadSwapX: quadSwapX,
  31719. quadSwapY: quadSwapY,
  31720. radians: radians,
  31721. rand: rand,
  31722. range: range,
  31723. rangeFog: rangeFog,
  31724. rangeFogFactor: rangeFogFactor,
  31725. reciprocal: reciprocal,
  31726. reference: reference,
  31727. referenceBuffer: referenceBuffer,
  31728. reflect: reflect,
  31729. reflectVector: reflectVector,
  31730. reflectView: reflectView,
  31731. reflector: reflector,
  31732. refract: refract,
  31733. refractVector: refractVector,
  31734. refractView: refractView,
  31735. reinhardToneMapping: reinhardToneMapping,
  31736. remap: remap,
  31737. remapClamp: remapClamp,
  31738. renderGroup: renderGroup,
  31739. renderOutput: renderOutput,
  31740. rendererReference: rendererReference,
  31741. rotate: rotate,
  31742. rotateUV: rotateUV,
  31743. roughness: roughness,
  31744. round: round,
  31745. rtt: rtt,
  31746. sRGBTransferEOTF: sRGBTransferEOTF,
  31747. sRGBTransferOETF: sRGBTransferOETF,
  31748. sample: sample,
  31749. sampler: sampler,
  31750. samplerComparison: samplerComparison,
  31751. saturate: saturate,
  31752. saturation: saturation,
  31753. screen: screen,
  31754. screenCoordinate: screenCoordinate,
  31755. screenSize: screenSize,
  31756. screenUV: screenUV,
  31757. scriptable: scriptable,
  31758. scriptableValue: scriptableValue,
  31759. select: select,
  31760. setCurrentStack: setCurrentStack,
  31761. setName: setName,
  31762. shaderStages: shaderStages,
  31763. shadow: shadow,
  31764. shadowPositionWorld: shadowPositionWorld,
  31765. shapeCircle: shapeCircle,
  31766. sharedUniformGroup: sharedUniformGroup,
  31767. sheen: sheen,
  31768. sheenRoughness: sheenRoughness,
  31769. shiftLeft: shiftLeft,
  31770. shiftRight: shiftRight,
  31771. shininess: shininess,
  31772. sign: sign,
  31773. sin: sin,
  31774. sinc: sinc,
  31775. skinning: skinning,
  31776. smoothstep: smoothstep,
  31777. smoothstepElement: smoothstepElement,
  31778. specularColor: specularColor,
  31779. specularF90: specularF90,
  31780. spherizeUV: spherizeUV,
  31781. split: split,
  31782. spritesheetUV: spritesheetUV,
  31783. sqrt: sqrt,
  31784. stack: stack,
  31785. step: step,
  31786. stepElement: stepElement,
  31787. storage: storage,
  31788. storageBarrier: storageBarrier,
  31789. storageObject: storageObject,
  31790. storageTexture: storageTexture,
  31791. string: string,
  31792. struct: struct,
  31793. sub: sub,
  31794. subBuild: subBuild,
  31795. subgroupAdd: subgroupAdd,
  31796. subgroupAll: subgroupAll,
  31797. subgroupAnd: subgroupAnd,
  31798. subgroupAny: subgroupAny,
  31799. subgroupBallot: subgroupBallot,
  31800. subgroupBroadcast: subgroupBroadcast,
  31801. subgroupBroadcastFirst: subgroupBroadcastFirst,
  31802. subgroupElect: subgroupElect,
  31803. subgroupExclusiveAdd: subgroupExclusiveAdd,
  31804. subgroupExclusiveMul: subgroupExclusiveMul,
  31805. subgroupInclusiveAdd: subgroupInclusiveAdd,
  31806. subgroupInclusiveMul: subgroupInclusiveMul,
  31807. subgroupIndex: subgroupIndex,
  31808. subgroupMax: subgroupMax,
  31809. subgroupMin: subgroupMin,
  31810. subgroupMul: subgroupMul,
  31811. subgroupOr: subgroupOr,
  31812. subgroupShuffle: subgroupShuffle,
  31813. subgroupShuffleDown: subgroupShuffleDown,
  31814. subgroupShuffleUp: subgroupShuffleUp,
  31815. subgroupShuffleXor: subgroupShuffleXor,
  31816. subgroupSize: subgroupSize,
  31817. subgroupXor: subgroupXor,
  31818. tan: tan,
  31819. tangentGeometry: tangentGeometry,
  31820. tangentLocal: tangentLocal,
  31821. tangentView: tangentView,
  31822. tangentWorld: tangentWorld,
  31823. texture: texture,
  31824. texture3D: texture3D,
  31825. textureBarrier: textureBarrier,
  31826. textureBicubic: textureBicubic,
  31827. textureBicubicLevel: textureBicubicLevel,
  31828. textureCubeUV: textureCubeUV,
  31829. textureLoad: textureLoad,
  31830. textureSize: textureSize,
  31831. textureStore: textureStore,
  31832. thickness: thickness,
  31833. time: time,
  31834. toneMapping: toneMapping,
  31835. toneMappingExposure: toneMappingExposure,
  31836. toonOutlinePass: toonOutlinePass,
  31837. transformDirection: transformDirection,
  31838. transformNormal: transformNormal,
  31839. transformNormalToView: transformNormalToView,
  31840. transformedClearcoatNormalView: transformedClearcoatNormalView,
  31841. transformedNormalView: transformedNormalView,
  31842. transformedNormalWorld: transformedNormalWorld,
  31843. transmission: transmission,
  31844. transpose: transpose,
  31845. triNoise3D: triNoise3D,
  31846. triplanarTexture: triplanarTexture,
  31847. triplanarTextures: triplanarTextures,
  31848. trunc: trunc,
  31849. uint: uint,
  31850. uniform: uniform,
  31851. uniformArray: uniformArray,
  31852. uniformCubeTexture: uniformCubeTexture,
  31853. uniformFlow: uniformFlow,
  31854. uniformGroup: uniformGroup,
  31855. uniformTexture: uniformTexture,
  31856. unpremultiplyAlpha: unpremultiplyAlpha,
  31857. userData: userData,
  31858. uv: uv$1,
  31859. uvec2: uvec2,
  31860. uvec3: uvec3,
  31861. uvec4: uvec4,
  31862. varying: varying,
  31863. varyingProperty: varyingProperty,
  31864. vec2: vec2,
  31865. vec3: vec3,
  31866. vec4: vec4,
  31867. vectorComponents: vectorComponents,
  31868. velocity: velocity,
  31869. vertexColor: vertexColor,
  31870. vertexIndex: vertexIndex,
  31871. vertexStage: vertexStage,
  31872. vibrance: vibrance,
  31873. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  31874. viewZToOrthographicDepth: viewZToOrthographicDepth,
  31875. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  31876. viewport: viewport,
  31877. viewportCoordinate: viewportCoordinate,
  31878. viewportDepthTexture: viewportDepthTexture,
  31879. viewportLinearDepth: viewportLinearDepth,
  31880. viewportMipTexture: viewportMipTexture,
  31881. viewportResolution: viewportResolution,
  31882. viewportSafeUV: viewportSafeUV,
  31883. viewportSharedTexture: viewportSharedTexture,
  31884. viewportSize: viewportSize,
  31885. viewportTexture: viewportTexture,
  31886. viewportUV: viewportUV,
  31887. wgsl: wgsl,
  31888. wgslFn: wgslFn,
  31889. workgroupArray: workgroupArray,
  31890. workgroupBarrier: workgroupBarrier,
  31891. workgroupId: workgroupId,
  31892. workingToColorSpace: workingToColorSpace,
  31893. xor: xor
  31894. });
  31895. const _clearColor = /*@__PURE__*/ new Color4();
  31896. /**
  31897. * This renderer module manages the background.
  31898. *
  31899. * @private
  31900. * @augments DataMap
  31901. */
  31902. class Background extends DataMap {
  31903. /**
  31904. * Constructs a new background management component.
  31905. *
  31906. * @param {Renderer} renderer - The renderer.
  31907. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  31908. */
  31909. constructor( renderer, nodes ) {
  31910. super();
  31911. /**
  31912. * The renderer.
  31913. *
  31914. * @type {Renderer}
  31915. */
  31916. this.renderer = renderer;
  31917. /**
  31918. * Renderer component for managing nodes related logic.
  31919. *
  31920. * @type {Nodes}
  31921. */
  31922. this.nodes = nodes;
  31923. }
  31924. /**
  31925. * Updates the background for the given scene. Depending on how `Scene.background`
  31926. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  31927. * or add a mesh to the render list for rendering the background as a textured plane
  31928. * or skybox.
  31929. *
  31930. * @param {Scene} scene - The scene.
  31931. * @param {RenderList} renderList - The current render list.
  31932. * @param {RenderContext} renderContext - The current render context.
  31933. */
  31934. update( scene, renderList, renderContext ) {
  31935. const renderer = this.renderer;
  31936. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  31937. let forceClear = false;
  31938. if ( background === null ) {
  31939. // no background settings, use clear color configuration from the renderer
  31940. renderer._clearColor.getRGB( _clearColor );
  31941. _clearColor.a = renderer._clearColor.a;
  31942. } else if ( background.isColor === true ) {
  31943. // background is an opaque color
  31944. background.getRGB( _clearColor );
  31945. _clearColor.a = 1;
  31946. forceClear = true;
  31947. } else if ( background.isNode === true ) {
  31948. const sceneData = this.get( scene );
  31949. const backgroundNode = background;
  31950. _clearColor.copy( renderer._clearColor );
  31951. let backgroundMesh = sceneData.backgroundMesh;
  31952. if ( backgroundMesh === undefined ) {
  31953. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  31954. // @TODO: Add Texture2D support using node context
  31955. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  31956. getTextureLevel: () => backgroundBlurriness
  31957. } );
  31958. let viewProj = modelViewProjection;
  31959. viewProj = viewProj.setZ( viewProj.w );
  31960. const nodeMaterial = new NodeMaterial();
  31961. nodeMaterial.name = 'Background.material';
  31962. nodeMaterial.side = BackSide;
  31963. nodeMaterial.depthTest = false;
  31964. nodeMaterial.depthWrite = false;
  31965. nodeMaterial.allowOverride = false;
  31966. nodeMaterial.fog = false;
  31967. nodeMaterial.lights = false;
  31968. nodeMaterial.vertexNode = viewProj;
  31969. nodeMaterial.colorNode = backgroundMeshNode;
  31970. sceneData.backgroundMeshNode = backgroundMeshNode;
  31971. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  31972. backgroundMesh.frustumCulled = false;
  31973. backgroundMesh.name = 'Background.mesh';
  31974. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  31975. this.matrixWorld.copyPosition( camera.matrixWorld );
  31976. };
  31977. function onBackgroundDispose() {
  31978. background.removeEventListener( 'dispose', onBackgroundDispose );
  31979. backgroundMesh.material.dispose();
  31980. backgroundMesh.geometry.dispose();
  31981. }
  31982. background.addEventListener( 'dispose', onBackgroundDispose );
  31983. }
  31984. const backgroundCacheKey = backgroundNode.getCacheKey();
  31985. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  31986. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  31987. sceneData.backgroundMeshNode.needsUpdate = true;
  31988. backgroundMesh.material.needsUpdate = true;
  31989. sceneData.backgroundCacheKey = backgroundCacheKey;
  31990. }
  31991. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  31992. } else {
  31993. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  31994. }
  31995. //
  31996. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  31997. if ( environmentBlendMode === 'additive' ) {
  31998. _clearColor.set( 0, 0, 0, 1 );
  31999. } else if ( environmentBlendMode === 'alpha-blend' ) {
  32000. _clearColor.set( 0, 0, 0, 0 );
  32001. }
  32002. //
  32003. if ( renderer.autoClear === true || forceClear === true ) {
  32004. const clearColorValue = renderContext.clearColorValue;
  32005. clearColorValue.r = _clearColor.r;
  32006. clearColorValue.g = _clearColor.g;
  32007. clearColorValue.b = _clearColor.b;
  32008. clearColorValue.a = _clearColor.a;
  32009. // premultiply alpha
  32010. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  32011. clearColorValue.r *= clearColorValue.a;
  32012. clearColorValue.g *= clearColorValue.a;
  32013. clearColorValue.b *= clearColorValue.a;
  32014. }
  32015. //
  32016. renderContext.depthClearValue = renderer._clearDepth;
  32017. renderContext.stencilClearValue = renderer._clearStencil;
  32018. renderContext.clearColor = renderer.autoClearColor === true;
  32019. renderContext.clearDepth = renderer.autoClearDepth === true;
  32020. renderContext.clearStencil = renderer.autoClearStencil === true;
  32021. } else {
  32022. renderContext.clearColor = false;
  32023. renderContext.clearDepth = false;
  32024. renderContext.clearStencil = false;
  32025. }
  32026. }
  32027. }
  32028. let _id$6 = 0;
  32029. /**
  32030. * A bind group represents a collection of bindings and thus a collection
  32031. * or resources. Bind groups are assigned to pipelines to provide them
  32032. * with the required resources (like uniform buffers or textures).
  32033. *
  32034. * @private
  32035. */
  32036. class BindGroup {
  32037. /**
  32038. * Constructs a new bind group.
  32039. *
  32040. * @param {string} name - The bind group's name.
  32041. * @param {Array<Binding>} bindings - An array of bindings.
  32042. * @param {number} index - The group index.
  32043. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  32044. */
  32045. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  32046. /**
  32047. * The bind group's name.
  32048. *
  32049. * @type {string}
  32050. */
  32051. this.name = name;
  32052. /**
  32053. * An array of bindings.
  32054. *
  32055. * @type {Array<Binding>}
  32056. */
  32057. this.bindings = bindings;
  32058. /**
  32059. * The group index.
  32060. *
  32061. * @type {number}
  32062. */
  32063. this.index = index;
  32064. /**
  32065. * An array of reference bindings.
  32066. *
  32067. * @type {Array<Binding>}
  32068. */
  32069. this.bindingsReference = bindingsReference;
  32070. /**
  32071. * The group's ID.
  32072. *
  32073. * @type {number}
  32074. */
  32075. this.id = _id$6 ++;
  32076. }
  32077. }
  32078. /**
  32079. * This module represents the state of a node builder after it was
  32080. * used to build the nodes for a render object. The state holds the
  32081. * results of the build for further processing in the renderer.
  32082. *
  32083. * Render objects with identical cache keys share the same node builder state.
  32084. *
  32085. * @private
  32086. */
  32087. class NodeBuilderState {
  32088. /**
  32089. * Constructs a new node builder state.
  32090. *
  32091. * @param {string} vertexShader - The native vertex shader code.
  32092. * @param {string} fragmentShader - The native fragment shader code.
  32093. * @param {string} computeShader - The native compute shader code.
  32094. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  32095. * @param {Array<BindGroup>} bindings - An array of bind groups.
  32096. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  32097. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  32098. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  32099. * @param {NodeMaterialObserver} observer - A node material observer.
  32100. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  32101. */
  32102. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  32103. /**
  32104. * The native vertex shader code.
  32105. *
  32106. * @type {string}
  32107. */
  32108. this.vertexShader = vertexShader;
  32109. /**
  32110. * The native fragment shader code.
  32111. *
  32112. * @type {string}
  32113. */
  32114. this.fragmentShader = fragmentShader;
  32115. /**
  32116. * The native compute shader code.
  32117. *
  32118. * @type {string}
  32119. */
  32120. this.computeShader = computeShader;
  32121. /**
  32122. * An array with transform attribute objects.
  32123. * Only relevant when using compute shaders with WebGL 2.
  32124. *
  32125. * @type {Array<Object>}
  32126. */
  32127. this.transforms = transforms;
  32128. /**
  32129. * An array of node attributes representing
  32130. * the attributes of the shaders.
  32131. *
  32132. * @type {Array<NodeAttribute>}
  32133. */
  32134. this.nodeAttributes = nodeAttributes;
  32135. /**
  32136. * An array of bind groups representing the uniform or storage
  32137. * buffers, texture or samplers of the shader.
  32138. *
  32139. * @type {Array<BindGroup>}
  32140. */
  32141. this.bindings = bindings;
  32142. /**
  32143. * An array of nodes that implement their `update()` method.
  32144. *
  32145. * @type {Array<Node>}
  32146. */
  32147. this.updateNodes = updateNodes;
  32148. /**
  32149. * An array of nodes that implement their `updateBefore()` method.
  32150. *
  32151. * @type {Array<Node>}
  32152. */
  32153. this.updateBeforeNodes = updateBeforeNodes;
  32154. /**
  32155. * An array of nodes that implement their `updateAfter()` method.
  32156. *
  32157. * @type {Array<Node>}
  32158. */
  32159. this.updateAfterNodes = updateAfterNodes;
  32160. /**
  32161. * A node material observer.
  32162. *
  32163. * @type {NodeMaterialObserver}
  32164. */
  32165. this.observer = observer;
  32166. /**
  32167. * How often this state is used by render objects.
  32168. *
  32169. * @type {number}
  32170. */
  32171. this.usedTimes = 0;
  32172. }
  32173. /**
  32174. * This method is used to create a array of bind groups based
  32175. * on the existing bind groups of this state. Shared groups are
  32176. * not cloned.
  32177. *
  32178. * @return {Array<BindGroup>} A array of bind groups.
  32179. */
  32180. createBindings() {
  32181. const bindings = [];
  32182. for ( const instanceGroup of this.bindings ) {
  32183. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  32184. if ( shared !== true ) {
  32185. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  32186. bindings.push( bindingsGroup );
  32187. for ( const instanceBinding of instanceGroup.bindings ) {
  32188. bindingsGroup.bindings.push( instanceBinding.clone() );
  32189. }
  32190. } else {
  32191. bindings.push( instanceGroup );
  32192. }
  32193. }
  32194. return bindings;
  32195. }
  32196. }
  32197. /**
  32198. * {@link NodeBuilder} is going to create instances of this class during the build process
  32199. * of nodes. They represent the final shader attributes that are going to be generated
  32200. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  32201. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  32202. */
  32203. class NodeAttribute {
  32204. /**
  32205. * Constructs a new node attribute.
  32206. *
  32207. * @param {string} name - The name of the attribute.
  32208. * @param {string} type - The type of the attribute.
  32209. * @param {?Node} node - An optional reference to the node.
  32210. */
  32211. constructor( name, type, node = null ) {
  32212. /**
  32213. * This flag can be used for type testing.
  32214. *
  32215. * @type {boolean}
  32216. * @readonly
  32217. * @default true
  32218. */
  32219. this.isNodeAttribute = true;
  32220. /**
  32221. * The name of the attribute.
  32222. *
  32223. * @type {string}
  32224. */
  32225. this.name = name;
  32226. /**
  32227. * The type of the attribute.
  32228. *
  32229. * @type {string}
  32230. */
  32231. this.type = type;
  32232. /**
  32233. * An optional reference to the node.
  32234. *
  32235. * @type {?Node}
  32236. * @default null
  32237. */
  32238. this.node = node;
  32239. }
  32240. }
  32241. /**
  32242. * {@link NodeBuilder} is going to create instances of this class during the build process
  32243. * of nodes. They represent the final shader uniforms that are going to be generated
  32244. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  32245. * for this purpose.
  32246. */
  32247. class NodeUniform {
  32248. /**
  32249. * Constructs a new node uniform.
  32250. *
  32251. * @param {string} name - The name of the uniform.
  32252. * @param {string} type - The type of the uniform.
  32253. * @param {UniformNode} node - An reference to the node.
  32254. */
  32255. constructor( name, type, node ) {
  32256. /**
  32257. * This flag can be used for type testing.
  32258. *
  32259. * @type {boolean}
  32260. * @readonly
  32261. * @default true
  32262. */
  32263. this.isNodeUniform = true;
  32264. /**
  32265. * The name of the uniform.
  32266. *
  32267. * @type {string}
  32268. */
  32269. this.name = name;
  32270. /**
  32271. * The type of the uniform.
  32272. *
  32273. * @type {string}
  32274. */
  32275. this.type = type;
  32276. /**
  32277. * An reference to the node.
  32278. *
  32279. * @type {UniformNode}
  32280. */
  32281. this.node = node.getSelf();
  32282. }
  32283. /**
  32284. * The value of the uniform node.
  32285. *
  32286. * @type {any}
  32287. */
  32288. get value() {
  32289. return this.node.value;
  32290. }
  32291. set value( val ) {
  32292. this.node.value = val;
  32293. }
  32294. /**
  32295. * The id of the uniform node.
  32296. *
  32297. * @type {number}
  32298. */
  32299. get id() {
  32300. return this.node.id;
  32301. }
  32302. /**
  32303. * The uniform node's group.
  32304. *
  32305. * @type {UniformGroupNode}
  32306. */
  32307. get groupNode() {
  32308. return this.node.groupNode;
  32309. }
  32310. }
  32311. /**
  32312. * {@link NodeBuilder} is going to create instances of this class during the build process
  32313. * of nodes. They represent the final shader variables that are going to be generated
  32314. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  32315. * this purpose.
  32316. */
  32317. class NodeVar {
  32318. /**
  32319. * Constructs a new node variable.
  32320. *
  32321. * @param {string} name - The name of the variable.
  32322. * @param {string} type - The type of the variable.
  32323. * @param {boolean} [readOnly=false] - The read-only flag.
  32324. * @param {?number} [count=null] - The size.
  32325. */
  32326. constructor( name, type, readOnly = false, count = null ) {
  32327. /**
  32328. * This flag can be used for type testing.
  32329. *
  32330. * @type {boolean}
  32331. * @readonly
  32332. * @default true
  32333. */
  32334. this.isNodeVar = true;
  32335. /**
  32336. * The name of the variable.
  32337. *
  32338. * @type {string}
  32339. */
  32340. this.name = name;
  32341. /**
  32342. * The type of the variable.
  32343. *
  32344. * @type {string}
  32345. */
  32346. this.type = type;
  32347. /**
  32348. * The read-only flag.
  32349. *
  32350. * @type {boolean}
  32351. */
  32352. this.readOnly = readOnly;
  32353. /**
  32354. * The size.
  32355. *
  32356. * @type {?number}
  32357. */
  32358. this.count = count;
  32359. }
  32360. }
  32361. /**
  32362. * {@link NodeBuilder} is going to create instances of this class during the build process
  32363. * of nodes. They represent the final shader varyings that are going to be generated
  32364. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  32365. * this purpose.
  32366. *
  32367. * @augments NodeVar
  32368. */
  32369. class NodeVarying extends NodeVar {
  32370. /**
  32371. * Constructs a new node varying.
  32372. *
  32373. * @param {string} name - The name of the varying.
  32374. * @param {string} type - The type of the varying.
  32375. * @param {?string} interpolationType - The interpolation type of the varying.
  32376. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32377. */
  32378. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  32379. super( name, type );
  32380. /**
  32381. * Whether this varying requires interpolation or not. This property can be used
  32382. * to check if the varying can be optimized for a variable.
  32383. *
  32384. * @type {boolean}
  32385. * @default false
  32386. */
  32387. this.needsInterpolation = false;
  32388. /**
  32389. * This flag can be used for type testing.
  32390. *
  32391. * @type {boolean}
  32392. * @readonly
  32393. * @default true
  32394. */
  32395. this.isNodeVarying = true;
  32396. /**
  32397. * The interpolation type of the varying data.
  32398. *
  32399. * @type {?string}
  32400. * @default null
  32401. */
  32402. this.interpolationType = interpolationType;
  32403. /**
  32404. * The interpolation sampling type of varying data.
  32405. *
  32406. * @type {?string}
  32407. * @default null
  32408. */
  32409. this.interpolationSampling = interpolationSampling;
  32410. }
  32411. }
  32412. /**
  32413. * {@link NodeBuilder} is going to create instances of this class during the build process
  32414. * of nodes. They represent user-defined, native shader code portions that are going to be
  32415. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  32416. * for this purpose.
  32417. */
  32418. class NodeCode {
  32419. /**
  32420. * Constructs a new code node.
  32421. *
  32422. * @param {string} name - The name of the code.
  32423. * @param {string} type - The node type.
  32424. * @param {string} [code=''] - The native shader code.
  32425. */
  32426. constructor( name, type, code = '' ) {
  32427. /**
  32428. * The name of the code.
  32429. *
  32430. * @type {string}
  32431. */
  32432. this.name = name;
  32433. /**
  32434. * The node type.
  32435. *
  32436. * @type {string}
  32437. */
  32438. this.type = type;
  32439. /**
  32440. * The native shader code.
  32441. *
  32442. * @type {string}
  32443. * @default ''
  32444. */
  32445. this.code = code;
  32446. Object.defineProperty( this, 'isNodeCode', { value: true } );
  32447. }
  32448. }
  32449. let _id$5 = 0;
  32450. /**
  32451. * This utility class is used in {@link NodeBuilder} as an internal
  32452. * cache data structure for node data.
  32453. */
  32454. class NodeCache {
  32455. /**
  32456. * Constructs a new node cache.
  32457. *
  32458. * @param {?NodeCache} parent - A reference to a parent cache.
  32459. */
  32460. constructor( parent = null ) {
  32461. /**
  32462. * The id of the cache.
  32463. *
  32464. * @type {number}
  32465. * @readonly
  32466. */
  32467. this.id = _id$5 ++;
  32468. /**
  32469. * A weak map for managing node data.
  32470. *
  32471. * @type {WeakMap<Node, Object>}
  32472. */
  32473. this.nodesData = new WeakMap();
  32474. /**
  32475. * Reference to a parent node cache.
  32476. *
  32477. * @type {?NodeCache}
  32478. * @default null
  32479. */
  32480. this.parent = parent;
  32481. }
  32482. /**
  32483. * Returns the data for the given node.
  32484. *
  32485. * @param {Node} node - The node.
  32486. * @return {?Object} The data for the node.
  32487. */
  32488. getData( node ) {
  32489. let data = this.nodesData.get( node );
  32490. if ( data === undefined && this.parent !== null ) {
  32491. data = this.parent.getData( node );
  32492. }
  32493. return data;
  32494. }
  32495. /**
  32496. * Sets the data for a given node.
  32497. *
  32498. * @param {Node} node - The node.
  32499. * @param {Object} data - The data that should be cached.
  32500. */
  32501. setData( node, data ) {
  32502. this.nodesData.set( node, data );
  32503. }
  32504. }
  32505. class StructType {
  32506. constructor( name, members ) {
  32507. this.name = name;
  32508. this.members = members;
  32509. this.output = false;
  32510. }
  32511. }
  32512. /**
  32513. * Abstract base class for uniforms.
  32514. *
  32515. * @abstract
  32516. * @private
  32517. */
  32518. class Uniform {
  32519. /**
  32520. * Constructs a new uniform.
  32521. *
  32522. * @param {string} name - The uniform's name.
  32523. * @param {any} value - The uniform's value.
  32524. */
  32525. constructor( name, value ) {
  32526. /**
  32527. * The uniform's name.
  32528. *
  32529. * @type {string}
  32530. */
  32531. this.name = name;
  32532. /**
  32533. * The uniform's value.
  32534. *
  32535. * @type {any}
  32536. */
  32537. this.value = value;
  32538. /**
  32539. * Used to build the uniform buffer according to the STD140 layout.
  32540. * Derived uniforms will set this property to a data type specific
  32541. * value.
  32542. *
  32543. * @type {number}
  32544. */
  32545. this.boundary = 0;
  32546. /**
  32547. * The item size. Derived uniforms will set this property to a data
  32548. * type specific value.
  32549. *
  32550. * @type {number}
  32551. */
  32552. this.itemSize = 0;
  32553. /**
  32554. * This property is set by {@link UniformsGroup} and marks
  32555. * the start position in the uniform buffer.
  32556. *
  32557. * @type {number}
  32558. */
  32559. this.offset = 0;
  32560. }
  32561. /**
  32562. * Sets the uniform's value.
  32563. *
  32564. * @param {any} value - The value to set.
  32565. */
  32566. setValue( value ) {
  32567. this.value = value;
  32568. }
  32569. /**
  32570. * Returns the uniform's value.
  32571. *
  32572. * @return {any} The value.
  32573. */
  32574. getValue() {
  32575. return this.value;
  32576. }
  32577. }
  32578. /**
  32579. * Represents a Number uniform.
  32580. *
  32581. * @private
  32582. * @augments Uniform
  32583. */
  32584. class NumberUniform extends Uniform {
  32585. /**
  32586. * Constructs a new Number uniform.
  32587. *
  32588. * @param {string} name - The uniform's name.
  32589. * @param {number} value - The uniform's value.
  32590. */
  32591. constructor( name, value = 0 ) {
  32592. super( name, value );
  32593. /**
  32594. * This flag can be used for type testing.
  32595. *
  32596. * @type {boolean}
  32597. * @readonly
  32598. * @default true
  32599. */
  32600. this.isNumberUniform = true;
  32601. this.boundary = 4;
  32602. this.itemSize = 1;
  32603. }
  32604. }
  32605. /**
  32606. * Represents a Vector2 uniform.
  32607. *
  32608. * @private
  32609. * @augments Uniform
  32610. */
  32611. class Vector2Uniform extends Uniform {
  32612. /**
  32613. * Constructs a new Number uniform.
  32614. *
  32615. * @param {string} name - The uniform's name.
  32616. * @param {Vector2} value - The uniform's value.
  32617. */
  32618. constructor( name, value = new Vector2() ) {
  32619. super( name, value );
  32620. /**
  32621. * This flag can be used for type testing.
  32622. *
  32623. * @type {boolean}
  32624. * @readonly
  32625. * @default true
  32626. */
  32627. this.isVector2Uniform = true;
  32628. this.boundary = 8;
  32629. this.itemSize = 2;
  32630. }
  32631. }
  32632. /**
  32633. * Represents a Vector3 uniform.
  32634. *
  32635. * @private
  32636. * @augments Uniform
  32637. */
  32638. class Vector3Uniform extends Uniform {
  32639. /**
  32640. * Constructs a new Number uniform.
  32641. *
  32642. * @param {string} name - The uniform's name.
  32643. * @param {Vector3} value - The uniform's value.
  32644. */
  32645. constructor( name, value = new Vector3() ) {
  32646. super( name, value );
  32647. /**
  32648. * This flag can be used for type testing.
  32649. *
  32650. * @type {boolean}
  32651. * @readonly
  32652. * @default true
  32653. */
  32654. this.isVector3Uniform = true;
  32655. this.boundary = 16;
  32656. this.itemSize = 3;
  32657. }
  32658. }
  32659. /**
  32660. * Represents a Vector4 uniform.
  32661. *
  32662. * @private
  32663. * @augments Uniform
  32664. */
  32665. class Vector4Uniform extends Uniform {
  32666. /**
  32667. * Constructs a new Number uniform.
  32668. *
  32669. * @param {string} name - The uniform's name.
  32670. * @param {Vector4} value - The uniform's value.
  32671. */
  32672. constructor( name, value = new Vector4() ) {
  32673. super( name, value );
  32674. /**
  32675. * This flag can be used for type testing.
  32676. *
  32677. * @type {boolean}
  32678. * @readonly
  32679. * @default true
  32680. */
  32681. this.isVector4Uniform = true;
  32682. this.boundary = 16;
  32683. this.itemSize = 4;
  32684. }
  32685. }
  32686. /**
  32687. * Represents a Color uniform.
  32688. *
  32689. * @private
  32690. * @augments Uniform
  32691. */
  32692. class ColorUniform extends Uniform {
  32693. /**
  32694. * Constructs a new Number uniform.
  32695. *
  32696. * @param {string} name - The uniform's name.
  32697. * @param {Color} value - The uniform's value.
  32698. */
  32699. constructor( name, value = new Color() ) {
  32700. super( name, value );
  32701. /**
  32702. * This flag can be used for type testing.
  32703. *
  32704. * @type {boolean}
  32705. * @readonly
  32706. * @default true
  32707. */
  32708. this.isColorUniform = true;
  32709. this.boundary = 16;
  32710. this.itemSize = 3;
  32711. }
  32712. }
  32713. /**
  32714. * Represents a Matrix2 uniform.
  32715. *
  32716. * @private
  32717. * @augments Uniform
  32718. */
  32719. class Matrix2Uniform extends Uniform {
  32720. /**
  32721. * Constructs a new Number uniform.
  32722. *
  32723. * @param {string} name - The uniform's name.
  32724. * @param {Matrix2} value - The uniform's value.
  32725. */
  32726. constructor( name, value = new Matrix2() ) {
  32727. super( name, value );
  32728. /**
  32729. * This flag can be used for type testing.
  32730. *
  32731. * @type {boolean}
  32732. * @readonly
  32733. * @default true
  32734. */
  32735. this.isMatrix2Uniform = true;
  32736. this.boundary = 8;
  32737. this.itemSize = 4;
  32738. }
  32739. }
  32740. /**
  32741. * Represents a Matrix3 uniform.
  32742. *
  32743. * @private
  32744. * @augments Uniform
  32745. */
  32746. class Matrix3Uniform extends Uniform {
  32747. /**
  32748. * Constructs a new Number uniform.
  32749. *
  32750. * @param {string} name - The uniform's name.
  32751. * @param {Matrix3} value - The uniform's value.
  32752. */
  32753. constructor( name, value = new Matrix3() ) {
  32754. super( name, value );
  32755. /**
  32756. * This flag can be used for type testing.
  32757. *
  32758. * @type {boolean}
  32759. * @readonly
  32760. * @default true
  32761. */
  32762. this.isMatrix3Uniform = true;
  32763. this.boundary = 48;
  32764. this.itemSize = 12;
  32765. }
  32766. }
  32767. /**
  32768. * Represents a Matrix4 uniform.
  32769. *
  32770. * @private
  32771. * @augments Uniform
  32772. */
  32773. class Matrix4Uniform extends Uniform {
  32774. /**
  32775. * Constructs a new Number uniform.
  32776. *
  32777. * @param {string} name - The uniform's name.
  32778. * @param {Matrix4} value - The uniform's value.
  32779. */
  32780. constructor( name, value = new Matrix4() ) {
  32781. super( name, value );
  32782. /**
  32783. * This flag can be used for type testing.
  32784. *
  32785. * @type {boolean}
  32786. * @readonly
  32787. * @default true
  32788. */
  32789. this.isMatrix4Uniform = true;
  32790. this.boundary = 64;
  32791. this.itemSize = 16;
  32792. }
  32793. }
  32794. /**
  32795. * A special form of Number uniform binding type.
  32796. * It's value is managed by a node object.
  32797. *
  32798. * @private
  32799. * @augments NumberUniform
  32800. */
  32801. class NumberNodeUniform extends NumberUniform {
  32802. /**
  32803. * Constructs a new node-based Number uniform.
  32804. *
  32805. * @param {NodeUniform} nodeUniform - The node uniform.
  32806. */
  32807. constructor( nodeUniform ) {
  32808. super( nodeUniform.name, nodeUniform.value );
  32809. /**
  32810. * The node uniform.
  32811. *
  32812. * @type {NodeUniform}
  32813. */
  32814. this.nodeUniform = nodeUniform;
  32815. }
  32816. /**
  32817. * Overwritten to return the value of the node uniform.
  32818. *
  32819. * @return {number} The value.
  32820. */
  32821. getValue() {
  32822. return this.nodeUniform.value;
  32823. }
  32824. /**
  32825. * Returns the node uniform data type.
  32826. *
  32827. * @return {string} The data type.
  32828. */
  32829. getType() {
  32830. return this.nodeUniform.type;
  32831. }
  32832. }
  32833. /**
  32834. * A special form of Vector2 uniform binding type.
  32835. * It's value is managed by a node object.
  32836. *
  32837. * @private
  32838. * @augments Vector2Uniform
  32839. */
  32840. class Vector2NodeUniform extends Vector2Uniform {
  32841. /**
  32842. * Constructs a new node-based Vector2 uniform.
  32843. *
  32844. * @param {NodeUniform} nodeUniform - The node uniform.
  32845. */
  32846. constructor( nodeUniform ) {
  32847. super( nodeUniform.name, nodeUniform.value );
  32848. /**
  32849. * The node uniform.
  32850. *
  32851. * @type {NodeUniform}
  32852. */
  32853. this.nodeUniform = nodeUniform;
  32854. }
  32855. /**
  32856. * Overwritten to return the value of the node uniform.
  32857. *
  32858. * @return {Vector2} The value.
  32859. */
  32860. getValue() {
  32861. return this.nodeUniform.value;
  32862. }
  32863. /**
  32864. * Returns the node uniform data type.
  32865. *
  32866. * @return {string} The data type.
  32867. */
  32868. getType() {
  32869. return this.nodeUniform.type;
  32870. }
  32871. }
  32872. /**
  32873. * A special form of Vector3 uniform binding type.
  32874. * It's value is managed by a node object.
  32875. *
  32876. * @private
  32877. * @augments Vector3Uniform
  32878. */
  32879. class Vector3NodeUniform extends Vector3Uniform {
  32880. /**
  32881. * Constructs a new node-based Vector3 uniform.
  32882. *
  32883. * @param {NodeUniform} nodeUniform - The node uniform.
  32884. */
  32885. constructor( nodeUniform ) {
  32886. super( nodeUniform.name, nodeUniform.value );
  32887. /**
  32888. * The node uniform.
  32889. *
  32890. * @type {NodeUniform}
  32891. */
  32892. this.nodeUniform = nodeUniform;
  32893. }
  32894. /**
  32895. * Overwritten to return the value of the node uniform.
  32896. *
  32897. * @return {Vector3} The value.
  32898. */
  32899. getValue() {
  32900. return this.nodeUniform.value;
  32901. }
  32902. /**
  32903. * Returns the node uniform data type.
  32904. *
  32905. * @return {string} The data type.
  32906. */
  32907. getType() {
  32908. return this.nodeUniform.type;
  32909. }
  32910. }
  32911. /**
  32912. * A special form of Vector4 uniform binding type.
  32913. * It's value is managed by a node object.
  32914. *
  32915. * @private
  32916. * @augments Vector4Uniform
  32917. */
  32918. class Vector4NodeUniform extends Vector4Uniform {
  32919. /**
  32920. * Constructs a new node-based Vector4 uniform.
  32921. *
  32922. * @param {NodeUniform} nodeUniform - The node uniform.
  32923. */
  32924. constructor( nodeUniform ) {
  32925. super( nodeUniform.name, nodeUniform.value );
  32926. /**
  32927. * The node uniform.
  32928. *
  32929. * @type {NodeUniform}
  32930. */
  32931. this.nodeUniform = nodeUniform;
  32932. }
  32933. /**
  32934. * Overwritten to return the value of the node uniform.
  32935. *
  32936. * @return {Vector4} The value.
  32937. */
  32938. getValue() {
  32939. return this.nodeUniform.value;
  32940. }
  32941. /**
  32942. * Returns the node uniform data type.
  32943. *
  32944. * @return {string} The data type.
  32945. */
  32946. getType() {
  32947. return this.nodeUniform.type;
  32948. }
  32949. }
  32950. /**
  32951. * A special form of Color uniform binding type.
  32952. * It's value is managed by a node object.
  32953. *
  32954. * @private
  32955. * @augments ColorUniform
  32956. */
  32957. class ColorNodeUniform extends ColorUniform {
  32958. /**
  32959. * Constructs a new node-based Color uniform.
  32960. *
  32961. * @param {NodeUniform} nodeUniform - The node uniform.
  32962. */
  32963. constructor( nodeUniform ) {
  32964. super( nodeUniform.name, nodeUniform.value );
  32965. /**
  32966. * The node uniform.
  32967. *
  32968. * @type {NodeUniform}
  32969. */
  32970. this.nodeUniform = nodeUniform;
  32971. }
  32972. /**
  32973. * Overwritten to return the value of the node uniform.
  32974. *
  32975. * @return {Color} The value.
  32976. */
  32977. getValue() {
  32978. return this.nodeUniform.value;
  32979. }
  32980. /**
  32981. * Returns the node uniform data type.
  32982. *
  32983. * @return {string} The data type.
  32984. */
  32985. getType() {
  32986. return this.nodeUniform.type;
  32987. }
  32988. }
  32989. /**
  32990. * A special form of Matrix2 uniform binding type.
  32991. * It's value is managed by a node object.
  32992. *
  32993. * @private
  32994. * @augments Matrix2Uniform
  32995. */
  32996. class Matrix2NodeUniform extends Matrix2Uniform {
  32997. /**
  32998. * Constructs a new node-based Matrix2 uniform.
  32999. *
  33000. * @param {NodeUniform} nodeUniform - The node uniform.
  33001. */
  33002. constructor( nodeUniform ) {
  33003. super( nodeUniform.name, nodeUniform.value );
  33004. /**
  33005. * The node uniform.
  33006. *
  33007. * @type {NodeUniform}
  33008. */
  33009. this.nodeUniform = nodeUniform;
  33010. }
  33011. /**
  33012. * Overwritten to return the value of the node uniform.
  33013. *
  33014. * @return {Matrix2} The value.
  33015. */
  33016. getValue() {
  33017. return this.nodeUniform.value;
  33018. }
  33019. /**
  33020. * Returns the node uniform data type.
  33021. *
  33022. * @return {string} The data type.
  33023. */
  33024. getType() {
  33025. return this.nodeUniform.type;
  33026. }
  33027. }
  33028. /**
  33029. * A special form of Matrix3 uniform binding type.
  33030. * It's value is managed by a node object.
  33031. *
  33032. * @private
  33033. * @augments Matrix3Uniform
  33034. */
  33035. class Matrix3NodeUniform extends Matrix3Uniform {
  33036. /**
  33037. * Constructs a new node-based Matrix3 uniform.
  33038. *
  33039. * @param {NodeUniform} nodeUniform - The node uniform.
  33040. */
  33041. constructor( nodeUniform ) {
  33042. super( nodeUniform.name, nodeUniform.value );
  33043. /**
  33044. * The node uniform.
  33045. *
  33046. * @type {NodeUniform}
  33047. */
  33048. this.nodeUniform = nodeUniform;
  33049. }
  33050. /**
  33051. * Overwritten to return the value of the node uniform.
  33052. *
  33053. * @return {Matrix3} The value.
  33054. */
  33055. getValue() {
  33056. return this.nodeUniform.value;
  33057. }
  33058. /**
  33059. * Returns the node uniform data type.
  33060. *
  33061. * @return {string} The data type.
  33062. */
  33063. getType() {
  33064. return this.nodeUniform.type;
  33065. }
  33066. }
  33067. /**
  33068. * A special form of Matrix4 uniform binding type.
  33069. * It's value is managed by a node object.
  33070. *
  33071. * @private
  33072. * @augments Matrix4Uniform
  33073. */
  33074. class Matrix4NodeUniform extends Matrix4Uniform {
  33075. /**
  33076. * Constructs a new node-based Matrix4 uniform.
  33077. *
  33078. * @param {NodeUniform} nodeUniform - The node uniform.
  33079. */
  33080. constructor( nodeUniform ) {
  33081. super( nodeUniform.name, nodeUniform.value );
  33082. /**
  33083. * The node uniform.
  33084. *
  33085. * @type {NodeUniform}
  33086. */
  33087. this.nodeUniform = nodeUniform;
  33088. }
  33089. /**
  33090. * Overwritten to return the value of the node uniform.
  33091. *
  33092. * @return {Matrix4} The value.
  33093. */
  33094. getValue() {
  33095. return this.nodeUniform.value;
  33096. }
  33097. /**
  33098. * Returns the node uniform data type.
  33099. *
  33100. * @return {string} The data type.
  33101. */
  33102. getType() {
  33103. return this.nodeUniform.type;
  33104. }
  33105. }
  33106. const rendererCache = new WeakMap();
  33107. const typeFromArray = new Map( [
  33108. [ Int8Array, 'int' ],
  33109. [ Int16Array, 'int' ],
  33110. [ Int32Array, 'int' ],
  33111. [ Uint8Array, 'uint' ],
  33112. [ Uint16Array, 'uint' ],
  33113. [ Uint32Array, 'uint' ],
  33114. [ Float32Array, 'float' ]
  33115. ] );
  33116. const toFloat = ( value ) => {
  33117. if ( /e/g.test( value ) ) {
  33118. return String( value ).replace( /\+/g, '' );
  33119. } else {
  33120. value = Number( value );
  33121. return value + ( value % 1 ? '' : '.0' );
  33122. }
  33123. };
  33124. /**
  33125. * Base class for builders which generate a shader program based
  33126. * on a 3D object and its node material definition.
  33127. */
  33128. class NodeBuilder {
  33129. /**
  33130. * Constructs a new node builder.
  33131. *
  33132. * @param {Object3D} object - The 3D object.
  33133. * @param {Renderer} renderer - The current renderer.
  33134. * @param {NodeParser} parser - A reference to a node parser.
  33135. */
  33136. constructor( object, renderer, parser ) {
  33137. /**
  33138. * The 3D object.
  33139. *
  33140. * @type {Object3D}
  33141. */
  33142. this.object = object;
  33143. /**
  33144. * The material of the 3D object.
  33145. *
  33146. * @type {?Material}
  33147. */
  33148. this.material = ( object && object.material ) || null;
  33149. /**
  33150. * The geometry of the 3D object.
  33151. *
  33152. * @type {?BufferGeometry}
  33153. */
  33154. this.geometry = ( object && object.geometry ) || null;
  33155. /**
  33156. * The current renderer.
  33157. *
  33158. * @type {Renderer}
  33159. */
  33160. this.renderer = renderer;
  33161. /**
  33162. * A reference to a node parser.
  33163. *
  33164. * @type {NodeParser}
  33165. */
  33166. this.parser = parser;
  33167. /**
  33168. * The scene the 3D object belongs to.
  33169. *
  33170. * @type {?Scene}
  33171. * @default null
  33172. */
  33173. this.scene = null;
  33174. /**
  33175. * The camera the 3D object is rendered with.
  33176. *
  33177. * @type {?Camera}
  33178. * @default null
  33179. */
  33180. this.camera = null;
  33181. /**
  33182. * A list of all nodes the builder is processing
  33183. * for this 3D object.
  33184. *
  33185. * @type {Array<Node>}
  33186. */
  33187. this.nodes = [];
  33188. /**
  33189. * A list of all sequential nodes.
  33190. *
  33191. * @type {Array<Node>}
  33192. */
  33193. this.sequentialNodes = [];
  33194. /**
  33195. * A list of all nodes which {@link Node#update} method should be executed.
  33196. *
  33197. * @type {Array<Node>}
  33198. */
  33199. this.updateNodes = [];
  33200. /**
  33201. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  33202. *
  33203. * @type {Array<Node>}
  33204. */
  33205. this.updateBeforeNodes = [];
  33206. /**
  33207. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  33208. *
  33209. * @type {Array<Node>}
  33210. */
  33211. this.updateAfterNodes = [];
  33212. /**
  33213. * A dictionary that assigns each node to a unique hash.
  33214. *
  33215. * @type {Object<number,Node>}
  33216. */
  33217. this.hashNodes = {};
  33218. /**
  33219. * A reference to a node material observer.
  33220. *
  33221. * @type {?NodeMaterialObserver}
  33222. * @default null
  33223. */
  33224. this.observer = null;
  33225. /**
  33226. * A reference to the current lights node.
  33227. *
  33228. * @type {?LightsNode}
  33229. * @default null
  33230. */
  33231. this.lightsNode = null;
  33232. /**
  33233. * A reference to the current environment node.
  33234. *
  33235. * @type {?Node}
  33236. * @default null
  33237. */
  33238. this.environmentNode = null;
  33239. /**
  33240. * A reference to the current fog node.
  33241. *
  33242. * @type {?Node}
  33243. * @default null
  33244. */
  33245. this.fogNode = null;
  33246. /**
  33247. * The current clipping context.
  33248. *
  33249. * @type {?ClippingContext}
  33250. */
  33251. this.clippingContext = null;
  33252. /**
  33253. * The generated vertex shader.
  33254. *
  33255. * @type {?string}
  33256. */
  33257. this.vertexShader = null;
  33258. /**
  33259. * The generated fragment shader.
  33260. *
  33261. * @type {?string}
  33262. */
  33263. this.fragmentShader = null;
  33264. /**
  33265. * The generated compute shader.
  33266. *
  33267. * @type {?string}
  33268. */
  33269. this.computeShader = null;
  33270. /**
  33271. * Nodes used in the primary flow of code generation.
  33272. *
  33273. * @type {Object<string,Array<Node>>}
  33274. */
  33275. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  33276. /**
  33277. * Nodes code from `.flowNodes`.
  33278. *
  33279. * @type {Object<string,string>}
  33280. */
  33281. this.flowCode = { vertex: '', fragment: '', compute: '' };
  33282. /**
  33283. * This dictionary holds the node uniforms of the builder.
  33284. * The uniforms are maintained in an array for each shader stage.
  33285. *
  33286. * @type {Object}
  33287. */
  33288. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  33289. /**
  33290. * This dictionary holds the output structs of the builder.
  33291. * The structs are maintained in an array for each shader stage.
  33292. *
  33293. * @type {Object}
  33294. */
  33295. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  33296. /**
  33297. * This dictionary holds the types of the builder.
  33298. *
  33299. * @type {Object}
  33300. */
  33301. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  33302. /**
  33303. * This dictionary holds the bindings for each shader stage.
  33304. *
  33305. * @type {Object}
  33306. */
  33307. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  33308. /**
  33309. * This dictionary maintains the binding indices per bind group.
  33310. *
  33311. * @type {Object}
  33312. */
  33313. this.bindingsIndexes = {};
  33314. /**
  33315. * Reference to the array of bind groups.
  33316. *
  33317. * @type {?Array<BindGroup>}
  33318. */
  33319. this.bindGroups = null;
  33320. /**
  33321. * This array holds the node attributes of this builder
  33322. * created via {@link AttributeNode}.
  33323. *
  33324. * @type {Array<NodeAttribute>}
  33325. */
  33326. this.attributes = [];
  33327. /**
  33328. * This array holds the node attributes of this builder
  33329. * created via {@link BufferAttributeNode}.
  33330. *
  33331. * @type {Array<NodeAttribute>}
  33332. */
  33333. this.bufferAttributes = [];
  33334. /**
  33335. * This array holds the node varyings of this builder.
  33336. *
  33337. * @type {Array<NodeVarying>}
  33338. */
  33339. this.varyings = [];
  33340. /**
  33341. * This dictionary holds the (native) node codes of this builder.
  33342. * The codes are maintained in an array for each shader stage.
  33343. *
  33344. * @type {Object<string,Array<NodeCode>>}
  33345. */
  33346. this.codes = {};
  33347. /**
  33348. * This dictionary holds the node variables of this builder.
  33349. * The variables are maintained in an array for each shader stage.
  33350. * This dictionary is also used to count the number of variables
  33351. * according to their type (const, vars).
  33352. *
  33353. * @type {Object<string,Array<NodeVar>|number>}
  33354. */
  33355. this.vars = {};
  33356. /**
  33357. * This dictionary holds the declarations for each shader stage.
  33358. *
  33359. * @type {Object}
  33360. */
  33361. this.declarations = {};
  33362. /**
  33363. * Current code flow.
  33364. * All code generated in this stack will be stored in `.flow`.
  33365. *
  33366. * @type {{code: string}}
  33367. */
  33368. this.flow = { code: '' };
  33369. /**
  33370. * A chain of nodes.
  33371. * Used to check recursive calls in node-graph.
  33372. *
  33373. * @type {Array<Node>}
  33374. */
  33375. this.chaining = [];
  33376. /**
  33377. * The current stack.
  33378. * This reflects the current process in the code block hierarchy,
  33379. * it is useful to know if the current process is inside a conditional for example.
  33380. *
  33381. * @type {StackNode}
  33382. */
  33383. this.stack = stack();
  33384. /**
  33385. * List of stack nodes.
  33386. * The current stack hierarchy is stored in an array.
  33387. *
  33388. * @type {Array<StackNode>}
  33389. */
  33390. this.stacks = [];
  33391. /**
  33392. * A tab value. Used for shader string generation.
  33393. *
  33394. * @type {string}
  33395. * @default '\t'
  33396. */
  33397. this.tab = '\t';
  33398. /**
  33399. * Reference to the current function node.
  33400. *
  33401. * @type {?FunctionNode}
  33402. * @default null
  33403. */
  33404. this.currentFunctionNode = null;
  33405. /**
  33406. * The builder's context.
  33407. *
  33408. * @type {Object}
  33409. */
  33410. this.context = {
  33411. material: this.material
  33412. };
  33413. /**
  33414. * The builder's cache.
  33415. *
  33416. * @type {NodeCache}
  33417. */
  33418. this.cache = new NodeCache();
  33419. /**
  33420. * Since the {@link NodeBuilder#cache} might be temporarily
  33421. * overwritten by other caches, this member retains the reference
  33422. * to the builder's own cache.
  33423. *
  33424. * @type {NodeCache}
  33425. * @default this.cache
  33426. */
  33427. this.globalCache = this.cache;
  33428. this.flowsData = new WeakMap();
  33429. /**
  33430. * The current shader stage.
  33431. *
  33432. * @type {?('vertex'|'fragment'|'compute'|'any')}
  33433. */
  33434. this.shaderStage = null;
  33435. /**
  33436. * The current build stage.
  33437. *
  33438. * @type {?('setup'|'analyze'|'generate')}
  33439. */
  33440. this.buildStage = null;
  33441. /**
  33442. * The sub-build layers.
  33443. *
  33444. * @type {Array<SubBuildNode>}
  33445. * @default []
  33446. */
  33447. this.subBuildLayers = [];
  33448. /**
  33449. * The current stack of nodes.
  33450. *
  33451. * @type {?StackNode}
  33452. * @default null
  33453. */
  33454. this.currentStack = null;
  33455. /**
  33456. * The current sub-build TSL function(Fn).
  33457. *
  33458. * @type {?string}
  33459. * @default null
  33460. */
  33461. this.subBuildFn = null;
  33462. }
  33463. /**
  33464. * Returns the bind groups of the current renderer.
  33465. *
  33466. * @return {ChainMap} The cache.
  33467. */
  33468. getBindGroupsCache() {
  33469. let bindGroupsCache = rendererCache.get( this.renderer );
  33470. if ( bindGroupsCache === undefined ) {
  33471. bindGroupsCache = new ChainMap();
  33472. rendererCache.set( this.renderer, bindGroupsCache );
  33473. }
  33474. return bindGroupsCache;
  33475. }
  33476. /**
  33477. * Factory method for creating an instance of {@link RenderTarget} with the given
  33478. * dimensions and options.
  33479. *
  33480. * @param {number} width - The width of the render target.
  33481. * @param {number} height - The height of the render target.
  33482. * @param {Object} options - The options of the render target.
  33483. * @return {RenderTarget} The render target.
  33484. */
  33485. createRenderTarget( width, height, options ) {
  33486. return new RenderTarget( width, height, options );
  33487. }
  33488. /**
  33489. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  33490. * dimensions and options.
  33491. *
  33492. * @param {number} size - The size of the cube render target.
  33493. * @param {Object} options - The options of the cube render target.
  33494. * @return {CubeRenderTarget} The cube render target.
  33495. */
  33496. createCubeRenderTarget( size, options ) {
  33497. return new CubeRenderTarget( size, options );
  33498. }
  33499. /**
  33500. * Whether the given node is included in the internal array of nodes or not.
  33501. *
  33502. * @param {Node} node - The node to test.
  33503. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  33504. */
  33505. includes( node ) {
  33506. return this.nodes.includes( node );
  33507. }
  33508. /**
  33509. * Returns the output struct name which is required by
  33510. * {@link OutputStructNode}.
  33511. *
  33512. * @abstract
  33513. * @return {string} The name of the output struct.
  33514. */
  33515. getOutputStructName() {}
  33516. /**
  33517. * Returns a bind group for the given group name and binding.
  33518. *
  33519. * @private
  33520. * @param {string} groupName - The group name.
  33521. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  33522. * @return {BindGroup} The bind group
  33523. */
  33524. _getBindGroup( groupName, bindings ) {
  33525. const bindGroupsCache = this.getBindGroupsCache();
  33526. //
  33527. const bindingsArray = [];
  33528. let sharedGroup = true;
  33529. for ( const binding of bindings ) {
  33530. bindingsArray.push( binding );
  33531. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  33532. }
  33533. //
  33534. let bindGroup;
  33535. if ( sharedGroup ) {
  33536. bindGroup = bindGroupsCache.get( bindingsArray );
  33537. if ( bindGroup === undefined ) {
  33538. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  33539. bindGroupsCache.set( bindingsArray, bindGroup );
  33540. }
  33541. } else {
  33542. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  33543. }
  33544. return bindGroup;
  33545. }
  33546. /**
  33547. * Returns an array of node uniform groups for the given group name and shader stage.
  33548. *
  33549. * @param {string} groupName - The group name.
  33550. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33551. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  33552. */
  33553. getBindGroupArray( groupName, shaderStage ) {
  33554. const bindings = this.bindings[ shaderStage ];
  33555. let bindGroup = bindings[ groupName ];
  33556. if ( bindGroup === undefined ) {
  33557. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  33558. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  33559. }
  33560. bindings[ groupName ] = bindGroup = [];
  33561. }
  33562. return bindGroup;
  33563. }
  33564. /**
  33565. * Returns a list bindings of all shader stages separated by groups.
  33566. *
  33567. * @return {Array<BindGroup>} The list of bindings.
  33568. */
  33569. getBindings() {
  33570. let bindingsGroups = this.bindGroups;
  33571. if ( bindingsGroups === null ) {
  33572. const groups = {};
  33573. const bindings = this.bindings;
  33574. for ( const shaderStage of shaderStages ) {
  33575. for ( const groupName in bindings[ shaderStage ] ) {
  33576. const uniforms = bindings[ shaderStage ][ groupName ];
  33577. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  33578. groupUniforms.push( ...uniforms );
  33579. }
  33580. }
  33581. bindingsGroups = [];
  33582. for ( const groupName in groups ) {
  33583. const group = groups[ groupName ];
  33584. const bindingsGroup = this._getBindGroup( groupName, group );
  33585. bindingsGroups.push( bindingsGroup );
  33586. }
  33587. this.bindGroups = bindingsGroups;
  33588. }
  33589. return bindingsGroups;
  33590. }
  33591. /**
  33592. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  33593. */
  33594. sortBindingGroups() {
  33595. const bindingsGroups = this.getBindings();
  33596. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  33597. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  33598. const bindingGroup = bindingsGroups[ i ];
  33599. this.bindingsIndexes[ bindingGroup.name ].group = i;
  33600. bindingGroup.index = i;
  33601. }
  33602. }
  33603. /**
  33604. * The builder maintains each node in a hash-based dictionary.
  33605. * This method sets the given node (value) with the given hash (key) into this dictionary.
  33606. *
  33607. * @param {Node} node - The node to add.
  33608. * @param {number} hash - The hash of the node.
  33609. */
  33610. setHashNode( node, hash ) {
  33611. this.hashNodes[ hash ] = node;
  33612. }
  33613. /**
  33614. * Adds a node to this builder.
  33615. *
  33616. * @param {Node} node - The node to add.
  33617. */
  33618. addNode( node ) {
  33619. if ( this.nodes.includes( node ) === false ) {
  33620. this.nodes.push( node );
  33621. this.setHashNode( node, node.getHash( this ) );
  33622. }
  33623. }
  33624. /**
  33625. * It is used to add Nodes that will be used as FRAME and RENDER events,
  33626. * and need to follow a certain sequence in the calls to work correctly.
  33627. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  33628. *
  33629. * @param {Node} node - The node to add.
  33630. */
  33631. addSequentialNode( node ) {
  33632. if ( this.sequentialNodes.includes( node ) === false ) {
  33633. this.sequentialNodes.push( node );
  33634. }
  33635. }
  33636. /**
  33637. * Checks the update types of nodes
  33638. */
  33639. buildUpdateNodes() {
  33640. for ( const node of this.nodes ) {
  33641. const updateType = node.getUpdateType();
  33642. if ( updateType !== NodeUpdateType.NONE ) {
  33643. this.updateNodes.push( node.getSelf() );
  33644. }
  33645. }
  33646. for ( const node of this.sequentialNodes ) {
  33647. const updateBeforeType = node.getUpdateBeforeType();
  33648. const updateAfterType = node.getUpdateAfterType();
  33649. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  33650. this.updateBeforeNodes.push( node.getSelf() );
  33651. }
  33652. if ( updateAfterType !== NodeUpdateType.NONE ) {
  33653. this.updateAfterNodes.push( node.getSelf() );
  33654. }
  33655. }
  33656. }
  33657. /**
  33658. * A reference the current node which is the
  33659. * last node in the chain of nodes.
  33660. *
  33661. * @type {Node}
  33662. */
  33663. get currentNode() {
  33664. return this.chaining[ this.chaining.length - 1 ];
  33665. }
  33666. /**
  33667. * Whether the given texture is filtered or not.
  33668. *
  33669. * @param {Texture} texture - The texture to check.
  33670. * @return {boolean} Whether the given texture is filtered or not.
  33671. */
  33672. isFilteredTexture( texture ) {
  33673. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  33674. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  33675. }
  33676. /**
  33677. * Adds the given node to the internal node chain.
  33678. * This is used to check recursive calls in node-graph.
  33679. *
  33680. * @param {Node} node - The node to add.
  33681. */
  33682. addChain( node ) {
  33683. /*
  33684. if ( this.chaining.indexOf( node ) !== - 1 ) {
  33685. console.warn( 'Recursive node: ', node );
  33686. }
  33687. */
  33688. this.chaining.push( node );
  33689. }
  33690. /**
  33691. * Removes the given node from the internal node chain.
  33692. *
  33693. * @param {Node} node - The node to remove.
  33694. */
  33695. removeChain( node ) {
  33696. const lastChain = this.chaining.pop();
  33697. if ( lastChain !== node ) {
  33698. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  33699. }
  33700. }
  33701. /**
  33702. * Returns the native shader method name for a given generic name. E.g.
  33703. * the method name `textureDimensions` matches the WGSL name but must be
  33704. * resolved to `textureSize` in GLSL.
  33705. *
  33706. * @abstract
  33707. * @param {string} method - The method name to resolve.
  33708. * @return {string} The resolved method name.
  33709. */
  33710. getMethod( method ) {
  33711. return method;
  33712. }
  33713. /**
  33714. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  33715. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  33716. *
  33717. * @abstract
  33718. * @param {string} condSnippet - The condition determining which expression gets resolved.
  33719. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  33720. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  33721. * @return {string} The resolved method name.
  33722. */
  33723. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  33724. return null;
  33725. }
  33726. /**
  33727. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  33728. *
  33729. * @param {number} hash - The hash of the node.
  33730. * @return {Node} The found node.
  33731. */
  33732. getNodeFromHash( hash ) {
  33733. return this.hashNodes[ hash ];
  33734. }
  33735. /**
  33736. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  33737. *
  33738. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  33739. * @param {Node} node - The node to add.
  33740. * @return {Node} The node.
  33741. */
  33742. addFlow( shaderStage, node ) {
  33743. this.flowNodes[ shaderStage ].push( node );
  33744. return node;
  33745. }
  33746. /**
  33747. * Sets builder's context.
  33748. *
  33749. * @param {Object} context - The context to set.
  33750. */
  33751. setContext( context ) {
  33752. this.context = context;
  33753. }
  33754. /**
  33755. * Returns the builder's current context.
  33756. *
  33757. * @return {Object} The builder's current context.
  33758. */
  33759. getContext() {
  33760. return this.context;
  33761. }
  33762. /**
  33763. * Gets a context used in shader construction that can be shared across different materials.
  33764. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  33765. *
  33766. * @return {Object} The builder's current context without material.
  33767. */
  33768. getSharedContext() {
  33769. ({ ...this.context });
  33770. return this.context;
  33771. }
  33772. /**
  33773. * Sets builder's cache.
  33774. *
  33775. * @param {NodeCache} cache - The cache to set.
  33776. */
  33777. setCache( cache ) {
  33778. this.cache = cache;
  33779. }
  33780. /**
  33781. * Returns the builder's current cache.
  33782. *
  33783. * @return {NodeCache} The builder's current cache.
  33784. */
  33785. getCache() {
  33786. return this.cache;
  33787. }
  33788. /**
  33789. * Returns a cache for the given node.
  33790. *
  33791. * @param {Node} node - The node.
  33792. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  33793. * @return {NodeCache} The cache.
  33794. */
  33795. getCacheFromNode( node, parent = true ) {
  33796. const data = this.getDataFromNode( node );
  33797. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  33798. return data.cache;
  33799. }
  33800. /**
  33801. * Whether the requested feature is available or not.
  33802. *
  33803. * @abstract
  33804. * @param {string} name - The requested feature.
  33805. * @return {boolean} Whether the requested feature is supported or not.
  33806. */
  33807. isAvailable( /*name*/ ) {
  33808. return false;
  33809. }
  33810. /**
  33811. * Returns the vertexIndex input variable as a native shader string.
  33812. *
  33813. * @abstract
  33814. * @return {string} The instanceIndex shader string.
  33815. */
  33816. getVertexIndex() {
  33817. console.warn( 'Abstract function.' );
  33818. }
  33819. /**
  33820. * Returns the instanceIndex input variable as a native shader string.
  33821. *
  33822. * @abstract
  33823. * @return {string} The instanceIndex shader string.
  33824. */
  33825. getInstanceIndex() {
  33826. console.warn( 'Abstract function.' );
  33827. }
  33828. /**
  33829. * Returns the drawIndex input variable as a native shader string.
  33830. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  33831. *
  33832. * @abstract
  33833. * @return {?string} The drawIndex shader string.
  33834. */
  33835. getDrawIndex() {
  33836. console.warn( 'Abstract function.' );
  33837. }
  33838. /**
  33839. * Returns the frontFacing input variable as a native shader string.
  33840. *
  33841. * @abstract
  33842. * @return {string} The frontFacing shader string.
  33843. */
  33844. getFrontFacing() {
  33845. console.warn( 'Abstract function.' );
  33846. }
  33847. /**
  33848. * Returns the fragCoord input variable as a native shader string.
  33849. *
  33850. * @abstract
  33851. * @return {string} The fragCoord shader string.
  33852. */
  33853. getFragCoord() {
  33854. console.warn( 'Abstract function.' );
  33855. }
  33856. /**
  33857. * Whether to flip texture data along its vertical axis or not. WebGL needs
  33858. * this method evaluate to `true`, WebGPU to `false`.
  33859. *
  33860. * @abstract
  33861. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  33862. */
  33863. isFlipY() {
  33864. return false;
  33865. }
  33866. /**
  33867. * Calling this method increases the usage count for the given node by one.
  33868. *
  33869. * @param {Node} node - The node to increase the usage count for.
  33870. * @return {number} The updated usage count.
  33871. */
  33872. increaseUsage( node ) {
  33873. const nodeData = this.getDataFromNode( node );
  33874. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  33875. return nodeData.usageCount;
  33876. }
  33877. /**
  33878. * Generates a texture sample shader string for the given texture data.
  33879. *
  33880. * @abstract
  33881. * @param {Texture} texture - The texture.
  33882. * @param {string} textureProperty - The texture property name.
  33883. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  33884. * @return {string} The generated shader string.
  33885. */
  33886. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  33887. console.warn( 'Abstract function.' );
  33888. }
  33889. /**
  33890. * Generates a texture LOD shader string for the given texture data.
  33891. *
  33892. * @abstract
  33893. * @param {Texture} texture - The texture.
  33894. * @param {string} textureProperty - The texture property name.
  33895. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  33896. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  33897. * @param {string} levelSnippet - Snippet defining the mip level.
  33898. * @return {string} The generated shader string.
  33899. */
  33900. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  33901. console.warn( 'Abstract function.' );
  33902. }
  33903. /**
  33904. * Generates the array declaration string.
  33905. *
  33906. * @param {string} type - The type.
  33907. * @param {?number} [count] - The count.
  33908. * @return {string} The generated value as a shader string.
  33909. */
  33910. generateArrayDeclaration( type, count ) {
  33911. return this.getType( type ) + '[ ' + count + ' ]';
  33912. }
  33913. /**
  33914. * Generates the array shader string for the given type and value.
  33915. *
  33916. * @param {string} type - The type.
  33917. * @param {?number} [count] - The count.
  33918. * @param {?Array<Node>} [values=null] - The default values.
  33919. * @return {string} The generated value as a shader string.
  33920. */
  33921. generateArray( type, count, values = null ) {
  33922. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  33923. for ( let i = 0; i < count; i ++ ) {
  33924. const value = values ? values[ i ] : null;
  33925. if ( value !== null ) {
  33926. snippet += value.build( this, type );
  33927. } else {
  33928. snippet += this.generateConst( type );
  33929. }
  33930. if ( i < count - 1 ) snippet += ', ';
  33931. }
  33932. snippet += ' )';
  33933. return snippet;
  33934. }
  33935. /**
  33936. * Generates the struct shader string.
  33937. *
  33938. * @param {string} type - The type.
  33939. * @param {Array<Object>} [membersLayout] - The count.
  33940. * @param {?Array<Node>} [values=null] - The default values.
  33941. * @return {string} The generated value as a shader string.
  33942. */
  33943. generateStruct( type, membersLayout, values = null ) {
  33944. const snippets = [];
  33945. for ( const member of membersLayout ) {
  33946. const { name, type } = member;
  33947. if ( values && values[ name ] && values[ name ].isNode ) {
  33948. snippets.push( values[ name ].build( this, type ) );
  33949. } else {
  33950. snippets.push( this.generateConst( type ) );
  33951. }
  33952. }
  33953. return type + '( ' + snippets.join( ', ' ) + ' )';
  33954. }
  33955. /**
  33956. * Generates the shader string for the given type and value.
  33957. *
  33958. * @param {string} type - The type.
  33959. * @param {?any} [value=null] - The value.
  33960. * @return {string} The generated value as a shader string.
  33961. */
  33962. generateConst( type, value = null ) {
  33963. if ( value === null ) {
  33964. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  33965. else if ( type === 'bool' ) value = false;
  33966. else if ( type === 'color' ) value = new Color();
  33967. else if ( type === 'vec2' ) value = new Vector2();
  33968. else if ( type === 'vec3' ) value = new Vector3();
  33969. else if ( type === 'vec4' ) value = new Vector4();
  33970. }
  33971. if ( type === 'float' ) return toFloat( value );
  33972. if ( type === 'int' ) return `${ Math.round( value ) }`;
  33973. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  33974. if ( type === 'bool' ) return value ? 'true' : 'false';
  33975. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  33976. const typeLength = this.getTypeLength( type );
  33977. const componentType = this.getComponentType( type );
  33978. const generateConst = value => this.generateConst( componentType, value );
  33979. if ( typeLength === 2 ) {
  33980. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  33981. } else if ( typeLength === 3 ) {
  33982. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  33983. } else if ( typeLength === 4 && type !== 'mat2' ) {
  33984. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  33985. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  33986. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  33987. } else if ( typeLength > 4 ) {
  33988. return `${ this.getType( type ) }()`;
  33989. }
  33990. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  33991. }
  33992. /**
  33993. * It might be necessary to convert certain data types to different ones
  33994. * so this method can be used to hide the conversion.
  33995. *
  33996. * @param {string} type - The type.
  33997. * @return {string} The updated type.
  33998. */
  33999. getType( type ) {
  34000. if ( type === 'color' ) return 'vec3';
  34001. return type;
  34002. }
  34003. /**
  34004. * Whether the given attribute name is defined in the geometry or not.
  34005. *
  34006. * @param {string} name - The attribute name.
  34007. * @return {boolean} Whether the given attribute name is defined in the geometry.
  34008. */
  34009. hasGeometryAttribute( name ) {
  34010. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  34011. }
  34012. /**
  34013. * Returns a node attribute for the given name and type.
  34014. *
  34015. * @param {string} name - The attribute's name.
  34016. * @param {string} type - The attribute's type.
  34017. * @return {NodeAttribute} The node attribute.
  34018. */
  34019. getAttribute( name, type ) {
  34020. const attributes = this.attributes;
  34021. // find attribute
  34022. for ( const attribute of attributes ) {
  34023. if ( attribute.name === name ) {
  34024. return attribute;
  34025. }
  34026. }
  34027. // create a new if no exist
  34028. const attribute = new NodeAttribute( name, type );
  34029. this.registerDeclaration( attribute );
  34030. attributes.push( attribute );
  34031. return attribute;
  34032. }
  34033. /**
  34034. * Returns for the given node and shader stage the property name for the shader.
  34035. *
  34036. * @param {Node} node - The node.
  34037. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34038. * @return {string} The property name.
  34039. */
  34040. getPropertyName( node/*, shaderStage*/ ) {
  34041. return node.name;
  34042. }
  34043. /**
  34044. * Whether the given type is a vector type or not.
  34045. *
  34046. * @param {string} type - The type to check.
  34047. * @return {boolean} Whether the given type is a vector type or not.
  34048. */
  34049. isVector( type ) {
  34050. return /vec\d/.test( type );
  34051. }
  34052. /**
  34053. * Whether the given type is a matrix type or not.
  34054. *
  34055. * @param {string} type - The type to check.
  34056. * @return {boolean} Whether the given type is a matrix type or not.
  34057. */
  34058. isMatrix( type ) {
  34059. return /mat\d/.test( type );
  34060. }
  34061. /**
  34062. * Whether the given type is a reference type or not.
  34063. *
  34064. * @param {string} type - The type to check.
  34065. * @return {boolean} Whether the given type is a reference type or not.
  34066. */
  34067. isReference( type ) {
  34068. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  34069. }
  34070. /**
  34071. * Checks if the given texture requires a manual conversion to the working color space.
  34072. *
  34073. * @abstract
  34074. * @param {Texture} texture - The texture to check.
  34075. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  34076. */
  34077. needsToWorkingColorSpace( /*texture*/ ) {
  34078. return false;
  34079. }
  34080. /**
  34081. * Returns the component type of a given texture.
  34082. *
  34083. * @param {Texture} texture - The texture.
  34084. * @return {string} The component type.
  34085. */
  34086. getComponentTypeFromTexture( texture ) {
  34087. const type = texture.type;
  34088. if ( texture.isDataTexture ) {
  34089. if ( type === IntType ) return 'int';
  34090. if ( type === UnsignedIntType ) return 'uint';
  34091. }
  34092. return 'float';
  34093. }
  34094. /**
  34095. * Returns the element type for a given type.
  34096. *
  34097. * @param {string} type - The type.
  34098. * @return {string} The element type.
  34099. */
  34100. getElementType( type ) {
  34101. if ( type === 'mat2' ) return 'vec2';
  34102. if ( type === 'mat3' ) return 'vec3';
  34103. if ( type === 'mat4' ) return 'vec4';
  34104. return this.getComponentType( type );
  34105. }
  34106. /**
  34107. * Returns the component type for a given type.
  34108. *
  34109. * @param {string} type - The type.
  34110. * @return {string} The component type.
  34111. */
  34112. getComponentType( type ) {
  34113. type = this.getVectorType( type );
  34114. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  34115. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  34116. if ( componentType === null ) return null;
  34117. if ( componentType[ 1 ] === 'b' ) return 'bool';
  34118. if ( componentType[ 1 ] === 'i' ) return 'int';
  34119. if ( componentType[ 1 ] === 'u' ) return 'uint';
  34120. return 'float';
  34121. }
  34122. /**
  34123. * Returns the vector type for a given type.
  34124. *
  34125. * @param {string} type - The type.
  34126. * @return {string} The vector type.
  34127. */
  34128. getVectorType( type ) {
  34129. if ( type === 'color' ) return 'vec3';
  34130. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  34131. return type;
  34132. }
  34133. /**
  34134. * Returns the data type for the given the length and component type.
  34135. *
  34136. * @param {number} length - The length.
  34137. * @param {string} [componentType='float'] - The component type.
  34138. * @return {string} The type.
  34139. */
  34140. getTypeFromLength( length, componentType = 'float' ) {
  34141. if ( length === 1 ) return componentType;
  34142. let baseType = getTypeFromLength( length );
  34143. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  34144. // fix edge case for mat2x2 being same size as vec4
  34145. if ( /mat2/.test( componentType ) === true ) {
  34146. baseType = baseType.replace( 'vec', 'mat' );
  34147. }
  34148. return prefix + baseType;
  34149. }
  34150. /**
  34151. * Returns the type for a given typed array.
  34152. *
  34153. * @param {TypedArray} array - The typed array.
  34154. * @return {string} The type.
  34155. */
  34156. getTypeFromArray( array ) {
  34157. return typeFromArray.get( array.constructor );
  34158. }
  34159. /**
  34160. * Returns the type is an integer type.
  34161. *
  34162. * @param {string} type - The type.
  34163. * @return {boolean} Whether the type is an integer type or not.
  34164. */
  34165. isInteger( type ) {
  34166. return /int|uint|(i|u)vec/.test( type );
  34167. }
  34168. /**
  34169. * Returns the type for a given buffer attribute.
  34170. *
  34171. * @param {BufferAttribute} attribute - The buffer attribute.
  34172. * @return {string} The type.
  34173. */
  34174. getTypeFromAttribute( attribute ) {
  34175. let dataAttribute = attribute;
  34176. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  34177. const array = dataAttribute.array;
  34178. const itemSize = attribute.itemSize;
  34179. const normalized = attribute.normalized;
  34180. let arrayType;
  34181. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  34182. arrayType = this.getTypeFromArray( array );
  34183. }
  34184. return this.getTypeFromLength( itemSize, arrayType );
  34185. }
  34186. /**
  34187. * Returns the length for the given data type.
  34188. *
  34189. * @param {string} type - The data type.
  34190. * @return {number} The length.
  34191. */
  34192. getTypeLength( type ) {
  34193. const vecType = this.getVectorType( type );
  34194. const vecNum = /vec([2-4])/.exec( vecType );
  34195. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  34196. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  34197. if ( /mat2/.test( type ) === true ) return 4;
  34198. if ( /mat3/.test( type ) === true ) return 9;
  34199. if ( /mat4/.test( type ) === true ) return 16;
  34200. return 0;
  34201. }
  34202. /**
  34203. * Returns the vector type for a given matrix type.
  34204. *
  34205. * @param {string} type - The matrix type.
  34206. * @return {string} The vector type.
  34207. */
  34208. getVectorFromMatrix( type ) {
  34209. return type.replace( 'mat', 'vec' );
  34210. }
  34211. /**
  34212. * For a given type this method changes the component type to the
  34213. * given value. E.g. `vec4` should be changed to the new component type
  34214. * `uint` which results in `uvec4`.
  34215. *
  34216. * @param {string} type - The type.
  34217. * @param {string} newComponentType - The new component type.
  34218. * @return {string} The new type.
  34219. */
  34220. changeComponentType( type, newComponentType ) {
  34221. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  34222. }
  34223. /**
  34224. * Returns the integer type pendant for the given type.
  34225. *
  34226. * @param {string} type - The type.
  34227. * @return {string} The integer type.
  34228. */
  34229. getIntegerType( type ) {
  34230. const componentType = this.getComponentType( type );
  34231. if ( componentType === 'int' || componentType === 'uint' ) return type;
  34232. return this.changeComponentType( type, 'int' );
  34233. }
  34234. /**
  34235. * Adds a stack node to the internal stack.
  34236. *
  34237. * @return {StackNode} The added stack node.
  34238. */
  34239. addStack() {
  34240. this.stack = stack( this.stack );
  34241. this.stacks.push( getCurrentStack() || this.stack );
  34242. setCurrentStack( this.stack );
  34243. return this.stack;
  34244. }
  34245. /**
  34246. * Removes the last stack node from the internal stack.
  34247. *
  34248. * @return {StackNode} The removed stack node.
  34249. */
  34250. removeStack() {
  34251. const lastStack = this.stack;
  34252. this.stack = lastStack.parent;
  34253. setCurrentStack( this.stacks.pop() );
  34254. return lastStack;
  34255. }
  34256. /**
  34257. * The builder maintains (cached) data for each node during the building process. This method
  34258. * can be used to get these data for a specific shader stage and cache.
  34259. *
  34260. * @param {Node} node - The node to get the data for.
  34261. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34262. * @param {?NodeCache} cache - An optional cache.
  34263. * @return {Object} The node data.
  34264. */
  34265. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  34266. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  34267. let nodeData = cache.getData( node );
  34268. if ( nodeData === undefined ) {
  34269. nodeData = {};
  34270. cache.setData( node, nodeData );
  34271. }
  34272. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  34273. //
  34274. let data = nodeData[ shaderStage ];
  34275. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  34276. const subBuild = this.getClosestSubBuild( subBuilds );
  34277. if ( subBuild ) {
  34278. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  34279. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  34280. data.subBuilds = subBuilds;
  34281. }
  34282. return data;
  34283. }
  34284. /**
  34285. * Returns the properties for the given node and shader stage.
  34286. *
  34287. * @param {Node} node - The node to get the properties for.
  34288. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  34289. * @return {Object} The node properties.
  34290. */
  34291. getNodeProperties( node, shaderStage = 'any' ) {
  34292. const nodeData = this.getDataFromNode( node, shaderStage );
  34293. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  34294. }
  34295. /**
  34296. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  34297. *
  34298. * @param {BufferAttributeNode} node - The buffer attribute node.
  34299. * @param {string} type - The node type.
  34300. * @return {NodeAttribute} The node attribute.
  34301. */
  34302. getBufferAttributeFromNode( node, type ) {
  34303. const nodeData = this.getDataFromNode( node );
  34304. let bufferAttribute = nodeData.bufferAttribute;
  34305. if ( bufferAttribute === undefined ) {
  34306. const index = this.uniforms.index ++;
  34307. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  34308. this.bufferAttributes.push( bufferAttribute );
  34309. nodeData.bufferAttribute = bufferAttribute;
  34310. }
  34311. return bufferAttribute;
  34312. }
  34313. /**
  34314. * Returns an instance of {@link StructType} for the given struct name and shader stage
  34315. * or null if not found.
  34316. *
  34317. * @param {string} name - The name of the struct.
  34318. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34319. * @return {?StructType} The struct type or null if not found.
  34320. */
  34321. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  34322. return this.types[ shaderStage ][ name ] || null;
  34323. }
  34324. /**
  34325. * Returns an instance of {@link StructType} for the given output struct node.
  34326. *
  34327. * @param {OutputStructNode} node - The output struct node.
  34328. * @param {Array<Object>} membersLayout - The output struct types.
  34329. * @param {?string} [name=null] - The name of the struct.
  34330. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34331. * @return {StructType} The struct type attribute.
  34332. */
  34333. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  34334. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34335. let structType = nodeData.structType;
  34336. if ( structType === undefined ) {
  34337. const index = this.structs.index ++;
  34338. if ( name === null ) name = 'StructType' + index;
  34339. structType = new StructType( name, membersLayout );
  34340. this.structs[ shaderStage ].push( structType );
  34341. this.types[ shaderStage ][ name ] = node;
  34342. nodeData.structType = structType;
  34343. }
  34344. return structType;
  34345. }
  34346. /**
  34347. * Returns an instance of {@link StructType} for the given output struct node.
  34348. *
  34349. * @param {OutputStructNode} node - The output struct node.
  34350. * @param {Array<Object>} membersLayout - The output struct types.
  34351. * @return {StructType} The struct type attribute.
  34352. */
  34353. getOutputStructTypeFromNode( node, membersLayout ) {
  34354. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  34355. structType.output = true;
  34356. return structType;
  34357. }
  34358. /**
  34359. * Returns an instance of {@link NodeUniform} for the given uniform node.
  34360. *
  34361. * @param {UniformNode} node - The uniform node.
  34362. * @param {string} type - The uniform type.
  34363. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34364. * @param {?string} name - The name of the uniform.
  34365. * @return {NodeUniform} The node uniform.
  34366. */
  34367. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  34368. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34369. let nodeUniform = nodeData.uniform;
  34370. if ( nodeUniform === undefined ) {
  34371. const index = this.uniforms.index ++;
  34372. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  34373. this.uniforms[ shaderStage ].push( nodeUniform );
  34374. this.registerDeclaration( nodeUniform );
  34375. nodeData.uniform = nodeUniform;
  34376. }
  34377. return nodeUniform;
  34378. }
  34379. /**
  34380. * Returns an instance of {@link NodeVar} for the given variable node.
  34381. *
  34382. * @param {VarNode} node - The variable node.
  34383. * @param {?string} name - The variable's name.
  34384. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  34385. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34386. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  34387. *
  34388. * @return {NodeVar} The node variable.
  34389. */
  34390. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  34391. const nodeData = this.getDataFromNode( node, shaderStage );
  34392. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  34393. let nodeVar = nodeData[ subBuildVariable ];
  34394. if ( nodeVar === undefined ) {
  34395. const idNS = readOnly ? '_const' : '_var';
  34396. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  34397. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  34398. if ( name === null ) {
  34399. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  34400. this.vars[ idNS ] ++;
  34401. }
  34402. //
  34403. if ( subBuildVariable !== 'variable' ) {
  34404. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  34405. }
  34406. //
  34407. const count = node.getArrayCount( this );
  34408. nodeVar = new NodeVar( name, type, readOnly, count );
  34409. if ( ! readOnly ) {
  34410. vars.push( nodeVar );
  34411. }
  34412. this.registerDeclaration( nodeVar );
  34413. nodeData[ subBuildVariable ] = nodeVar;
  34414. }
  34415. return nodeVar;
  34416. }
  34417. /**
  34418. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  34419. *
  34420. * @param {Node} node - The varying node.
  34421. * @return {boolean} Returns true if deterministic.
  34422. */
  34423. isDeterministic( node ) {
  34424. if ( node.isMathNode ) {
  34425. return this.isDeterministic( node.aNode ) &&
  34426. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  34427. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  34428. } else if ( node.isOperatorNode ) {
  34429. return this.isDeterministic( node.aNode ) &&
  34430. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  34431. } else if ( node.isArrayNode ) {
  34432. if ( node.values !== null ) {
  34433. for ( const n of node.values ) {
  34434. if ( ! this.isDeterministic( n ) ) {
  34435. return false;
  34436. }
  34437. }
  34438. }
  34439. return true;
  34440. } else if ( node.isConstNode ) {
  34441. return true;
  34442. }
  34443. return false;
  34444. }
  34445. /**
  34446. * Returns an instance of {@link NodeVarying} for the given varying node.
  34447. *
  34448. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  34449. * @param {?string} name - The varying's name.
  34450. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  34451. * @param {?string} interpolationType - The interpolation type of the varying.
  34452. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34453. * @return {NodeVar} The node varying.
  34454. */
  34455. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  34456. const nodeData = this.getDataFromNode( node, 'any' );
  34457. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  34458. let nodeVarying = nodeData[ subBuildVarying ];
  34459. if ( nodeVarying === undefined ) {
  34460. const varyings = this.varyings;
  34461. const index = varyings.length;
  34462. if ( name === null ) name = 'nodeVarying' + index;
  34463. //
  34464. if ( subBuildVarying !== 'varying' ) {
  34465. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  34466. }
  34467. //
  34468. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  34469. varyings.push( nodeVarying );
  34470. this.registerDeclaration( nodeVarying );
  34471. nodeData[ subBuildVarying ] = nodeVarying;
  34472. }
  34473. return nodeVarying;
  34474. }
  34475. /**
  34476. * Registers a node declaration in the current shader stage.
  34477. *
  34478. * @param {Object} node - The node to be registered.
  34479. */
  34480. registerDeclaration( node ) {
  34481. const shaderStage = this.shaderStage;
  34482. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  34483. const property = this.getPropertyName( node );
  34484. let index = 1;
  34485. let name = property;
  34486. // Automatically renames the property if the name is already in use.
  34487. while ( declarations[ name ] !== undefined ) {
  34488. name = property + '_' + index ++;
  34489. }
  34490. if ( index > 1 ) {
  34491. node.name = name;
  34492. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  34493. }
  34494. declarations[ name ] = node;
  34495. }
  34496. /**
  34497. * Returns an instance of {@link NodeCode} for the given code node.
  34498. *
  34499. * @param {CodeNode} node - The code node.
  34500. * @param {string} type - The node type.
  34501. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34502. * @return {NodeCode} The node code.
  34503. */
  34504. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  34505. const nodeData = this.getDataFromNode( node );
  34506. let nodeCode = nodeData.code;
  34507. if ( nodeCode === undefined ) {
  34508. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  34509. const index = codes.length;
  34510. nodeCode = new NodeCode( 'nodeCode' + index, type );
  34511. codes.push( nodeCode );
  34512. nodeData.code = nodeCode;
  34513. }
  34514. return nodeCode;
  34515. }
  34516. /**
  34517. * Adds a code flow based on the code-block hierarchy.
  34518. * This is used so that code-blocks like If,Else create their variables locally if the Node
  34519. * is only used inside one of these conditionals in the current shader stage.
  34520. *
  34521. * @param {Node} node - The node to add.
  34522. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  34523. */
  34524. addFlowCodeHierarchy( node, nodeBlock ) {
  34525. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  34526. let needsFlowCode = true;
  34527. let nodeBlockHierarchy = nodeBlock;
  34528. while ( nodeBlockHierarchy ) {
  34529. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  34530. needsFlowCode = false;
  34531. break;
  34532. }
  34533. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  34534. }
  34535. if ( needsFlowCode ) {
  34536. for ( const flowCode of flowCodes ) {
  34537. this.addLineFlowCode( flowCode );
  34538. }
  34539. }
  34540. }
  34541. /**
  34542. * Add a inline-code to the current flow code-block.
  34543. *
  34544. * @param {Node} node - The node to add.
  34545. * @param {string} code - The code to add.
  34546. * @param {Node} nodeBlock - Current ConditionalNode
  34547. */
  34548. addLineFlowCodeBlock( node, code, nodeBlock ) {
  34549. const nodeData = this.getDataFromNode( node );
  34550. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  34551. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  34552. flowCodes.push( code );
  34553. codeBlock.set( nodeBlock, true );
  34554. }
  34555. /**
  34556. * Add a inline-code to the current flow.
  34557. *
  34558. * @param {string} code - The code to add.
  34559. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  34560. * @return {NodeBuilder} A reference to this node builder.
  34561. */
  34562. addLineFlowCode( code, node = null ) {
  34563. if ( code === '' ) return this;
  34564. if ( node !== null && this.context.nodeBlock ) {
  34565. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  34566. }
  34567. code = this.tab + code;
  34568. if ( ! /;\s*$/.test( code ) ) {
  34569. code = code + ';\n';
  34570. }
  34571. this.flow.code += code;
  34572. return this;
  34573. }
  34574. /**
  34575. * Adds a code to the current code flow.
  34576. *
  34577. * @param {string} code - Shader code.
  34578. * @return {NodeBuilder} A reference to this node builder.
  34579. */
  34580. addFlowCode( code ) {
  34581. this.flow.code += code;
  34582. return this;
  34583. }
  34584. /**
  34585. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  34586. * Typically used in codes with If,Else.
  34587. *
  34588. * @return {NodeBuilder} A reference to this node builder.
  34589. */
  34590. addFlowTab() {
  34591. this.tab += '\t';
  34592. return this;
  34593. }
  34594. /**
  34595. * Removes a tab.
  34596. *
  34597. * @return {NodeBuilder} A reference to this node builder.
  34598. */
  34599. removeFlowTab() {
  34600. this.tab = this.tab.slice( 0, -1 );
  34601. return this;
  34602. }
  34603. /**
  34604. * Gets the current flow data based on a Node.
  34605. *
  34606. * @param {Node} node - Node that the flow was started.
  34607. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34608. * @return {Object} The flow data.
  34609. */
  34610. getFlowData( node/*, shaderStage*/ ) {
  34611. return this.flowsData.get( node );
  34612. }
  34613. /**
  34614. * Executes the node flow based on a root node to generate the final shader code.
  34615. *
  34616. * @param {Node} node - The node to execute.
  34617. * @return {Object} The code flow.
  34618. */
  34619. flowNode( node ) {
  34620. const output = node.getNodeType( this );
  34621. const flowData = this.flowChildNode( node, output );
  34622. this.flowsData.set( node, flowData );
  34623. return flowData;
  34624. }
  34625. /**
  34626. * Includes a node in the current function node.
  34627. *
  34628. * @param {Node} node - The node to include.
  34629. * @returns {void}
  34630. */
  34631. addInclude( node ) {
  34632. if ( this.currentFunctionNode !== null ) {
  34633. this.currentFunctionNode.includes.push( node );
  34634. }
  34635. }
  34636. /**
  34637. * Returns the native shader operator name for a given generic name.
  34638. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  34639. *
  34640. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  34641. * @return {FunctionNode} The build function node.
  34642. */
  34643. buildFunctionNode( shaderNode ) {
  34644. const fn = new FunctionNode();
  34645. const previous = this.currentFunctionNode;
  34646. this.currentFunctionNode = fn;
  34647. fn.code = this.buildFunctionCode( shaderNode );
  34648. this.currentFunctionNode = previous;
  34649. return fn;
  34650. }
  34651. /**
  34652. * Generates a code flow based on a TSL function: Fn().
  34653. *
  34654. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  34655. * @return {Object}
  34656. */
  34657. flowShaderNode( shaderNode ) {
  34658. const layout = shaderNode.layout;
  34659. const inputs = {
  34660. [ Symbol.iterator ]() {
  34661. let index = 0;
  34662. const values = Object.values( this );
  34663. return {
  34664. next: () => ( {
  34665. value: values[ index ],
  34666. done: index ++ >= values.length
  34667. } )
  34668. };
  34669. }
  34670. };
  34671. for ( const input of layout.inputs ) {
  34672. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  34673. }
  34674. //
  34675. shaderNode.layout = null;
  34676. const callNode = shaderNode.call( inputs );
  34677. const flowData = this.flowStagesNode( callNode, layout.type );
  34678. shaderNode.layout = layout;
  34679. return flowData;
  34680. }
  34681. /**
  34682. * Executes the node in a specific build stage.
  34683. *
  34684. * @param {Node} node - The node to execute.
  34685. * @param {string} buildStage - The build stage to execute the node in.
  34686. * @param {Node|string|null} output - Expected output type. For example 'vec3'.
  34687. * @return {Node|string|null} The result of the node build.
  34688. */
  34689. flowBuildStage( node, buildStage, output = null ) {
  34690. const previousBuildStage = this.getBuildStage();
  34691. this.setBuildStage( buildStage );
  34692. const result = node.build( this, output );
  34693. this.setBuildStage( previousBuildStage );
  34694. return result;
  34695. }
  34696. /**
  34697. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  34698. *
  34699. * @param {Node} node - The node to execute.
  34700. * @param {?string} output - Expected output type. For example 'vec3'.
  34701. * @return {Object}
  34702. */
  34703. flowStagesNode( node, output = null ) {
  34704. const previousFlow = this.flow;
  34705. const previousVars = this.vars;
  34706. const previousDeclarations = this.declarations;
  34707. const previousCache = this.cache;
  34708. const previousBuildStage = this.buildStage;
  34709. const previousStack = this.stack;
  34710. const flow = {
  34711. code: ''
  34712. };
  34713. this.flow = flow;
  34714. this.vars = {};
  34715. this.declarations = {};
  34716. this.cache = new NodeCache();
  34717. this.stack = stack();
  34718. for ( const buildStage of defaultBuildStages ) {
  34719. this.setBuildStage( buildStage );
  34720. flow.result = node.build( this, output );
  34721. }
  34722. flow.vars = this.getVars( this.shaderStage );
  34723. this.flow = previousFlow;
  34724. this.vars = previousVars;
  34725. this.declarations = previousDeclarations;
  34726. this.cache = previousCache;
  34727. this.stack = previousStack;
  34728. this.setBuildStage( previousBuildStage );
  34729. return flow;
  34730. }
  34731. /**
  34732. * Returns the native shader operator name for a given generic name.
  34733. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  34734. *
  34735. * @abstract
  34736. * @param {string} op - The operator name to resolve.
  34737. * @return {?string} The resolved operator name.
  34738. */
  34739. getFunctionOperator( /* op */ ) {
  34740. return null;
  34741. }
  34742. /**
  34743. * Builds the given shader node.
  34744. *
  34745. * @abstract
  34746. * @param {ShaderNodeInternal} shaderNode - The shader node.
  34747. * @return {string} The function code.
  34748. */
  34749. buildFunctionCode( /* shaderNode */ ) {
  34750. console.warn( 'Abstract function.' );
  34751. }
  34752. /**
  34753. * Generates a code flow based on a child Node.
  34754. *
  34755. * @param {Node} node - The node to execute.
  34756. * @param {?string} output - Expected output type. For example 'vec3'.
  34757. * @return {Object} The code flow.
  34758. */
  34759. flowChildNode( node, output = null ) {
  34760. const previousFlow = this.flow;
  34761. const flow = {
  34762. code: ''
  34763. };
  34764. this.flow = flow;
  34765. flow.result = node.build( this, output );
  34766. this.flow = previousFlow;
  34767. return flow;
  34768. }
  34769. /**
  34770. * Executes a flow of code in a different stage.
  34771. *
  34772. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  34773. * return the value in fragment-stage even if it is being executed in an input fragment.
  34774. *
  34775. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34776. * @param {Node} node - The node to execute.
  34777. * @param {?string} output - Expected output type. For example 'vec3'.
  34778. * @param {?string} propertyName - The property name to assign the result.
  34779. * @return {Object|Node|null} The code flow or node.build() result.
  34780. */
  34781. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  34782. const previousTab = this.tab;
  34783. const previousCache = this.cache;
  34784. const previousShaderStage = this.shaderStage;
  34785. const previousContext = this.context;
  34786. this.setShaderStage( shaderStage );
  34787. const context = { ...this.context };
  34788. delete context.nodeBlock;
  34789. this.cache = this.globalCache;
  34790. this.tab = '\t';
  34791. this.context = context;
  34792. let result = null;
  34793. if ( this.buildStage === 'generate' ) {
  34794. const flowData = this.flowChildNode( node, output );
  34795. if ( propertyName !== null ) {
  34796. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  34797. }
  34798. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  34799. result = flowData;
  34800. } else {
  34801. result = node.build( this );
  34802. }
  34803. this.setShaderStage( previousShaderStage );
  34804. this.cache = previousCache;
  34805. this.tab = previousTab;
  34806. this.context = previousContext;
  34807. return result;
  34808. }
  34809. /**
  34810. * Returns an array holding all node attributes of this node builder.
  34811. *
  34812. * @return {Array<NodeAttribute>} The node attributes of this builder.
  34813. */
  34814. getAttributesArray() {
  34815. return this.attributes.concat( this.bufferAttributes );
  34816. }
  34817. /**
  34818. * Returns the attribute definitions as a shader string for the given shader stage.
  34819. *
  34820. * @abstract
  34821. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34822. * @return {string} The attribute code section.
  34823. */
  34824. getAttributes( /*shaderStage*/ ) {
  34825. console.warn( 'Abstract function.' );
  34826. }
  34827. /**
  34828. * Returns the varying definitions as a shader string for the given shader stage.
  34829. *
  34830. * @abstract
  34831. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34832. * @return {string} The varying code section.
  34833. */
  34834. getVaryings( /*shaderStage*/ ) {
  34835. console.warn( 'Abstract function.' );
  34836. }
  34837. /**
  34838. * Returns a single variable definition as a shader string for the given variable type and name.
  34839. *
  34840. * @param {string} type - The variable's type.
  34841. * @param {string} name - The variable's name.
  34842. * @param {?number} [count=null] - The array length.
  34843. * @return {string} The shader string.
  34844. */
  34845. getVar( type, name, count = null ) {
  34846. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  34847. }
  34848. /**
  34849. * Returns the variable definitions as a shader string for the given shader stage.
  34850. *
  34851. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34852. * @return {string} The variable code section.
  34853. */
  34854. getVars( shaderStage ) {
  34855. let snippet = '';
  34856. const vars = this.vars[ shaderStage ];
  34857. if ( vars !== undefined ) {
  34858. for ( const variable of vars ) {
  34859. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  34860. }
  34861. }
  34862. return snippet;
  34863. }
  34864. /**
  34865. * Returns the uniform definitions as a shader string for the given shader stage.
  34866. *
  34867. * @abstract
  34868. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34869. * @return {string} The uniform code section.
  34870. */
  34871. getUniforms( /*shaderStage*/ ) {
  34872. console.warn( 'Abstract function.' );
  34873. }
  34874. /**
  34875. * Returns the native code definitions as a shader string for the given shader stage.
  34876. *
  34877. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34878. * @return {string} The native code section.
  34879. */
  34880. getCodes( shaderStage ) {
  34881. const codes = this.codes[ shaderStage ];
  34882. let code = '';
  34883. if ( codes !== undefined ) {
  34884. for ( const nodeCode of codes ) {
  34885. code += nodeCode.code + '\n';
  34886. }
  34887. }
  34888. return code;
  34889. }
  34890. /**
  34891. * Returns the hash of this node builder.
  34892. *
  34893. * @return {string} The hash.
  34894. */
  34895. getHash() {
  34896. return this.vertexShader + this.fragmentShader + this.computeShader;
  34897. }
  34898. /**
  34899. * Sets the current shader stage.
  34900. *
  34901. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  34902. */
  34903. setShaderStage( shaderStage ) {
  34904. this.shaderStage = shaderStage;
  34905. }
  34906. /**
  34907. * Returns the current shader stage.
  34908. *
  34909. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  34910. */
  34911. getShaderStage() {
  34912. return this.shaderStage;
  34913. }
  34914. /**
  34915. * Sets the current build stage.
  34916. *
  34917. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  34918. */
  34919. setBuildStage( buildStage ) {
  34920. this.buildStage = buildStage;
  34921. }
  34922. /**
  34923. * Returns the current build stage.
  34924. *
  34925. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  34926. */
  34927. getBuildStage() {
  34928. return this.buildStage;
  34929. }
  34930. /**
  34931. * Controls the code build of the shader stages.
  34932. *
  34933. * @abstract
  34934. */
  34935. buildCode() {
  34936. console.warn( 'Abstract function.' );
  34937. }
  34938. /**
  34939. * Returns the current sub-build layer.
  34940. *
  34941. * @return {SubBuildNode} The current sub-build layers.
  34942. */
  34943. get subBuild() {
  34944. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  34945. }
  34946. /**
  34947. * Adds a sub-build layer to the node builder.
  34948. *
  34949. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  34950. */
  34951. addSubBuild( subBuild ) {
  34952. this.subBuildLayers.push( subBuild );
  34953. }
  34954. /**
  34955. * Removes the last sub-build layer from the node builder.
  34956. *
  34957. * @return {SubBuildNode} The removed sub-build layer.
  34958. */
  34959. removeSubBuild() {
  34960. return this.subBuildLayers.pop();
  34961. }
  34962. /**
  34963. * Returns the closest sub-build layer for the given data.
  34964. *
  34965. * @param {Node|Set|Array} data - The data to get the closest sub-build layer from.
  34966. * @return {?string} The closest sub-build name or null if none found.
  34967. */
  34968. getClosestSubBuild( data ) {
  34969. let subBuilds;
  34970. if ( data && data.isNode ) {
  34971. if ( data.isShaderCallNodeInternal ) {
  34972. subBuilds = data.shaderNode.subBuilds;
  34973. } else if ( data.isStackNode ) {
  34974. subBuilds = [ data.subBuild ];
  34975. } else {
  34976. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  34977. }
  34978. } else if ( data instanceof Set ) {
  34979. subBuilds = [ ...data ];
  34980. } else {
  34981. subBuilds = data;
  34982. }
  34983. if ( ! subBuilds ) return null;
  34984. const subBuildLayers = this.subBuildLayers;
  34985. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  34986. const subBuild = subBuilds[ i ];
  34987. if ( subBuildLayers.includes( subBuild ) ) {
  34988. return subBuild;
  34989. }
  34990. }
  34991. return null;
  34992. }
  34993. /**
  34994. * Returns the output node of a sub-build layer.
  34995. *
  34996. * @param {Node} node - The node to get the output from.
  34997. * @return {string} The output node name.
  34998. */
  34999. getSubBuildOutput( node ) {
  35000. return this.getSubBuildProperty( 'outputNode', node );
  35001. }
  35002. /**
  35003. * Returns the sub-build property name for the given property and node.
  35004. *
  35005. * @param {string} [property=''] - The property name.
  35006. * @param {?Node} [node=null] - The node to get the sub-build from.
  35007. * @return {string} The sub-build property name.
  35008. */
  35009. getSubBuildProperty( property = '', node = null ) {
  35010. let subBuild;
  35011. if ( node !== null ) {
  35012. subBuild = this.getClosestSubBuild( node );
  35013. } else {
  35014. subBuild = this.subBuildFn;
  35015. }
  35016. let result;
  35017. if ( subBuild ) {
  35018. result = property ? ( subBuild + '_' + property ) : subBuild;
  35019. } else {
  35020. result = property;
  35021. }
  35022. return result;
  35023. }
  35024. /**
  35025. * Central build method which controls the build for the given object.
  35026. *
  35027. * @return {NodeBuilder} A reference to this node builder.
  35028. */
  35029. build() {
  35030. const { object, material, renderer } = this;
  35031. if ( material !== null ) {
  35032. let nodeMaterial = renderer.library.fromMaterial( material );
  35033. if ( nodeMaterial === null ) {
  35034. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  35035. nodeMaterial = new NodeMaterial();
  35036. }
  35037. nodeMaterial.build( this );
  35038. } else {
  35039. this.addFlow( 'compute', object );
  35040. }
  35041. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  35042. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  35043. // generate() -> stage 3: generate shader
  35044. for ( const buildStage of defaultBuildStages ) {
  35045. this.setBuildStage( buildStage );
  35046. if ( this.context.vertex && this.context.vertex.isNode ) {
  35047. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  35048. }
  35049. for ( const shaderStage of shaderStages ) {
  35050. this.setShaderStage( shaderStage );
  35051. const flowNodes = this.flowNodes[ shaderStage ];
  35052. for ( const node of flowNodes ) {
  35053. if ( buildStage === 'generate' ) {
  35054. this.flowNode( node );
  35055. } else {
  35056. node.build( this );
  35057. }
  35058. }
  35059. }
  35060. }
  35061. this.setBuildStage( null );
  35062. this.setShaderStage( null );
  35063. // stage 4: build code for a specific output
  35064. this.buildCode();
  35065. this.buildUpdateNodes();
  35066. return this;
  35067. }
  35068. /**
  35069. * Returns a uniform representation which is later used for UBO generation and rendering.
  35070. *
  35071. * @param {NodeUniform} uniformNode - The uniform node.
  35072. * @param {string} type - The requested type.
  35073. * @return {Uniform} The uniform.
  35074. */
  35075. getNodeUniform( uniformNode, type ) {
  35076. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  35077. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  35078. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  35079. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  35080. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  35081. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  35082. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  35083. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  35084. throw new Error( `Uniform "${type}" not declared.` );
  35085. }
  35086. /**
  35087. * Formats the given shader snippet from a given type into another one. E.g.
  35088. * this method might be used to convert a simple float string `"1.0"` into a
  35089. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  35090. *
  35091. * @param {string} snippet - The shader snippet.
  35092. * @param {string} fromType - The source type.
  35093. * @param {string} toType - The target type.
  35094. * @return {string} The updated shader string.
  35095. */
  35096. format( snippet, fromType, toType ) {
  35097. fromType = this.getVectorType( fromType );
  35098. toType = this.getVectorType( toType );
  35099. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  35100. return snippet;
  35101. }
  35102. const fromTypeLength = this.getTypeLength( fromType );
  35103. const toTypeLength = this.getTypeLength( toType );
  35104. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  35105. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  35106. }
  35107. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  35108. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  35109. }
  35110. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  35111. // @TODO: ignore for now
  35112. return snippet;
  35113. }
  35114. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  35115. // @TODO: ignore for now
  35116. return snippet;
  35117. }
  35118. if ( fromTypeLength === toTypeLength ) {
  35119. return `${ this.getType( toType ) }( ${ snippet } )`;
  35120. }
  35121. if ( fromTypeLength > toTypeLength ) {
  35122. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  35123. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  35124. }
  35125. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  35126. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  35127. }
  35128. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  35129. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  35130. }
  35131. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  35132. // convert a number value to vector type, e.g:
  35133. // vec3( 1u ) -> vec3( float( 1u ) )
  35134. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  35135. }
  35136. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  35137. }
  35138. /**
  35139. * Returns a signature with the engine's current revision.
  35140. *
  35141. * @return {string} The signature.
  35142. */
  35143. getSignature() {
  35144. return `// Three.js r${ REVISION } - Node System\n`;
  35145. }
  35146. }
  35147. /**
  35148. * Management class for updating nodes. The module tracks metrics like
  35149. * the elapsed time, delta time, the render and frame ID to correctly
  35150. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  35151. * and {@link Node#updateAfter} depending on the node's configuration.
  35152. */
  35153. class NodeFrame {
  35154. /**
  35155. * Constructs a new node fame.
  35156. */
  35157. constructor() {
  35158. /**
  35159. * The elapsed time in seconds.
  35160. *
  35161. * @type {number}
  35162. * @default 0
  35163. */
  35164. this.time = 0;
  35165. /**
  35166. * The delta time in seconds.
  35167. *
  35168. * @type {number}
  35169. * @default 0
  35170. */
  35171. this.deltaTime = 0;
  35172. /**
  35173. * The frame ID.
  35174. *
  35175. * @type {number}
  35176. * @default 0
  35177. */
  35178. this.frameId = 0;
  35179. /**
  35180. * The render ID.
  35181. *
  35182. * @type {number}
  35183. * @default 0
  35184. */
  35185. this.renderId = 0;
  35186. /**
  35187. * Used to control the {@link Node#update} call.
  35188. *
  35189. * @type {WeakMap<Node, Object>}
  35190. */
  35191. this.updateMap = new WeakMap();
  35192. /**
  35193. * Used to control the {@link Node#updateBefore} call.
  35194. *
  35195. * @type {WeakMap<Node, Object>}
  35196. */
  35197. this.updateBeforeMap = new WeakMap();
  35198. /**
  35199. * Used to control the {@link Node#updateAfter} call.
  35200. *
  35201. * @type {WeakMap<Node, Object>}
  35202. */
  35203. this.updateAfterMap = new WeakMap();
  35204. /**
  35205. * A reference to the current renderer.
  35206. *
  35207. * @type {?Renderer}
  35208. * @default null
  35209. */
  35210. this.renderer = null;
  35211. /**
  35212. * A reference to the current material.
  35213. *
  35214. * @type {?Material}
  35215. * @default null
  35216. */
  35217. this.material = null;
  35218. /**
  35219. * A reference to the current camera.
  35220. *
  35221. * @type {?Camera}
  35222. * @default null
  35223. */
  35224. this.camera = null;
  35225. /**
  35226. * A reference to the current 3D object.
  35227. *
  35228. * @type {?Object3D}
  35229. * @default null
  35230. */
  35231. this.object = null;
  35232. /**
  35233. * A reference to the current scene.
  35234. *
  35235. * @type {?Scene}
  35236. * @default null
  35237. */
  35238. this.scene = null;
  35239. }
  35240. /**
  35241. * Returns a dictionary for a given node and update map which
  35242. * is used to correctly call node update methods per frame or render.
  35243. *
  35244. * @private
  35245. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  35246. * @param {Node} nodeRef - The reference to the current node.
  35247. * @return {Object<string,WeakMap>} The dictionary.
  35248. */
  35249. _getMaps( referenceMap, nodeRef ) {
  35250. let maps = referenceMap.get( nodeRef );
  35251. if ( maps === undefined ) {
  35252. maps = {
  35253. renderMap: new WeakMap(),
  35254. frameMap: new WeakMap()
  35255. };
  35256. referenceMap.set( nodeRef, maps );
  35257. }
  35258. return maps;
  35259. }
  35260. /**
  35261. * This method executes the {@link Node#updateBefore} for the given node.
  35262. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  35263. * is only executed once per frame, render or object depending on the update
  35264. * type.
  35265. *
  35266. * @param {Node} node - The node that should be updated.
  35267. */
  35268. updateBeforeNode( node ) {
  35269. const updateType = node.getUpdateBeforeType();
  35270. const reference = node.updateReference( this );
  35271. if ( updateType === NodeUpdateType.FRAME ) {
  35272. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  35273. if ( frameMap.get( reference ) !== this.frameId ) {
  35274. if ( node.updateBefore( this ) !== false ) {
  35275. frameMap.set( reference, this.frameId );
  35276. }
  35277. }
  35278. } else if ( updateType === NodeUpdateType.RENDER ) {
  35279. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  35280. if ( renderMap.get( reference ) !== this.renderId ) {
  35281. if ( node.updateBefore( this ) !== false ) {
  35282. renderMap.set( reference, this.renderId );
  35283. }
  35284. }
  35285. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35286. node.updateBefore( this );
  35287. }
  35288. }
  35289. /**
  35290. * This method executes the {@link Node#updateAfter} for the given node.
  35291. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  35292. * is only executed once per frame, render or object depending on the update
  35293. * type.
  35294. *
  35295. * @param {Node} node - The node that should be updated.
  35296. */
  35297. updateAfterNode( node ) {
  35298. const updateType = node.getUpdateAfterType();
  35299. const reference = node.updateReference( this );
  35300. if ( updateType === NodeUpdateType.FRAME ) {
  35301. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  35302. if ( frameMap.get( reference ) !== this.frameId ) {
  35303. if ( node.updateAfter( this ) !== false ) {
  35304. frameMap.set( reference, this.frameId );
  35305. }
  35306. }
  35307. } else if ( updateType === NodeUpdateType.RENDER ) {
  35308. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  35309. if ( renderMap.get( reference ) !== this.renderId ) {
  35310. if ( node.updateAfter( this ) !== false ) {
  35311. renderMap.set( reference, this.renderId );
  35312. }
  35313. }
  35314. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35315. node.updateAfter( this );
  35316. }
  35317. }
  35318. /**
  35319. * This method executes the {@link Node#update} for the given node.
  35320. * It makes sure {@link Node#updateType} is honored meaning the update
  35321. * is only executed once per frame, render or object depending on the update
  35322. * type.
  35323. *
  35324. * @param {Node} node - The node that should be updated.
  35325. */
  35326. updateNode( node ) {
  35327. const updateType = node.getUpdateType();
  35328. const reference = node.updateReference( this );
  35329. if ( updateType === NodeUpdateType.FRAME ) {
  35330. const { frameMap } = this._getMaps( this.updateMap, reference );
  35331. if ( frameMap.get( reference ) !== this.frameId ) {
  35332. if ( node.update( this ) !== false ) {
  35333. frameMap.set( reference, this.frameId );
  35334. }
  35335. }
  35336. } else if ( updateType === NodeUpdateType.RENDER ) {
  35337. const { renderMap } = this._getMaps( this.updateMap, reference );
  35338. if ( renderMap.get( reference ) !== this.renderId ) {
  35339. if ( node.update( this ) !== false ) {
  35340. renderMap.set( reference, this.renderId );
  35341. }
  35342. }
  35343. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35344. node.update( this );
  35345. }
  35346. }
  35347. /**
  35348. * Updates the internal state of the node frame. This method is
  35349. * called by the renderer in its internal animation loop.
  35350. */
  35351. update() {
  35352. this.frameId ++;
  35353. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  35354. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  35355. this.lastTime = performance.now();
  35356. this.time += this.deltaTime;
  35357. }
  35358. }
  35359. /**
  35360. * Describes the input of a {@link NodeFunction}.
  35361. */
  35362. class NodeFunctionInput {
  35363. /**
  35364. * Constructs a new node function input.
  35365. *
  35366. * @param {string} type - The input type.
  35367. * @param {string} name - The input name.
  35368. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  35369. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  35370. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  35371. */
  35372. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  35373. /**
  35374. * The input type.
  35375. *
  35376. * @type {string}
  35377. */
  35378. this.type = type;
  35379. /**
  35380. * The input name.
  35381. *
  35382. * @type {string}
  35383. */
  35384. this.name = name;
  35385. /**
  35386. * If the input is an Array, count will be the length.
  35387. *
  35388. * @type {?number}
  35389. * @default null
  35390. */
  35391. this.count = count;
  35392. /**
  35393. *The parameter qualifier (only relevant for GLSL).
  35394. *
  35395. * @type {('in'|'out'|'inout')}
  35396. * @default ''
  35397. */
  35398. this.qualifier = qualifier;
  35399. /**
  35400. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  35401. *
  35402. * @type {boolean}
  35403. * @default false
  35404. */
  35405. this.isConst = isConst;
  35406. }
  35407. }
  35408. NodeFunctionInput.isNodeFunctionInput = true;
  35409. /**
  35410. * Module for representing directional lights as nodes.
  35411. *
  35412. * @augments AnalyticLightNode
  35413. */
  35414. class DirectionalLightNode extends AnalyticLightNode {
  35415. static get type() {
  35416. return 'DirectionalLightNode';
  35417. }
  35418. /**
  35419. * Constructs a new directional light node.
  35420. *
  35421. * @param {?DirectionalLight} [light=null] - The directional light source.
  35422. */
  35423. constructor( light = null ) {
  35424. super( light );
  35425. }
  35426. setupDirect() {
  35427. const lightColor = this.colorNode;
  35428. const lightDirection = lightTargetDirection( this.light );
  35429. return { lightDirection, lightColor };
  35430. }
  35431. }
  35432. const _matrix41 = /*@__PURE__*/ new Matrix4();
  35433. const _matrix42 = /*@__PURE__*/ new Matrix4();
  35434. let _ltcLib = null;
  35435. /**
  35436. * Module for representing rect area lights as nodes.
  35437. *
  35438. * @augments AnalyticLightNode
  35439. */
  35440. class RectAreaLightNode extends AnalyticLightNode {
  35441. static get type() {
  35442. return 'RectAreaLightNode';
  35443. }
  35444. /**
  35445. * Constructs a new rect area light node.
  35446. *
  35447. * @param {?RectAreaLight} [light=null] - The rect area light source.
  35448. */
  35449. constructor( light = null ) {
  35450. super( light );
  35451. /**
  35452. * Uniform node representing the half height of the are light.
  35453. *
  35454. * @type {UniformNode<vec3>}
  35455. */
  35456. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  35457. /**
  35458. * Uniform node representing the half width of the are light.
  35459. *
  35460. * @type {UniformNode<vec3>}
  35461. */
  35462. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  35463. /**
  35464. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  35465. * relies on `viewMatrix` which might vary per render call.
  35466. *
  35467. * @type {string}
  35468. * @default 'render'
  35469. */
  35470. this.updateType = NodeUpdateType.RENDER;
  35471. }
  35472. /**
  35473. * Overwritten to updated rect area light specific uniforms.
  35474. *
  35475. * @param {NodeFrame} frame - A reference to the current node frame.
  35476. */
  35477. update( frame ) {
  35478. super.update( frame );
  35479. const { light } = this;
  35480. const viewMatrix = frame.camera.matrixWorldInverse;
  35481. _matrix42.identity();
  35482. _matrix41.copy( light.matrixWorld );
  35483. _matrix41.premultiply( viewMatrix );
  35484. _matrix42.extractRotation( _matrix41 );
  35485. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  35486. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  35487. this.halfWidth.value.applyMatrix4( _matrix42 );
  35488. this.halfHeight.value.applyMatrix4( _matrix42 );
  35489. }
  35490. setupDirectRectArea( builder ) {
  35491. let ltc_1, ltc_2;
  35492. if ( builder.isAvailable( 'float32Filterable' ) ) {
  35493. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  35494. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  35495. } else {
  35496. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  35497. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  35498. }
  35499. const { colorNode, light } = this;
  35500. const lightPosition = lightViewPosition( light );
  35501. return {
  35502. lightColor: colorNode,
  35503. lightPosition,
  35504. halfWidth: this.halfWidth,
  35505. halfHeight: this.halfHeight,
  35506. ltc_1,
  35507. ltc_2
  35508. };
  35509. }
  35510. /**
  35511. * Used to configure the internal BRDF approximation texture data.
  35512. *
  35513. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  35514. */
  35515. static setLTC( ltc ) {
  35516. _ltcLib = ltc;
  35517. }
  35518. }
  35519. /**
  35520. * Module for representing spot lights as nodes.
  35521. *
  35522. * @augments AnalyticLightNode
  35523. */
  35524. class SpotLightNode extends AnalyticLightNode {
  35525. static get type() {
  35526. return 'SpotLightNode';
  35527. }
  35528. /**
  35529. * Constructs a new spot light node.
  35530. *
  35531. * @param {?SpotLight} [light=null] - The spot light source.
  35532. */
  35533. constructor( light = null ) {
  35534. super( light );
  35535. /**
  35536. * Uniform node representing the cone cosine.
  35537. *
  35538. * @type {UniformNode<float>}
  35539. */
  35540. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  35541. /**
  35542. * Uniform node representing the penumbra cosine.
  35543. *
  35544. * @type {UniformNode<float>}
  35545. */
  35546. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  35547. /**
  35548. * Uniform node representing the cutoff distance.
  35549. *
  35550. * @type {UniformNode<float>}
  35551. */
  35552. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  35553. /**
  35554. * Uniform node representing the decay exponent.
  35555. *
  35556. * @type {UniformNode<float>}
  35557. */
  35558. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  35559. /**
  35560. * Uniform node representing the light color.
  35561. *
  35562. * @type {UniformNode<Color>}
  35563. */
  35564. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  35565. }
  35566. /**
  35567. * Overwritten to updated spot light specific uniforms.
  35568. *
  35569. * @param {NodeFrame} frame - A reference to the current node frame.
  35570. */
  35571. update( frame ) {
  35572. super.update( frame );
  35573. const { light } = this;
  35574. this.coneCosNode.value = Math.cos( light.angle );
  35575. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  35576. this.cutoffDistanceNode.value = light.distance;
  35577. this.decayExponentNode.value = light.decay;
  35578. }
  35579. /**
  35580. * Computes the spot attenuation for the given angle.
  35581. *
  35582. * @param {NodeBuilder} builder - The node builder.
  35583. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  35584. * @return {Node<float>} The spot attenuation.
  35585. */
  35586. getSpotAttenuation( builder, angleCosine ) {
  35587. const { coneCosNode, penumbraCosNode } = this;
  35588. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  35589. }
  35590. getLightCoord( builder ) {
  35591. const properties = builder.getNodeProperties( this );
  35592. let projectionUV = properties.projectionUV;
  35593. if ( projectionUV === undefined ) {
  35594. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  35595. properties.projectionUV = projectionUV;
  35596. }
  35597. return projectionUV;
  35598. }
  35599. setupDirect( builder ) {
  35600. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  35601. const lightVector = this.getLightVector( builder );
  35602. const lightDirection = lightVector.normalize();
  35603. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  35604. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  35605. const lightDistance = lightVector.length();
  35606. const lightAttenuation = getDistanceAttenuation( {
  35607. lightDistance,
  35608. cutoffDistance: cutoffDistanceNode,
  35609. decayExponent: decayExponentNode
  35610. } );
  35611. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  35612. let projected, lightCoord;
  35613. if ( light.colorNode ) {
  35614. lightCoord = this.getLightCoord( builder );
  35615. projected = light.colorNode( lightCoord );
  35616. } else if ( light.map ) {
  35617. lightCoord = this.getLightCoord( builder );
  35618. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  35619. }
  35620. if ( projected ) {
  35621. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  35622. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  35623. }
  35624. return { lightColor, lightDirection };
  35625. }
  35626. }
  35627. /**
  35628. * An IES version of the default spot light node.
  35629. *
  35630. * @augments SpotLightNode
  35631. */
  35632. class IESSpotLightNode extends SpotLightNode {
  35633. static get type() {
  35634. return 'IESSpotLightNode';
  35635. }
  35636. /**
  35637. * Overwrites the default implementation to compute an IES conform spot attenuation.
  35638. *
  35639. * @param {NodeBuilder} builder - The node builder.
  35640. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  35641. * @return {Node<float>} The spot attenuation.
  35642. */
  35643. getSpotAttenuation( builder, angleCosine ) {
  35644. const iesMap = this.light.iesMap;
  35645. let spotAttenuation = null;
  35646. if ( iesMap && iesMap.isTexture === true ) {
  35647. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  35648. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  35649. } else {
  35650. spotAttenuation = super.getSpotAttenuation( angleCosine );
  35651. }
  35652. return spotAttenuation;
  35653. }
  35654. }
  35655. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  35656. const d = p.abs().sub( b );
  35657. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  35658. } );
  35659. /**
  35660. * An implementation of a projector light node.
  35661. *
  35662. * @augments SpotLightNode
  35663. */
  35664. class ProjectorLightNode extends SpotLightNode {
  35665. static get type() {
  35666. return 'ProjectorLightNode';
  35667. }
  35668. update( frame ) {
  35669. super.update( frame );
  35670. const light = this.light;
  35671. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  35672. if ( light.aspect === null ) {
  35673. let aspect = 1;
  35674. if ( light.map !== null ) {
  35675. aspect = light.map.width / light.map.height;
  35676. }
  35677. light.shadow.aspect = aspect;
  35678. } else {
  35679. light.shadow.aspect = light.aspect;
  35680. }
  35681. }
  35682. /**
  35683. * Overwrites the default implementation to compute projection attenuation.
  35684. *
  35685. * @param {NodeBuilder} builder - The node builder.
  35686. * @return {Node<float>} The spot attenuation.
  35687. */
  35688. getSpotAttenuation( builder ) {
  35689. const attenuation = float( 0 );
  35690. const penumbraCos = this.penumbraCosNode;
  35691. // compute the fragment's position in the light's clip space
  35692. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  35693. // the sign of w determines whether the current fragment is in front or behind the light.
  35694. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  35695. If( spotLightCoord.w.greaterThan( 0 ), () => {
  35696. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  35697. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  35698. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  35699. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  35700. } );
  35701. return attenuation;
  35702. }
  35703. }
  35704. /**
  35705. * Module for representing ambient lights as nodes.
  35706. *
  35707. * @augments AnalyticLightNode
  35708. */
  35709. class AmbientLightNode extends AnalyticLightNode {
  35710. static get type() {
  35711. return 'AmbientLightNode';
  35712. }
  35713. /**
  35714. * Constructs a new ambient light node.
  35715. *
  35716. * @param {?AmbientLight} [light=null] - The ambient light source.
  35717. */
  35718. constructor( light = null ) {
  35719. super( light );
  35720. }
  35721. setup( { context } ) {
  35722. context.irradiance.addAssign( this.colorNode );
  35723. }
  35724. }
  35725. /**
  35726. * Module for representing hemisphere lights as nodes.
  35727. *
  35728. * @augments AnalyticLightNode
  35729. */
  35730. class HemisphereLightNode extends AnalyticLightNode {
  35731. static get type() {
  35732. return 'HemisphereLightNode';
  35733. }
  35734. /**
  35735. * Constructs a new hemisphere light node.
  35736. *
  35737. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  35738. */
  35739. constructor( light = null ) {
  35740. super( light );
  35741. /**
  35742. * Uniform node representing the light's position.
  35743. *
  35744. * @type {UniformNode<vec3>}
  35745. */
  35746. this.lightPositionNode = lightPosition( light );
  35747. /**
  35748. * A node representing the light's direction.
  35749. *
  35750. * @type {Node<vec3>}
  35751. */
  35752. this.lightDirectionNode = this.lightPositionNode.normalize();
  35753. /**
  35754. * Uniform node representing the light's ground color.
  35755. *
  35756. * @type {UniformNode<vec3>}
  35757. */
  35758. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  35759. }
  35760. /**
  35761. * Overwritten to updated hemisphere light specific uniforms.
  35762. *
  35763. * @param {NodeFrame} frame - A reference to the current node frame.
  35764. */
  35765. update( frame ) {
  35766. const { light } = this;
  35767. super.update( frame );
  35768. this.lightPositionNode.object3d = light;
  35769. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  35770. }
  35771. setup( builder ) {
  35772. const { colorNode, groundColorNode, lightDirectionNode } = this;
  35773. const dotNL = normalWorld.dot( lightDirectionNode );
  35774. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  35775. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  35776. builder.context.irradiance.addAssign( irradiance );
  35777. }
  35778. }
  35779. /**
  35780. * Module for representing light probes as nodes.
  35781. *
  35782. * @augments AnalyticLightNode
  35783. */
  35784. class LightProbeNode extends AnalyticLightNode {
  35785. static get type() {
  35786. return 'LightProbeNode';
  35787. }
  35788. /**
  35789. * Constructs a new light probe node.
  35790. *
  35791. * @param {?LightProbe} [light=null] - The light probe.
  35792. */
  35793. constructor( light = null ) {
  35794. super( light );
  35795. const array = [];
  35796. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  35797. /**
  35798. * Light probe represented as a uniform of spherical harmonics.
  35799. *
  35800. * @type {UniformArrayNode}
  35801. */
  35802. this.lightProbe = uniformArray( array );
  35803. }
  35804. /**
  35805. * Overwritten to updated light probe specific uniforms.
  35806. *
  35807. * @param {NodeFrame} frame - A reference to the current node frame.
  35808. */
  35809. update( frame ) {
  35810. const { light } = this;
  35811. super.update( frame );
  35812. //
  35813. for ( let i = 0; i < 9; i ++ ) {
  35814. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  35815. }
  35816. }
  35817. setup( builder ) {
  35818. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  35819. builder.context.irradiance.addAssign( irradiance );
  35820. }
  35821. }
  35822. /**
  35823. * Base class for node parsers. A derived parser must be implemented
  35824. * for each supported native shader language.
  35825. */
  35826. class NodeParser {
  35827. /**
  35828. * The method parses the given native code an returns a node function.
  35829. *
  35830. * @abstract
  35831. * @param {string} source - The native shader code.
  35832. * @return {NodeFunction} A node function.
  35833. */
  35834. parseFunction( /*source*/ ) {
  35835. console.warn( 'Abstract function.' );
  35836. }
  35837. }
  35838. /**
  35839. * Base class for node functions. A derived module must be implemented
  35840. * for each supported native shader language. Similar to other `Node*` modules,
  35841. * this class is only relevant during the building process and not used
  35842. * in user-level code.
  35843. */
  35844. class NodeFunction {
  35845. /**
  35846. * Constructs a new node function.
  35847. *
  35848. * @param {string} type - The node type. This type is the return type of the node function.
  35849. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  35850. * @param {string} [name=''] - The function's name.
  35851. * @param {string} [precision=''] - The precision qualifier.
  35852. */
  35853. constructor( type, inputs, name = '', precision = '' ) {
  35854. /**
  35855. * The node type. This type is the return type of the node function.
  35856. *
  35857. * @type {string}
  35858. */
  35859. this.type = type;
  35860. /**
  35861. * The function's inputs.
  35862. *
  35863. * @type {Array<NodeFunctionInput>}
  35864. */
  35865. this.inputs = inputs;
  35866. /**
  35867. * The name of the uniform.
  35868. *
  35869. * @type {string}
  35870. * @default ''
  35871. */
  35872. this.name = name;
  35873. /**
  35874. * The precision qualifier.
  35875. *
  35876. * @type {string}
  35877. * @default ''
  35878. */
  35879. this.precision = precision;
  35880. }
  35881. /**
  35882. * This method returns the native code of the node function.
  35883. *
  35884. * @abstract
  35885. * @param {string} name - The function's name.
  35886. * @return {string} A shader code.
  35887. */
  35888. getCode( /*name = this.name*/ ) {
  35889. console.warn( 'Abstract function.' );
  35890. }
  35891. }
  35892. NodeFunction.isNodeFunction = true;
  35893. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  35894. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  35895. const pragmaMain = '#pragma main';
  35896. const parse$1 = ( source ) => {
  35897. source = source.trim();
  35898. const pragmaMainIndex = source.indexOf( pragmaMain );
  35899. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  35900. const declaration = mainCode.match( declarationRegexp$1 );
  35901. if ( declaration !== null && declaration.length === 5 ) {
  35902. // tokenizer
  35903. const inputsCode = declaration[ 4 ];
  35904. const propsMatches = [];
  35905. let nameMatch = null;
  35906. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  35907. propsMatches.push( nameMatch );
  35908. }
  35909. // parser
  35910. const inputs = [];
  35911. let i = 0;
  35912. while ( i < propsMatches.length ) {
  35913. const isConst = propsMatches[ i ][ 0 ] === 'const';
  35914. if ( isConst === true ) {
  35915. i ++;
  35916. }
  35917. let qualifier = propsMatches[ i ][ 0 ];
  35918. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  35919. i ++;
  35920. } else {
  35921. qualifier = '';
  35922. }
  35923. const type = propsMatches[ i ++ ][ 0 ];
  35924. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  35925. if ( Number.isNaN( count ) === false ) i ++;
  35926. else count = null;
  35927. const name = propsMatches[ i ++ ][ 0 ];
  35928. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  35929. }
  35930. //
  35931. const blockCode = mainCode.substring( declaration[ 0 ].length );
  35932. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  35933. const type = declaration[ 2 ];
  35934. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  35935. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  35936. return {
  35937. type,
  35938. inputs,
  35939. name,
  35940. precision,
  35941. inputsCode,
  35942. blockCode,
  35943. headerCode
  35944. };
  35945. } else {
  35946. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  35947. }
  35948. };
  35949. /**
  35950. * This class represents a GLSL node function.
  35951. *
  35952. * @augments NodeFunction
  35953. */
  35954. class GLSLNodeFunction extends NodeFunction {
  35955. /**
  35956. * Constructs a new GLSL node function.
  35957. *
  35958. * @param {string} source - The GLSL source.
  35959. */
  35960. constructor( source ) {
  35961. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  35962. super( type, inputs, name, precision );
  35963. this.inputsCode = inputsCode;
  35964. this.blockCode = blockCode;
  35965. this.headerCode = headerCode;
  35966. }
  35967. /**
  35968. * This method returns the GLSL code of the node function.
  35969. *
  35970. * @param {string} [name=this.name] - The function's name.
  35971. * @return {string} The shader code.
  35972. */
  35973. getCode( name = this.name ) {
  35974. let code;
  35975. const blockCode = this.blockCode;
  35976. if ( blockCode !== '' ) {
  35977. const { type, inputsCode, headerCode, precision } = this;
  35978. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  35979. if ( precision !== '' ) {
  35980. declarationCode = `${ precision } ${ declarationCode }`;
  35981. }
  35982. code = headerCode + declarationCode + blockCode;
  35983. } else {
  35984. // interface function
  35985. code = '';
  35986. }
  35987. return code;
  35988. }
  35989. }
  35990. /**
  35991. * A GLSL node parser.
  35992. *
  35993. * @augments NodeParser
  35994. */
  35995. class GLSLNodeParser extends NodeParser {
  35996. /**
  35997. * The method parses the given GLSL code an returns a node function.
  35998. *
  35999. * @param {string} source - The GLSL code.
  36000. * @return {GLSLNodeFunction} A node function.
  36001. */
  36002. parseFunction( source ) {
  36003. return new GLSLNodeFunction( source );
  36004. }
  36005. }
  36006. const _outputNodeMap = new WeakMap();
  36007. const _chainKeys$2 = [];
  36008. const _cacheKeyValues = [];
  36009. /**
  36010. * This renderer module manages node-related objects and is the
  36011. * primary interface between the renderer and the node system.
  36012. *
  36013. * @private
  36014. * @augments DataMap
  36015. */
  36016. class Nodes extends DataMap {
  36017. /**
  36018. * Constructs a new nodes management component.
  36019. *
  36020. * @param {Renderer} renderer - The renderer.
  36021. * @param {Backend} backend - The renderer's backend.
  36022. */
  36023. constructor( renderer, backend ) {
  36024. super();
  36025. /**
  36026. * The renderer.
  36027. *
  36028. * @type {Renderer}
  36029. */
  36030. this.renderer = renderer;
  36031. /**
  36032. * The renderer's backend.
  36033. *
  36034. * @type {Backend}
  36035. */
  36036. this.backend = backend;
  36037. /**
  36038. * The node frame.
  36039. *
  36040. * @type {Renderer}
  36041. */
  36042. this.nodeFrame = new NodeFrame();
  36043. /**
  36044. * A cache for managing node builder states.
  36045. *
  36046. * @type {Map<number,NodeBuilderState>}
  36047. */
  36048. this.nodeBuilderCache = new Map();
  36049. /**
  36050. * A cache for managing data cache key data.
  36051. *
  36052. * @type {ChainMap}
  36053. */
  36054. this.callHashCache = new ChainMap();
  36055. /**
  36056. * A cache for managing node uniforms group data.
  36057. *
  36058. * @type {ChainMap}
  36059. */
  36060. this.groupsData = new ChainMap();
  36061. /**
  36062. * A cache for managing node objects of
  36063. * scene properties like fog or environments.
  36064. *
  36065. * @type {Object<string,WeakMap>}
  36066. */
  36067. this.cacheLib = {};
  36068. }
  36069. /**
  36070. * Returns `true` if the given node uniforms group must be updated or not.
  36071. *
  36072. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  36073. * @return {boolean} Whether the node uniforms group requires an update or not.
  36074. */
  36075. updateGroup( nodeUniformsGroup ) {
  36076. const groupNode = nodeUniformsGroup.groupNode;
  36077. const name = groupNode.name;
  36078. // objectGroup is always updated
  36079. if ( name === objectGroup.name ) return true;
  36080. // renderGroup is updated once per render/compute call
  36081. if ( name === renderGroup.name ) {
  36082. const uniformsGroupData = this.get( nodeUniformsGroup );
  36083. const renderId = this.nodeFrame.renderId;
  36084. if ( uniformsGroupData.renderId !== renderId ) {
  36085. uniformsGroupData.renderId = renderId;
  36086. return true;
  36087. }
  36088. return false;
  36089. }
  36090. // frameGroup is updated once per frame
  36091. if ( name === frameGroup.name ) {
  36092. const uniformsGroupData = this.get( nodeUniformsGroup );
  36093. const frameId = this.nodeFrame.frameId;
  36094. if ( uniformsGroupData.frameId !== frameId ) {
  36095. uniformsGroupData.frameId = frameId;
  36096. return true;
  36097. }
  36098. return false;
  36099. }
  36100. // other groups are updated just when groupNode.needsUpdate is true
  36101. _chainKeys$2[ 0 ] = groupNode;
  36102. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  36103. let groupData = this.groupsData.get( _chainKeys$2 );
  36104. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  36105. _chainKeys$2.length = 0;
  36106. if ( groupData.version !== groupNode.version ) {
  36107. groupData.version = groupNode.version;
  36108. return true;
  36109. }
  36110. return false;
  36111. }
  36112. /**
  36113. * Returns the cache key for the given render object.
  36114. *
  36115. * @param {RenderObject} renderObject - The render object.
  36116. * @return {number} The cache key.
  36117. */
  36118. getForRenderCacheKey( renderObject ) {
  36119. return renderObject.initialCacheKey;
  36120. }
  36121. /**
  36122. * Returns a node builder state for the given render object.
  36123. *
  36124. * @param {RenderObject} renderObject - The render object.
  36125. * @return {NodeBuilderState} The node builder state.
  36126. */
  36127. getForRender( renderObject ) {
  36128. const renderObjectData = this.get( renderObject );
  36129. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36130. if ( nodeBuilderState === undefined ) {
  36131. const { nodeBuilderCache } = this;
  36132. const cacheKey = this.getForRenderCacheKey( renderObject );
  36133. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36134. if ( nodeBuilderState === undefined ) {
  36135. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36136. nodeBuilder.scene = renderObject.scene;
  36137. nodeBuilder.material = renderObject.material;
  36138. nodeBuilder.camera = renderObject.camera;
  36139. nodeBuilder.context.material = renderObject.material;
  36140. nodeBuilder.lightsNode = renderObject.lightsNode;
  36141. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36142. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36143. nodeBuilder.clippingContext = renderObject.clippingContext;
  36144. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  36145. nodeBuilder.enableMultiview();
  36146. }
  36147. nodeBuilder.build();
  36148. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36149. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  36150. }
  36151. nodeBuilderState.usedTimes ++;
  36152. renderObjectData.nodeBuilderState = nodeBuilderState;
  36153. }
  36154. return nodeBuilderState;
  36155. }
  36156. /**
  36157. * Deletes the given object from the internal data map
  36158. *
  36159. * @param {any} object - The object to delete.
  36160. * @return {?Object} The deleted dictionary.
  36161. */
  36162. delete( object ) {
  36163. if ( object.isRenderObject ) {
  36164. const nodeBuilderState = this.get( object ).nodeBuilderState;
  36165. nodeBuilderState.usedTimes --;
  36166. if ( nodeBuilderState.usedTimes === 0 ) {
  36167. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  36168. }
  36169. }
  36170. return super.delete( object );
  36171. }
  36172. /**
  36173. * Returns a node builder state for the given compute node.
  36174. *
  36175. * @param {Node} computeNode - The compute node.
  36176. * @return {NodeBuilderState} The node builder state.
  36177. */
  36178. getForCompute( computeNode ) {
  36179. const computeData = this.get( computeNode );
  36180. let nodeBuilderState = computeData.nodeBuilderState;
  36181. if ( nodeBuilderState === undefined ) {
  36182. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  36183. nodeBuilder.build();
  36184. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36185. computeData.nodeBuilderState = nodeBuilderState;
  36186. }
  36187. return nodeBuilderState;
  36188. }
  36189. /**
  36190. * Creates a node builder state for the given node builder.
  36191. *
  36192. * @private
  36193. * @param {NodeBuilder} nodeBuilder - The node builder.
  36194. * @return {NodeBuilderState} The node builder state.
  36195. */
  36196. _createNodeBuilderState( nodeBuilder ) {
  36197. return new NodeBuilderState(
  36198. nodeBuilder.vertexShader,
  36199. nodeBuilder.fragmentShader,
  36200. nodeBuilder.computeShader,
  36201. nodeBuilder.getAttributesArray(),
  36202. nodeBuilder.getBindings(),
  36203. nodeBuilder.updateNodes,
  36204. nodeBuilder.updateBeforeNodes,
  36205. nodeBuilder.updateAfterNodes,
  36206. nodeBuilder.observer,
  36207. nodeBuilder.transforms
  36208. );
  36209. }
  36210. /**
  36211. * Returns an environment node for the current configured
  36212. * scene environment.
  36213. *
  36214. * @param {Scene} scene - The scene.
  36215. * @return {Node} A node representing the current scene environment.
  36216. */
  36217. getEnvironmentNode( scene ) {
  36218. this.updateEnvironment( scene );
  36219. let environmentNode = null;
  36220. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  36221. environmentNode = scene.environmentNode;
  36222. } else {
  36223. const sceneData = this.get( scene );
  36224. if ( sceneData.environmentNode ) {
  36225. environmentNode = sceneData.environmentNode;
  36226. }
  36227. }
  36228. return environmentNode;
  36229. }
  36230. /**
  36231. * Returns a background node for the current configured
  36232. * scene background.
  36233. *
  36234. * @param {Scene} scene - The scene.
  36235. * @return {Node} A node representing the current scene background.
  36236. */
  36237. getBackgroundNode( scene ) {
  36238. this.updateBackground( scene );
  36239. let backgroundNode = null;
  36240. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  36241. backgroundNode = scene.backgroundNode;
  36242. } else {
  36243. const sceneData = this.get( scene );
  36244. if ( sceneData.backgroundNode ) {
  36245. backgroundNode = sceneData.backgroundNode;
  36246. }
  36247. }
  36248. return backgroundNode;
  36249. }
  36250. /**
  36251. * Returns a fog node for the current configured scene fog.
  36252. *
  36253. * @param {Scene} scene - The scene.
  36254. * @return {Node} A node representing the current scene fog.
  36255. */
  36256. getFogNode( scene ) {
  36257. this.updateFog( scene );
  36258. return scene.fogNode || this.get( scene ).fogNode || null;
  36259. }
  36260. /**
  36261. * Returns a cache key for the given scene and lights node.
  36262. * This key is used by `RenderObject` as a part of the dynamic
  36263. * cache key (a key that must be checked every time the render
  36264. * objects is drawn).
  36265. *
  36266. * @param {Scene} scene - The scene.
  36267. * @param {LightsNode} lightsNode - The lights node.
  36268. * @return {number} The cache key.
  36269. */
  36270. getCacheKey( scene, lightsNode ) {
  36271. _chainKeys$2[ 0 ] = scene;
  36272. _chainKeys$2[ 1 ] = lightsNode;
  36273. const callId = this.renderer.info.calls;
  36274. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  36275. if ( cacheKeyData.callId !== callId ) {
  36276. const environmentNode = this.getEnvironmentNode( scene );
  36277. const fogNode = this.getFogNode( scene );
  36278. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  36279. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  36280. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  36281. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  36282. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  36283. cacheKeyData.callId = callId;
  36284. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  36285. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  36286. _cacheKeyValues.length = 0;
  36287. }
  36288. _chainKeys$2.length = 0;
  36289. return cacheKeyData.cacheKey;
  36290. }
  36291. /**
  36292. * A boolean that indicates whether tone mapping should be enabled
  36293. * or not.
  36294. *
  36295. * @type {boolean}
  36296. */
  36297. get isToneMappingState() {
  36298. return this.renderer.getRenderTarget() ? false : true;
  36299. }
  36300. /**
  36301. * If a scene background is configured, this method makes sure to
  36302. * represent the background with a corresponding node-based implementation.
  36303. *
  36304. * @param {Scene} scene - The scene.
  36305. */
  36306. updateBackground( scene ) {
  36307. const sceneData = this.get( scene );
  36308. const background = scene.background;
  36309. if ( background ) {
  36310. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  36311. if ( sceneData.background !== background || forceUpdate ) {
  36312. const backgroundNode = this.getCacheNode( 'background', background, () => {
  36313. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  36314. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  36315. return pmremTexture( background );
  36316. } else {
  36317. let envMap;
  36318. if ( background.isCubeTexture === true ) {
  36319. envMap = cubeTexture( background );
  36320. } else {
  36321. envMap = texture( background );
  36322. }
  36323. return cubeMapNode( envMap );
  36324. }
  36325. } else if ( background.isTexture === true ) {
  36326. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  36327. } else if ( background.isColor !== true ) {
  36328. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  36329. }
  36330. }, forceUpdate );
  36331. sceneData.backgroundNode = backgroundNode;
  36332. sceneData.background = background;
  36333. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  36334. }
  36335. } else if ( sceneData.backgroundNode ) {
  36336. delete sceneData.backgroundNode;
  36337. delete sceneData.background;
  36338. }
  36339. }
  36340. /**
  36341. * This method is part of the caching of nodes which are used to represents the
  36342. * scene's background, fog or environment.
  36343. *
  36344. * @param {string} type - The type of object to cache.
  36345. * @param {Object} object - The object.
  36346. * @param {Function} callback - A callback that produces a node representation for the given object.
  36347. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  36348. * @return {Node} The node representation.
  36349. */
  36350. getCacheNode( type, object, callback, forceUpdate = false ) {
  36351. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  36352. let node = nodeCache.get( object );
  36353. if ( node === undefined || forceUpdate ) {
  36354. node = callback();
  36355. nodeCache.set( object, node );
  36356. }
  36357. return node;
  36358. }
  36359. /**
  36360. * If a scene fog is configured, this method makes sure to
  36361. * represent the fog with a corresponding node-based implementation.
  36362. *
  36363. * @param {Scene} scene - The scene.
  36364. */
  36365. updateFog( scene ) {
  36366. const sceneData = this.get( scene );
  36367. const sceneFog = scene.fog;
  36368. if ( sceneFog ) {
  36369. if ( sceneData.fog !== sceneFog ) {
  36370. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  36371. if ( sceneFog.isFogExp2 ) {
  36372. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36373. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  36374. return fog( color, densityFogFactor( density ) );
  36375. } else if ( sceneFog.isFog ) {
  36376. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36377. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  36378. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  36379. return fog( color, rangeFogFactor( near, far ) );
  36380. } else {
  36381. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  36382. }
  36383. } );
  36384. sceneData.fogNode = fogNode;
  36385. sceneData.fog = sceneFog;
  36386. }
  36387. } else {
  36388. delete sceneData.fogNode;
  36389. delete sceneData.fog;
  36390. }
  36391. }
  36392. /**
  36393. * If a scene environment is configured, this method makes sure to
  36394. * represent the environment with a corresponding node-based implementation.
  36395. *
  36396. * @param {Scene} scene - The scene.
  36397. */
  36398. updateEnvironment( scene ) {
  36399. const sceneData = this.get( scene );
  36400. const environment = scene.environment;
  36401. if ( environment ) {
  36402. if ( sceneData.environment !== environment ) {
  36403. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  36404. if ( environment.isCubeTexture === true ) {
  36405. return cubeTexture( environment );
  36406. } else if ( environment.isTexture === true ) {
  36407. return texture( environment );
  36408. } else {
  36409. console.error( 'Nodes: Unsupported environment configuration.', environment );
  36410. }
  36411. } );
  36412. sceneData.environmentNode = environmentNode;
  36413. sceneData.environment = environment;
  36414. }
  36415. } else if ( sceneData.environmentNode ) {
  36416. delete sceneData.environmentNode;
  36417. delete sceneData.environment;
  36418. }
  36419. }
  36420. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  36421. const nodeFrame = this.nodeFrame;
  36422. nodeFrame.renderer = renderer;
  36423. nodeFrame.scene = scene;
  36424. nodeFrame.object = object;
  36425. nodeFrame.camera = camera;
  36426. nodeFrame.material = material;
  36427. return nodeFrame;
  36428. }
  36429. getNodeFrameForRender( renderObject ) {
  36430. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  36431. }
  36432. /**
  36433. * Returns the current output cache key.
  36434. *
  36435. * @return {string} The output cache key.
  36436. */
  36437. getOutputCacheKey() {
  36438. const renderer = this.renderer;
  36439. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  36440. }
  36441. /**
  36442. * Checks if the output configuration (tone mapping and color space) for
  36443. * the given target has changed.
  36444. *
  36445. * @param {Texture} outputTarget - The output target.
  36446. * @return {boolean} Whether the output configuration has changed or not.
  36447. */
  36448. hasOutputChange( outputTarget ) {
  36449. const cacheKey = _outputNodeMap.get( outputTarget );
  36450. return cacheKey !== this.getOutputCacheKey();
  36451. }
  36452. /**
  36453. * Returns a node that represents the output configuration (tone mapping and
  36454. * color space) for the current target.
  36455. *
  36456. * @param {Texture} outputTarget - The output target.
  36457. * @return {Node} The output node.
  36458. */
  36459. getOutputNode( outputTarget ) {
  36460. const renderer = this.renderer;
  36461. const cacheKey = this.getOutputCacheKey();
  36462. const output = outputTarget.isArrayTexture ?
  36463. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  36464. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  36465. _outputNodeMap.set( outputTarget, cacheKey );
  36466. return output;
  36467. }
  36468. /**
  36469. * Triggers the call of `updateBefore()` methods
  36470. * for all nodes of the given render object.
  36471. *
  36472. * @param {RenderObject} renderObject - The render object.
  36473. */
  36474. updateBefore( renderObject ) {
  36475. const nodeBuilder = renderObject.getNodeBuilderState();
  36476. for ( const node of nodeBuilder.updateBeforeNodes ) {
  36477. // update frame state for each node
  36478. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  36479. }
  36480. }
  36481. /**
  36482. * Triggers the call of `updateAfter()` methods
  36483. * for all nodes of the given render object.
  36484. *
  36485. * @param {RenderObject} renderObject - The render object.
  36486. */
  36487. updateAfter( renderObject ) {
  36488. const nodeBuilder = renderObject.getNodeBuilderState();
  36489. for ( const node of nodeBuilder.updateAfterNodes ) {
  36490. // update frame state for each node
  36491. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  36492. }
  36493. }
  36494. /**
  36495. * Triggers the call of `update()` methods
  36496. * for all nodes of the given compute node.
  36497. *
  36498. * @param {Node} computeNode - The compute node.
  36499. */
  36500. updateForCompute( computeNode ) {
  36501. const nodeFrame = this.getNodeFrame();
  36502. const nodeBuilder = this.getForCompute( computeNode );
  36503. for ( const node of nodeBuilder.updateNodes ) {
  36504. nodeFrame.updateNode( node );
  36505. }
  36506. }
  36507. /**
  36508. * Triggers the call of `update()` methods
  36509. * for all nodes of the given compute node.
  36510. *
  36511. * @param {RenderObject} renderObject - The render object.
  36512. */
  36513. updateForRender( renderObject ) {
  36514. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36515. const nodeBuilder = renderObject.getNodeBuilderState();
  36516. for ( const node of nodeBuilder.updateNodes ) {
  36517. nodeFrame.updateNode( node );
  36518. }
  36519. }
  36520. /**
  36521. * Returns `true` if the given render object requires a refresh.
  36522. *
  36523. * @param {RenderObject} renderObject - The render object.
  36524. * @return {boolean} Whether the given render object requires a refresh or not.
  36525. */
  36526. needsRefresh( renderObject ) {
  36527. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36528. const monitor = renderObject.getMonitor();
  36529. return monitor.needsRefresh( renderObject, nodeFrame );
  36530. }
  36531. /**
  36532. * Frees the internal resources.
  36533. */
  36534. dispose() {
  36535. super.dispose();
  36536. this.nodeFrame = new NodeFrame();
  36537. this.nodeBuilderCache = new Map();
  36538. this.cacheLib = {};
  36539. }
  36540. }
  36541. const _plane = /*@__PURE__*/ new Plane();
  36542. /**
  36543. * Represents the state that is used to perform clipping via clipping planes.
  36544. * There is a default clipping context for each render context. When the
  36545. * scene holds instances of `ClippingGroup`, there will be a context for each
  36546. * group.
  36547. *
  36548. * @private
  36549. */
  36550. class ClippingContext {
  36551. /**
  36552. * Constructs a new clipping context.
  36553. *
  36554. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  36555. */
  36556. constructor( parentContext = null ) {
  36557. /**
  36558. * The clipping context's version.
  36559. *
  36560. * @type {number}
  36561. * @readonly
  36562. */
  36563. this.version = 0;
  36564. /**
  36565. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  36566. *
  36567. * @type {?boolean}
  36568. * @default null
  36569. */
  36570. this.clipIntersection = null;
  36571. /**
  36572. * The clipping context's cache key.
  36573. *
  36574. * @type {string}
  36575. */
  36576. this.cacheKey = '';
  36577. /**
  36578. * Whether the shadow pass is active or not.
  36579. *
  36580. * @type {boolean}
  36581. * @default false
  36582. */
  36583. this.shadowPass = false;
  36584. /**
  36585. * The view normal matrix.
  36586. *
  36587. * @type {Matrix3}
  36588. */
  36589. this.viewNormalMatrix = new Matrix3();
  36590. /**
  36591. * Internal cache for maintaining clipping contexts.
  36592. *
  36593. * @type {WeakMap<ClippingGroup,ClippingContext>}
  36594. */
  36595. this.clippingGroupContexts = new WeakMap();
  36596. /**
  36597. * The intersection planes.
  36598. *
  36599. * @type {Array<Vector4>}
  36600. */
  36601. this.intersectionPlanes = [];
  36602. /**
  36603. * The intersection planes.
  36604. *
  36605. * @type {Array<Vector4>}
  36606. */
  36607. this.unionPlanes = [];
  36608. /**
  36609. * The version of the clipping context's parent context.
  36610. *
  36611. * @type {?number}
  36612. * @readonly
  36613. */
  36614. this.parentVersion = null;
  36615. if ( parentContext !== null ) {
  36616. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  36617. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  36618. this.shadowPass = parentContext.shadowPass;
  36619. this.viewMatrix = parentContext.viewMatrix;
  36620. }
  36621. }
  36622. /**
  36623. * Projects the given source clipping planes and writes the result into the
  36624. * destination array.
  36625. *
  36626. * @param {Array<Plane>} source - The source clipping planes.
  36627. * @param {Array<Vector4>} destination - The destination.
  36628. * @param {number} offset - The offset.
  36629. */
  36630. projectPlanes( source, destination, offset ) {
  36631. const l = source.length;
  36632. for ( let i = 0; i < l; i ++ ) {
  36633. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  36634. const v = destination[ offset + i ];
  36635. const normal = _plane.normal;
  36636. v.x = - normal.x;
  36637. v.y = - normal.y;
  36638. v.z = - normal.z;
  36639. v.w = _plane.constant;
  36640. }
  36641. }
  36642. /**
  36643. * Updates the root clipping context of a scene.
  36644. *
  36645. * @param {Scene} scene - The scene.
  36646. * @param {Camera} camera - The camera that is used to render the scene.
  36647. */
  36648. updateGlobal( scene, camera ) {
  36649. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  36650. this.viewMatrix = camera.matrixWorldInverse;
  36651. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  36652. }
  36653. /**
  36654. * Updates the clipping context.
  36655. *
  36656. * @param {ClippingContext} parentContext - The parent context.
  36657. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  36658. */
  36659. update( parentContext, clippingGroup ) {
  36660. let update = false;
  36661. if ( parentContext.version !== this.parentVersion ) {
  36662. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  36663. this.unionPlanes = Array.from( parentContext.unionPlanes );
  36664. this.parentVersion = parentContext.version;
  36665. }
  36666. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  36667. this.clipIntersection = clippingGroup.clipIntersection;
  36668. if ( this.clipIntersection ) {
  36669. this.unionPlanes.length = parentContext.unionPlanes.length;
  36670. } else {
  36671. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  36672. }
  36673. }
  36674. const srcClippingPlanes = clippingGroup.clippingPlanes;
  36675. const l = srcClippingPlanes.length;
  36676. let dstClippingPlanes;
  36677. let offset;
  36678. if ( this.clipIntersection ) {
  36679. dstClippingPlanes = this.intersectionPlanes;
  36680. offset = parentContext.intersectionPlanes.length;
  36681. } else {
  36682. dstClippingPlanes = this.unionPlanes;
  36683. offset = parentContext.unionPlanes.length;
  36684. }
  36685. if ( dstClippingPlanes.length !== offset + l ) {
  36686. dstClippingPlanes.length = offset + l;
  36687. for ( let i = 0; i < l; i ++ ) {
  36688. dstClippingPlanes[ offset + i ] = new Vector4();
  36689. }
  36690. update = true;
  36691. }
  36692. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  36693. if ( update ) {
  36694. this.version ++;
  36695. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  36696. }
  36697. }
  36698. /**
  36699. * Returns a clipping context for the given clipping group.
  36700. *
  36701. * @param {ClippingGroup} clippingGroup - The clipping group.
  36702. * @return {ClippingContext} The clipping context.
  36703. */
  36704. getGroupContext( clippingGroup ) {
  36705. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  36706. let context = this.clippingGroupContexts.get( clippingGroup );
  36707. if ( context === undefined ) {
  36708. context = new ClippingContext( this );
  36709. this.clippingGroupContexts.set( clippingGroup, context );
  36710. }
  36711. context.update( this, clippingGroup );
  36712. return context;
  36713. }
  36714. /**
  36715. * The count of union clipping planes.
  36716. *
  36717. * @type {number}
  36718. * @readonly
  36719. */
  36720. get unionClippingCount() {
  36721. return this.unionPlanes.length;
  36722. }
  36723. }
  36724. /**
  36725. * This module is used to represent render bundles inside the renderer
  36726. * for further processing.
  36727. *
  36728. * @private
  36729. */
  36730. class RenderBundle {
  36731. /**
  36732. * Constructs a new bundle group.
  36733. *
  36734. * @param {BundleGroup} bundleGroup - The bundle group.
  36735. * @param {Camera} camera - The camera the bundle group is rendered with.
  36736. */
  36737. constructor( bundleGroup, camera ) {
  36738. this.bundleGroup = bundleGroup;
  36739. this.camera = camera;
  36740. }
  36741. }
  36742. const _chainKeys$1 = [];
  36743. /**
  36744. * This renderer module manages render bundles.
  36745. *
  36746. * @private
  36747. */
  36748. class RenderBundles {
  36749. /**
  36750. * Constructs a new render bundle management component.
  36751. */
  36752. constructor() {
  36753. /**
  36754. * A chain map for maintaining the render bundles.
  36755. *
  36756. * @type {ChainMap}
  36757. */
  36758. this.bundles = new ChainMap();
  36759. }
  36760. /**
  36761. * Returns a render bundle for the given bundle group and camera.
  36762. *
  36763. * @param {BundleGroup} bundleGroup - The bundle group.
  36764. * @param {Camera} camera - The camera the bundle group is rendered with.
  36765. * @return {RenderBundle} The render bundle.
  36766. */
  36767. get( bundleGroup, camera ) {
  36768. const bundles = this.bundles;
  36769. _chainKeys$1[ 0 ] = bundleGroup;
  36770. _chainKeys$1[ 1 ] = camera;
  36771. let bundle = bundles.get( _chainKeys$1 );
  36772. if ( bundle === undefined ) {
  36773. bundle = new RenderBundle( bundleGroup, camera );
  36774. bundles.set( _chainKeys$1, bundle );
  36775. }
  36776. _chainKeys$1.length = 0;
  36777. return bundle;
  36778. }
  36779. /**
  36780. * Frees all internal resources.
  36781. */
  36782. dispose() {
  36783. this.bundles = new ChainMap();
  36784. }
  36785. }
  36786. /**
  36787. * The purpose of a node library is to assign node implementations
  36788. * to existing library features. In `WebGPURenderer` lights, materials
  36789. * which are not based on `NodeMaterial` as well as tone mapping techniques
  36790. * are implemented with node-based modules.
  36791. *
  36792. * @private
  36793. */
  36794. class NodeLibrary {
  36795. /**
  36796. * Constructs a new node library.
  36797. */
  36798. constructor() {
  36799. /**
  36800. * A weak map that maps lights to light nodes.
  36801. *
  36802. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  36803. */
  36804. this.lightNodes = new WeakMap();
  36805. /**
  36806. * A map that maps materials to node materials.
  36807. *
  36808. * @type {Map<string,NodeMaterial.constructor>}
  36809. */
  36810. this.materialNodes = new Map();
  36811. /**
  36812. * A map that maps tone mapping techniques (constants)
  36813. * to tone mapping node functions.
  36814. *
  36815. * @type {Map<number,Function>}
  36816. */
  36817. this.toneMappingNodes = new Map();
  36818. }
  36819. /**
  36820. * Returns a matching node material instance for the given material object.
  36821. *
  36822. * This method also assigns/copies the properties of the given material object
  36823. * to the node material. This is done to make sure the current material
  36824. * configuration carries over to the node version.
  36825. *
  36826. * @param {Material} material - A material.
  36827. * @return {NodeMaterial} The corresponding node material.
  36828. */
  36829. fromMaterial( material ) {
  36830. if ( material.isNodeMaterial ) return material;
  36831. let nodeMaterial = null;
  36832. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  36833. if ( nodeMaterialClass !== null ) {
  36834. nodeMaterial = new nodeMaterialClass();
  36835. for ( const key in material ) {
  36836. nodeMaterial[ key ] = material[ key ];
  36837. }
  36838. }
  36839. return nodeMaterial;
  36840. }
  36841. /**
  36842. * Adds a tone mapping node function for a tone mapping technique (constant).
  36843. *
  36844. * @param {Function} toneMappingNode - The tone mapping node function.
  36845. * @param {number} toneMapping - The tone mapping.
  36846. */
  36847. addToneMapping( toneMappingNode, toneMapping ) {
  36848. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  36849. }
  36850. /**
  36851. * Returns a tone mapping node function for a tone mapping technique (constant).
  36852. *
  36853. * @param {number} toneMapping - The tone mapping.
  36854. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  36855. */
  36856. getToneMappingFunction( toneMapping ) {
  36857. return this.toneMappingNodes.get( toneMapping ) || null;
  36858. }
  36859. /**
  36860. * Returns a node material class definition for a material type.
  36861. *
  36862. * @param {string} materialType - The material type.
  36863. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  36864. */
  36865. getMaterialNodeClass( materialType ) {
  36866. return this.materialNodes.get( materialType ) || null;
  36867. }
  36868. /**
  36869. * Adds a node material class definition for a given material type.
  36870. *
  36871. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  36872. * @param {string} materialClassType - The material type.
  36873. */
  36874. addMaterial( materialNodeClass, materialClassType ) {
  36875. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  36876. }
  36877. /**
  36878. * Returns a light node class definition for a light class definition.
  36879. *
  36880. * @param {Light.constructor} light - The light class definition.
  36881. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  36882. */
  36883. getLightNodeClass( light ) {
  36884. return this.lightNodes.get( light ) || null;
  36885. }
  36886. /**
  36887. * Adds a light node class definition for a given light class definition.
  36888. *
  36889. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  36890. * @param {Light.constructor} lightClass - The light class definition.
  36891. */
  36892. addLight( lightNodeClass, lightClass ) {
  36893. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  36894. }
  36895. /**
  36896. * Adds a node class definition for the given type to the provided type library.
  36897. *
  36898. * @param {any} nodeClass - The node class definition.
  36899. * @param {number|string} type - The object type.
  36900. * @param {Map} library - The type library.
  36901. */
  36902. addType( nodeClass, type, library ) {
  36903. if ( library.has( type ) ) {
  36904. console.warn( `Redefinition of node ${ type }` );
  36905. return;
  36906. }
  36907. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  36908. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  36909. library.set( type, nodeClass );
  36910. }
  36911. /**
  36912. * Adds a node class definition for the given class definition to the provided type library.
  36913. *
  36914. * @param {any} nodeClass - The node class definition.
  36915. * @param {any} baseClass - The class definition.
  36916. * @param {WeakMap} library - The type library.
  36917. */
  36918. addClass( nodeClass, baseClass, library ) {
  36919. if ( library.has( baseClass ) ) {
  36920. console.warn( `Redefinition of node ${ baseClass.name }` );
  36921. return;
  36922. }
  36923. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  36924. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  36925. library.set( baseClass, nodeClass );
  36926. }
  36927. }
  36928. const _defaultLights = /*@__PURE__*/ new LightsNode();
  36929. const _chainKeys = [];
  36930. /**
  36931. * This renderer module manages the lights nodes which are unique
  36932. * per scene and camera combination.
  36933. *
  36934. * The lights node itself is later configured in the render list
  36935. * with the actual lights from the scene.
  36936. *
  36937. * @private
  36938. * @augments ChainMap
  36939. */
  36940. class Lighting extends ChainMap {
  36941. /**
  36942. * Constructs a lighting management component.
  36943. */
  36944. constructor() {
  36945. super();
  36946. }
  36947. /**
  36948. * Creates a new lights node for the given array of lights.
  36949. *
  36950. * @param {Array<Light>} lights - The render object.
  36951. * @return {LightsNode} The lights node.
  36952. */
  36953. createNode( lights = [] ) {
  36954. return new LightsNode().setLights( lights );
  36955. }
  36956. /**
  36957. * Returns a lights node for the given scene and camera.
  36958. *
  36959. * @param {Scene} scene - The scene.
  36960. * @param {Camera} camera - The camera.
  36961. * @return {LightsNode} The lights node.
  36962. */
  36963. getNode( scene, camera ) {
  36964. // ignore post-processing
  36965. if ( scene.isQuadMesh ) return _defaultLights;
  36966. _chainKeys[ 0 ] = scene;
  36967. _chainKeys[ 1 ] = camera;
  36968. let node = this.get( _chainKeys );
  36969. if ( node === undefined ) {
  36970. node = this.createNode();
  36971. this.set( _chainKeys, node );
  36972. }
  36973. _chainKeys.length = 0;
  36974. return node;
  36975. }
  36976. }
  36977. /**
  36978. * A special type of render target that is used when rendering
  36979. * with the WebXR Device API.
  36980. *
  36981. * @private
  36982. * @augments RenderTarget
  36983. */
  36984. class XRRenderTarget extends RenderTarget {
  36985. /**
  36986. * Constructs a new XR render target.
  36987. *
  36988. * @param {number} [width=1] - The width of the render target.
  36989. * @param {number} [height=1] - The height of the render target.
  36990. * @param {Object} [options={}] - The configuration options.
  36991. */
  36992. constructor( width = 1, height = 1, options = {} ) {
  36993. super( width, height, options );
  36994. /**
  36995. * This flag can be used for type testing.
  36996. *
  36997. * @type {boolean}
  36998. * @readonly
  36999. * @default true
  37000. */
  37001. this.isXRRenderTarget = true;
  37002. /**
  37003. * Whether the attachments of the render target
  37004. * are defined by external textures. This flag is
  37005. * set to `true` when using the WebXR Layers API.
  37006. *
  37007. * @private
  37008. * @type {boolean}
  37009. * @default false
  37010. */
  37011. this._hasExternalTextures = false;
  37012. /**
  37013. * Whether a depth buffer should automatically be allocated
  37014. * for this XR render target or not.
  37015. *
  37016. * Allocating a depth buffer is the default behavior of XR render
  37017. * targets. However, when using the WebXR Layers API, this flag
  37018. * must be set to `false` when the `ignoreDepthValues` property of
  37019. * the projection layers evaluates to `false`.
  37020. *
  37021. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  37022. *
  37023. * @private
  37024. * @type {boolean}
  37025. * @default true
  37026. */
  37027. this._autoAllocateDepthBuffer = true;
  37028. /**
  37029. * Whether this render target is associated with a XRWebGLLayer.
  37030. *
  37031. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  37032. * this means that you don't have access to its bound color,
  37033. * stencil and depth buffers. We need to handle this framebuffer
  37034. * differently since its textures are always bound.
  37035. *
  37036. * @private
  37037. * @type {boolean}
  37038. * @default false
  37039. * */
  37040. this._isOpaqueFramebuffer = false;
  37041. }
  37042. copy( source ) {
  37043. super.copy( source );
  37044. this._hasExternalTextures = source._hasExternalTextures;
  37045. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  37046. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  37047. return this;
  37048. }
  37049. }
  37050. const _cameraLPos = /*@__PURE__*/ new Vector3();
  37051. const _cameraRPos = /*@__PURE__*/ new Vector3();
  37052. /**
  37053. * The XR manager is built on top of the WebXR Device API to
  37054. * manage XR sessions with `WebGPURenderer`.
  37055. *
  37056. * XR is currently only supported with a WebGL 2 backend.
  37057. *
  37058. * @augments EventDispatcher
  37059. */
  37060. class XRManager extends EventDispatcher {
  37061. /**
  37062. * Constructs a new XR manager.
  37063. *
  37064. * @param {Renderer} renderer - The renderer.
  37065. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  37066. */
  37067. constructor( renderer, multiview = false ) {
  37068. super();
  37069. /**
  37070. * This flag globally enables XR rendering.
  37071. *
  37072. * @type {boolean}
  37073. * @default false
  37074. */
  37075. this.enabled = false;
  37076. /**
  37077. * Whether the XR device is currently presenting or not.
  37078. *
  37079. * @type {boolean}
  37080. * @default false
  37081. * @readonly
  37082. */
  37083. this.isPresenting = false;
  37084. /**
  37085. * Whether the XR camera should automatically be updated or not.
  37086. *
  37087. * @type {boolean}
  37088. * @default true
  37089. */
  37090. this.cameraAutoUpdate = true;
  37091. /**
  37092. * The renderer.
  37093. *
  37094. * @private
  37095. * @type {Renderer}
  37096. */
  37097. this._renderer = renderer;
  37098. // camera
  37099. /**
  37100. * Represents the camera for the left eye.
  37101. *
  37102. * @private
  37103. * @type {PerspectiveCamera}
  37104. */
  37105. this._cameraL = new PerspectiveCamera();
  37106. this._cameraL.viewport = new Vector4();
  37107. /**
  37108. * Represents the camera for the right eye.
  37109. *
  37110. * @private
  37111. * @type {PerspectiveCamera}
  37112. */
  37113. this._cameraR = new PerspectiveCamera();
  37114. this._cameraR.viewport = new Vector4();
  37115. /**
  37116. * A list of cameras used for rendering the XR views.
  37117. *
  37118. * @private
  37119. * @type {Array<Camera>}
  37120. */
  37121. this._cameras = [ this._cameraL, this._cameraR ];
  37122. /**
  37123. * The main XR camera.
  37124. *
  37125. * @private
  37126. * @type {ArrayCamera}
  37127. */
  37128. this._cameraXR = new ArrayCamera();
  37129. /**
  37130. * The current near value of the XR camera.
  37131. *
  37132. * @private
  37133. * @type {?number}
  37134. * @default null
  37135. */
  37136. this._currentDepthNear = null;
  37137. /**
  37138. * The current far value of the XR camera.
  37139. *
  37140. * @private
  37141. * @type {?number}
  37142. * @default null
  37143. */
  37144. this._currentDepthFar = null;
  37145. /**
  37146. * A list of WebXR controllers requested by the application.
  37147. *
  37148. * @private
  37149. * @type {Array<WebXRController>}
  37150. */
  37151. this._controllers = [];
  37152. /**
  37153. * A list of XR input source. Each input source belongs to
  37154. * an instance of WebXRController.
  37155. *
  37156. * @private
  37157. * @type {Array<XRInputSource?>}
  37158. */
  37159. this._controllerInputSources = [];
  37160. /**
  37161. * The XR render target that represents the rendering destination
  37162. * during an active XR session.
  37163. *
  37164. * @private
  37165. * @type {?RenderTarget}
  37166. * @default null
  37167. */
  37168. this._xrRenderTarget = null;
  37169. /**
  37170. * An array holding all the non-projection layers
  37171. *
  37172. * @private
  37173. * @type {Array<Object>}
  37174. * @default []
  37175. */
  37176. this._layers = [];
  37177. /**
  37178. * Whether the XR session uses layers.
  37179. *
  37180. * @type {boolean}
  37181. * @default false
  37182. */
  37183. this._sessionUsesLayers = false;
  37184. /**
  37185. * Whether the device supports binding gl objects.
  37186. *
  37187. * @private
  37188. * @type {boolean}
  37189. * @readonly
  37190. */
  37191. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  37192. this._frameBufferTargets = null;
  37193. /**
  37194. * Helper function to create native WebXR Layer.
  37195. *
  37196. * @private
  37197. * @type {Function}
  37198. */
  37199. this._createXRLayer = createXRLayer.bind( this );
  37200. /**
  37201. * The current WebGL context.
  37202. *
  37203. * @private
  37204. * @type {?WebGL2RenderingContext}
  37205. * @default null
  37206. */
  37207. this._gl = null;
  37208. /**
  37209. * The current animation context.
  37210. *
  37211. * @private
  37212. * @type {?Window}
  37213. * @default null
  37214. */
  37215. this._currentAnimationContext = null;
  37216. /**
  37217. * The current animation loop.
  37218. *
  37219. * @private
  37220. * @type {?Function}
  37221. * @default null
  37222. */
  37223. this._currentAnimationLoop = null;
  37224. /**
  37225. * The current pixel ratio.
  37226. *
  37227. * @private
  37228. * @type {?number}
  37229. * @default null
  37230. */
  37231. this._currentPixelRatio = null;
  37232. /**
  37233. * The current size of the renderer's canvas
  37234. * in logical pixel unit.
  37235. *
  37236. * @private
  37237. * @type {Vector2}
  37238. */
  37239. this._currentSize = new Vector2();
  37240. /**
  37241. * The default event listener for handling events inside a XR session.
  37242. *
  37243. * @private
  37244. * @type {Function}
  37245. */
  37246. this._onSessionEvent = onSessionEvent.bind( this );
  37247. /**
  37248. * The event listener for handling the end of a XR session.
  37249. *
  37250. * @private
  37251. * @type {Function}
  37252. */
  37253. this._onSessionEnd = onSessionEnd.bind( this );
  37254. /**
  37255. * The event listener for handling the `inputsourceschange` event.
  37256. *
  37257. * @private
  37258. * @type {Function}
  37259. */
  37260. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  37261. /**
  37262. * The animation loop which is used as a replacement for the default
  37263. * animation loop of the application. It is only used when a XR session
  37264. * is active.
  37265. *
  37266. * @private
  37267. * @type {Function}
  37268. */
  37269. this._onAnimationFrame = onAnimationFrame.bind( this );
  37270. /**
  37271. * The current XR reference space.
  37272. *
  37273. * @private
  37274. * @type {?XRReferenceSpace}
  37275. * @default null
  37276. */
  37277. this._referenceSpace = null;
  37278. /**
  37279. * The current XR reference space type.
  37280. *
  37281. * @private
  37282. * @type {XRReferenceSpaceType}
  37283. * @default 'local-floor'
  37284. */
  37285. this._referenceSpaceType = 'local-floor';
  37286. /**
  37287. * A custom reference space defined by the application.
  37288. *
  37289. * @private
  37290. * @type {?XRReferenceSpace}
  37291. * @default null
  37292. */
  37293. this._customReferenceSpace = null;
  37294. /**
  37295. * The framebuffer scale factor.
  37296. *
  37297. * @private
  37298. * @type {number}
  37299. * @default 1
  37300. */
  37301. this._framebufferScaleFactor = 1;
  37302. /**
  37303. * The foveation factor.
  37304. *
  37305. * @private
  37306. * @type {number}
  37307. * @default 1
  37308. */
  37309. this._foveation = 1.0;
  37310. /**
  37311. * A reference to the current XR session.
  37312. *
  37313. * @private
  37314. * @type {?XRSession}
  37315. * @default null
  37316. */
  37317. this._session = null;
  37318. /**
  37319. * A reference to the current XR base layer.
  37320. *
  37321. * @private
  37322. * @type {?XRWebGLLayer}
  37323. * @default null
  37324. */
  37325. this._glBaseLayer = null;
  37326. /**
  37327. * A reference to the current XR binding.
  37328. *
  37329. * @private
  37330. * @type {?XRWebGLBinding}
  37331. * @default null
  37332. */
  37333. this._glBinding = null;
  37334. /**
  37335. * A reference to the current XR projection layer.
  37336. *
  37337. * @private
  37338. * @type {?XRProjectionLayer}
  37339. * @default null
  37340. */
  37341. this._glProjLayer = null;
  37342. /**
  37343. * A reference to the current XR frame.
  37344. *
  37345. * @private
  37346. * @type {?XRFrame}
  37347. * @default null
  37348. */
  37349. this._xrFrame = null;
  37350. /**
  37351. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  37352. *
  37353. * Note: this does not represent XRSession explicitly requesting
  37354. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  37355. *
  37356. * @private
  37357. * @type {boolean}
  37358. * @readonly
  37359. */
  37360. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  37361. /**
  37362. * Whether the usage of multiview has been requested by the application or not.
  37363. *
  37364. * @private
  37365. * @type {boolean}
  37366. * @default false
  37367. * @readonly
  37368. */
  37369. this._useMultiviewIfPossible = multiview;
  37370. /**
  37371. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  37372. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  37373. *
  37374. * @private
  37375. * @type {boolean}
  37376. * @readonly
  37377. */
  37378. this._useMultiview = false;
  37379. }
  37380. /**
  37381. * Returns an instance of `THREE.Group` that represents the transformation
  37382. * of a XR controller in target ray 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. getController( index ) {
  37389. const controller = this._getController( index );
  37390. return controller.getTargetRaySpace();
  37391. }
  37392. /**
  37393. * Returns an instance of `THREE.Group` that represents the transformation
  37394. * of a XR controller in grip 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. getControllerGrip( index ) {
  37401. const controller = this._getController( index );
  37402. return controller.getGripSpace();
  37403. }
  37404. /**
  37405. * Returns an instance of `THREE.Group` that represents the transformation
  37406. * of a XR controller in hand space. The requested controller is defined
  37407. * by the given index.
  37408. *
  37409. * @param {number} index - The index of the XR controller.
  37410. * @return {Group} A group that represents the controller's transformation.
  37411. */
  37412. getHand( index ) {
  37413. const controller = this._getController( index );
  37414. return controller.getHandSpace();
  37415. }
  37416. /**
  37417. * Returns the foveation value.
  37418. *
  37419. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  37420. */
  37421. getFoveation() {
  37422. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  37423. return undefined;
  37424. }
  37425. return this._foveation;
  37426. }
  37427. /**
  37428. * Sets the foveation value.
  37429. *
  37430. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  37431. * and `1` means maximum foveation (the edges render at lower resolution).
  37432. */
  37433. setFoveation( foveation ) {
  37434. this._foveation = foveation;
  37435. if ( this._glProjLayer !== null ) {
  37436. this._glProjLayer.fixedFoveation = foveation;
  37437. }
  37438. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  37439. this._glBaseLayer.fixedFoveation = foveation;
  37440. }
  37441. }
  37442. /**
  37443. * Returns the framebuffer scale factor.
  37444. *
  37445. * @return {number} The framebuffer scale factor.
  37446. */
  37447. getFramebufferScaleFactor() {
  37448. return this._framebufferScaleFactor;
  37449. }
  37450. /**
  37451. * Sets the framebuffer scale factor.
  37452. *
  37453. * This method can not be used during a XR session.
  37454. *
  37455. * @param {number} factor - The framebuffer scale factor.
  37456. */
  37457. setFramebufferScaleFactor( factor ) {
  37458. this._framebufferScaleFactor = factor;
  37459. if ( this.isPresenting === true ) {
  37460. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  37461. }
  37462. }
  37463. /**
  37464. * Returns the reference space type.
  37465. *
  37466. * @return {XRReferenceSpaceType} The reference space type.
  37467. */
  37468. getReferenceSpaceType() {
  37469. return this._referenceSpaceType;
  37470. }
  37471. /**
  37472. * Sets the reference space type.
  37473. *
  37474. * This method can not be used during a XR session.
  37475. *
  37476. * @param {XRReferenceSpaceType} type - The reference space type.
  37477. */
  37478. setReferenceSpaceType( type ) {
  37479. this._referenceSpaceType = type;
  37480. if ( this.isPresenting === true ) {
  37481. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  37482. }
  37483. }
  37484. /**
  37485. * Returns the XR reference space.
  37486. *
  37487. * @return {XRReferenceSpace} The XR reference space.
  37488. */
  37489. getReferenceSpace() {
  37490. return this._customReferenceSpace || this._referenceSpace;
  37491. }
  37492. /**
  37493. * Sets a custom XR reference space.
  37494. *
  37495. * @param {XRReferenceSpace} space - The XR reference space.
  37496. */
  37497. setReferenceSpace( space ) {
  37498. this._customReferenceSpace = space;
  37499. }
  37500. /**
  37501. * Returns the XR camera.
  37502. *
  37503. * @return {ArrayCamera} The XR camera.
  37504. */
  37505. getCamera() {
  37506. return this._cameraXR;
  37507. }
  37508. /**
  37509. * Returns the environment blend mode from the current XR session.
  37510. *
  37511. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  37512. */
  37513. getEnvironmentBlendMode() {
  37514. if ( this._session !== null ) {
  37515. return this._session.environmentBlendMode;
  37516. }
  37517. }
  37518. /**
  37519. * Returns the current XR binding.
  37520. *
  37521. * Creates a new binding if needed and the browser is
  37522. * capable of doing so.
  37523. *
  37524. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  37525. */
  37526. getBinding() {
  37527. if ( this._glBinding === null && this._supportsGlBinding ) {
  37528. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  37529. }
  37530. return this._glBinding;
  37531. }
  37532. /**
  37533. * Returns the current XR frame.
  37534. *
  37535. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  37536. */
  37537. getFrame() {
  37538. return this._xrFrame;
  37539. }
  37540. /**
  37541. * Returns `true` if the engine renders to a multiview target.
  37542. *
  37543. * @return {boolean} Whether the engine renders to a multiview render target or not.
  37544. */
  37545. useMultiview() {
  37546. return this._useMultiview;
  37547. }
  37548. /**
  37549. * This method can be used in XR applications to create a quadratic layer that presents a separate
  37550. * rendered scene.
  37551. *
  37552. * @param {number} width - The width of the layer plane in world units.
  37553. * @param {number} height - The height of the layer plane in world units.
  37554. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  37555. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  37556. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  37557. * @param {number} pixelheight - The height of the layer's render target in pixels.
  37558. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  37559. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  37560. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  37561. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  37562. */
  37563. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  37564. const geometry = new PlaneGeometry( width, height );
  37565. const renderTarget = new XRRenderTarget(
  37566. pixelwidth,
  37567. pixelheight,
  37568. {
  37569. format: RGBAFormat,
  37570. type: UnsignedByteType,
  37571. depthTexture: new DepthTexture(
  37572. pixelwidth,
  37573. pixelheight,
  37574. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  37575. undefined,
  37576. undefined,
  37577. undefined,
  37578. undefined,
  37579. undefined,
  37580. undefined,
  37581. attributes.stencil ? DepthStencilFormat : DepthFormat
  37582. ),
  37583. stencilBuffer: attributes.stencil,
  37584. resolveDepthBuffer: false,
  37585. resolveStencilBuffer: false
  37586. } );
  37587. renderTarget._autoAllocateDepthBuffer = true;
  37588. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  37589. material.map = renderTarget.texture;
  37590. material.map.offset.y = 1;
  37591. material.map.repeat.y = -1;
  37592. const plane = new Mesh( geometry, material );
  37593. plane.position.copy( translation );
  37594. plane.quaternion.copy( quaternion );
  37595. const layer = {
  37596. type: 'quad',
  37597. width: width,
  37598. height: height,
  37599. translation: translation,
  37600. quaternion: quaternion,
  37601. pixelwidth: pixelwidth,
  37602. pixelheight: pixelheight,
  37603. plane: plane,
  37604. material: material,
  37605. rendercall: rendercall,
  37606. renderTarget: renderTarget };
  37607. this._layers.push( layer );
  37608. if ( this._session !== null ) {
  37609. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  37610. layer.plane.material.blending = CustomBlending;
  37611. layer.plane.material.blendEquation = AddEquation;
  37612. layer.plane.material.blendSrc = ZeroFactor;
  37613. layer.plane.material.blendDst = ZeroFactor;
  37614. layer.xrlayer = this._createXRLayer( layer );
  37615. const xrlayers = this._session.renderState.layers;
  37616. xrlayers.unshift( layer.xrlayer );
  37617. this._session.updateRenderState( { layers: xrlayers } );
  37618. } else {
  37619. renderTarget.isXRRenderTarget = false;
  37620. }
  37621. return plane;
  37622. }
  37623. /**
  37624. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  37625. * rendered scene.
  37626. *
  37627. * @param {number} radius - The radius of the cylinder in world units.
  37628. * @param {number} centralAngle - The central angle of the cylinder in radians.
  37629. * @param {number} aspectratio - The aspect ratio.
  37630. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  37631. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  37632. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  37633. * @param {number} pixelheight - The height of the layer's render target in pixels.
  37634. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  37635. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  37636. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  37637. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  37638. */
  37639. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  37640. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  37641. const renderTarget = new XRRenderTarget(
  37642. pixelwidth,
  37643. pixelheight,
  37644. {
  37645. format: RGBAFormat,
  37646. type: UnsignedByteType,
  37647. depthTexture: new DepthTexture(
  37648. pixelwidth,
  37649. pixelheight,
  37650. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  37651. undefined,
  37652. undefined,
  37653. undefined,
  37654. undefined,
  37655. undefined,
  37656. undefined,
  37657. attributes.stencil ? DepthStencilFormat : DepthFormat
  37658. ),
  37659. stencilBuffer: attributes.stencil,
  37660. resolveDepthBuffer: false,
  37661. resolveStencilBuffer: false
  37662. } );
  37663. renderTarget._autoAllocateDepthBuffer = true;
  37664. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  37665. material.map = renderTarget.texture;
  37666. material.map.offset.y = 1;
  37667. material.map.repeat.y = -1;
  37668. const plane = new Mesh( geometry, material );
  37669. plane.position.copy( translation );
  37670. plane.quaternion.copy( quaternion );
  37671. const layer = {
  37672. type: 'cylinder',
  37673. radius: radius,
  37674. centralAngle: centralAngle,
  37675. aspectratio: aspectratio,
  37676. translation: translation,
  37677. quaternion: quaternion,
  37678. pixelwidth: pixelwidth,
  37679. pixelheight: pixelheight,
  37680. plane: plane,
  37681. material: material,
  37682. rendercall: rendercall,
  37683. renderTarget: renderTarget };
  37684. this._layers.push( layer );
  37685. if ( this._session !== null ) {
  37686. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  37687. layer.plane.material.blending = CustomBlending;
  37688. layer.plane.material.blendEquation = AddEquation;
  37689. layer.plane.material.blendSrc = ZeroFactor;
  37690. layer.plane.material.blendDst = ZeroFactor;
  37691. layer.xrlayer = this._createXRLayer( layer );
  37692. const xrlayers = this._session.renderState.layers;
  37693. xrlayers.unshift( layer.xrlayer );
  37694. this._session.updateRenderState( { layers: xrlayers } );
  37695. } else {
  37696. renderTarget.isXRRenderTarget = false;
  37697. }
  37698. return plane;
  37699. }
  37700. /**
  37701. * Renders the XR layers that have been previously added to the scene.
  37702. *
  37703. * This method is usually called in your animation loop before rendering
  37704. * the actual scene via `renderer.render( scene, camera );`.
  37705. */
  37706. renderLayers( ) {
  37707. const translationObject = new Vector3();
  37708. const quaternionObject = new Quaternion();
  37709. const renderer = this._renderer;
  37710. const wasPresenting = this.isPresenting;
  37711. const rendererOutputTarget = renderer.getOutputRenderTarget();
  37712. const rendererFramebufferTarget = renderer._frameBufferTarget;
  37713. this.isPresenting = false;
  37714. const rendererSize = new Vector2();
  37715. renderer.getSize( rendererSize );
  37716. const rendererQuad = renderer._quad;
  37717. for ( const layer of this._layers ) {
  37718. layer.renderTarget.isXRRenderTarget = this._session !== null;
  37719. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  37720. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  37721. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  37722. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  37723. renderer.backend.setXRRenderTargetTextures(
  37724. layer.renderTarget,
  37725. glSubImage.colorTexture,
  37726. undefined );
  37727. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  37728. renderer.setOutputRenderTarget( layer.renderTarget );
  37729. renderer.setRenderTarget( null );
  37730. renderer._frameBufferTarget = null;
  37731. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  37732. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  37733. if ( ! frameBufferTarget ) {
  37734. renderer._quad = new QuadMesh( new NodeMaterial() );
  37735. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  37736. } else {
  37737. renderer._frameBufferTarget = frameBufferTarget;
  37738. renderer._quad = quad;
  37739. }
  37740. layer.rendercall();
  37741. renderer._frameBufferTarget = null;
  37742. } else {
  37743. renderer.setRenderTarget( layer.renderTarget );
  37744. layer.rendercall();
  37745. }
  37746. }
  37747. renderer.setRenderTarget( null );
  37748. renderer.setOutputRenderTarget( rendererOutputTarget );
  37749. renderer._frameBufferTarget = rendererFramebufferTarget;
  37750. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  37751. renderer._quad = rendererQuad;
  37752. this.isPresenting = wasPresenting;
  37753. }
  37754. /**
  37755. * Returns the current XR session.
  37756. *
  37757. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  37758. */
  37759. getSession() {
  37760. return this._session;
  37761. }
  37762. /**
  37763. * After a XR session has been requested usually with one of the `*Button` modules, it
  37764. * is injected into the renderer with this method. This method triggers the start of
  37765. * the actual XR rendering.
  37766. *
  37767. * @async
  37768. * @param {XRSession} session - The XR session to set.
  37769. * @return {Promise} A Promise that resolves when the session has been set.
  37770. */
  37771. async setSession( session ) {
  37772. const renderer = this._renderer;
  37773. const backend = renderer.backend;
  37774. this._gl = renderer.getContext();
  37775. const gl = this._gl;
  37776. const attributes = gl.getContextAttributes();
  37777. this._session = session;
  37778. if ( session !== null ) {
  37779. 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.' );
  37780. session.addEventListener( 'select', this._onSessionEvent );
  37781. session.addEventListener( 'selectstart', this._onSessionEvent );
  37782. session.addEventListener( 'selectend', this._onSessionEvent );
  37783. session.addEventListener( 'squeeze', this._onSessionEvent );
  37784. session.addEventListener( 'squeezestart', this._onSessionEvent );
  37785. session.addEventListener( 'squeezeend', this._onSessionEvent );
  37786. session.addEventListener( 'end', this._onSessionEnd );
  37787. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  37788. await backend.makeXRCompatible();
  37789. this._currentPixelRatio = renderer.getPixelRatio();
  37790. renderer.getSize( this._currentSize );
  37791. this._currentAnimationContext = renderer._animation.getContext();
  37792. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  37793. renderer._animation.stop();
  37794. //
  37795. if ( this._supportsLayers === true ) {
  37796. // default path using XRProjectionLayer
  37797. let depthFormat = null;
  37798. let depthType = null;
  37799. let glDepthFormat = null;
  37800. if ( renderer.depth ) {
  37801. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  37802. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  37803. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  37804. }
  37805. const projectionlayerInit = {
  37806. colorFormat: gl.RGBA8,
  37807. depthFormat: glDepthFormat,
  37808. scaleFactor: this._framebufferScaleFactor,
  37809. clearOnAccess: false
  37810. };
  37811. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  37812. projectionlayerInit.textureType = 'texture-array';
  37813. this._useMultiview = true;
  37814. }
  37815. this._glBinding = this.getBinding();
  37816. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  37817. const layersArray = [ glProjLayer ];
  37818. this._glProjLayer = glProjLayer;
  37819. renderer.setPixelRatio( 1 );
  37820. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  37821. const depth = this._useMultiview ? 2 : 1;
  37822. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  37823. this._xrRenderTarget = new XRRenderTarget(
  37824. glProjLayer.textureWidth,
  37825. glProjLayer.textureHeight,
  37826. {
  37827. format: RGBAFormat,
  37828. type: UnsignedByteType,
  37829. colorSpace: renderer.outputColorSpace,
  37830. depthTexture: depthTexture,
  37831. stencilBuffer: renderer.stencil,
  37832. samples: attributes.antialias ? 4 : 0,
  37833. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  37834. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  37835. depth: this._useMultiview ? 2 : 1,
  37836. multiview: this._useMultiview
  37837. } );
  37838. this._xrRenderTarget._hasExternalTextures = true;
  37839. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  37840. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  37841. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  37842. if ( this._sessionUsesLayers ) {
  37843. // switch layers to native
  37844. for ( const layer of this._layers ) {
  37845. // change material so it "punches" out a hole to show the XR Layer.
  37846. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  37847. layer.plane.material.blending = CustomBlending;
  37848. layer.plane.material.blendEquation = AddEquation;
  37849. layer.plane.material.blendSrc = ZeroFactor;
  37850. layer.plane.material.blendDst = ZeroFactor;
  37851. layer.xrlayer = this._createXRLayer( layer );
  37852. layersArray.unshift( layer.xrlayer );
  37853. }
  37854. }
  37855. session.updateRenderState( { layers: layersArray } );
  37856. } else {
  37857. // fallback to XRWebGLLayer
  37858. const layerInit = {
  37859. antialias: renderer.samples > 0,
  37860. alpha: true,
  37861. depth: renderer.depth,
  37862. stencil: renderer.stencil,
  37863. framebufferScaleFactor: this.getFramebufferScaleFactor()
  37864. };
  37865. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  37866. this._glBaseLayer = glBaseLayer;
  37867. session.updateRenderState( { baseLayer: glBaseLayer } );
  37868. renderer.setPixelRatio( 1 );
  37869. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  37870. this._xrRenderTarget = new XRRenderTarget(
  37871. glBaseLayer.framebufferWidth,
  37872. glBaseLayer.framebufferHeight,
  37873. {
  37874. format: RGBAFormat,
  37875. type: UnsignedByteType,
  37876. colorSpace: renderer.outputColorSpace,
  37877. stencilBuffer: renderer.stencil,
  37878. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  37879. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  37880. }
  37881. );
  37882. this._xrRenderTarget._isOpaqueFramebuffer = true;
  37883. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  37884. }
  37885. //
  37886. this.setFoveation( this.getFoveation() );
  37887. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  37888. renderer._animation.setContext( session );
  37889. renderer._animation.start();
  37890. this.isPresenting = true;
  37891. this.dispatchEvent( { type: 'sessionstart' } );
  37892. }
  37893. }
  37894. /**
  37895. * This method is called by the renderer per frame and updates the XR camera
  37896. * and it sub cameras based on the given camera. The given camera is the "user"
  37897. * camera created on application level and used for non-XR rendering.
  37898. *
  37899. * @param {PerspectiveCamera} camera - The camera.
  37900. */
  37901. updateCamera( camera ) {
  37902. const session = this._session;
  37903. if ( session === null ) return;
  37904. const depthNear = camera.near;
  37905. const depthFar = camera.far;
  37906. const cameraXR = this._cameraXR;
  37907. const cameraL = this._cameraL;
  37908. const cameraR = this._cameraR;
  37909. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  37910. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  37911. cameraXR.isMultiViewCamera = this._useMultiview;
  37912. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  37913. // Note that the new renderState won't apply until the next frame. See #18320
  37914. session.updateRenderState( {
  37915. depthNear: cameraXR.near,
  37916. depthFar: cameraXR.far
  37917. } );
  37918. this._currentDepthNear = cameraXR.near;
  37919. this._currentDepthFar = cameraXR.far;
  37920. }
  37921. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  37922. cameraXR.layers.mask = camera.layers.mask | 0b110;
  37923. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  37924. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  37925. const parent = camera.parent;
  37926. const cameras = cameraXR.cameras;
  37927. updateCamera( cameraXR, parent );
  37928. for ( let i = 0; i < cameras.length; i ++ ) {
  37929. updateCamera( cameras[ i ], parent );
  37930. }
  37931. // update projection matrix for proper view frustum culling
  37932. if ( cameras.length === 2 ) {
  37933. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  37934. } else {
  37935. // assume single camera setup (AR)
  37936. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  37937. }
  37938. // update user camera and its children
  37939. updateUserCamera( camera, cameraXR, parent );
  37940. }
  37941. /**
  37942. * Returns a WebXR controller for the given controller index.
  37943. *
  37944. * @private
  37945. * @param {number} index - The controller index.
  37946. * @return {WebXRController} The XR controller.
  37947. */
  37948. _getController( index ) {
  37949. let controller = this._controllers[ index ];
  37950. if ( controller === undefined ) {
  37951. controller = new WebXRController();
  37952. this._controllers[ index ] = controller;
  37953. }
  37954. return controller;
  37955. }
  37956. }
  37957. /**
  37958. * Assumes 2 cameras that are parallel and share an X-axis, and that
  37959. * the cameras' projection and world matrices have already been set.
  37960. * And that near and far planes are identical for both cameras.
  37961. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  37962. *
  37963. * @param {ArrayCamera} camera - The camera to update.
  37964. * @param {PerspectiveCamera} cameraL - The left camera.
  37965. * @param {PerspectiveCamera} cameraR - The right camera.
  37966. */
  37967. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  37968. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  37969. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  37970. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  37971. const projL = cameraL.projectionMatrix.elements;
  37972. const projR = cameraR.projectionMatrix.elements;
  37973. // VR systems will have identical far and near planes, and
  37974. // most likely identical top and bottom frustum extents.
  37975. // Use the left camera for these values.
  37976. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  37977. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  37978. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  37979. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  37980. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  37981. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  37982. const left = near * leftFov;
  37983. const right = near * rightFov;
  37984. // Calculate the new camera's position offset from the
  37985. // left camera. xOffset should be roughly half `ipd`.
  37986. const zOffset = ipd / ( - leftFov + rightFov );
  37987. const xOffset = zOffset * - leftFov;
  37988. // TODO: Better way to apply this offset?
  37989. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  37990. camera.translateX( xOffset );
  37991. camera.translateZ( zOffset );
  37992. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  37993. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  37994. // Check if the projection uses an infinite far plane.
  37995. if ( projL[ 10 ] === -1 ) {
  37996. // Use the projection matrix from the left eye.
  37997. // The camera offset is sufficient to include the view volumes
  37998. // of both eyes (assuming symmetric projections).
  37999. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  38000. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  38001. } else {
  38002. // Find the union of the frustum values of the cameras and scale
  38003. // the values so that the near plane's position does not change in world space,
  38004. // although must now be relative to the new union camera.
  38005. const near2 = near + zOffset;
  38006. const far2 = far + zOffset;
  38007. const left2 = left - xOffset;
  38008. const right2 = right + ( ipd - xOffset );
  38009. const top2 = topFov * far / far2 * near2;
  38010. const bottom2 = bottomFov * far / far2 * near2;
  38011. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  38012. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38013. }
  38014. }
  38015. /**
  38016. * Updates the world matrices for the given camera based on the parent 3D object.
  38017. *
  38018. * @inner
  38019. * @param {Camera} camera - The camera to update.
  38020. * @param {Object3D} parent - The parent 3D object.
  38021. */
  38022. function updateCamera( camera, parent ) {
  38023. if ( parent === null ) {
  38024. camera.matrixWorld.copy( camera.matrix );
  38025. } else {
  38026. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  38027. }
  38028. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38029. }
  38030. /**
  38031. * Updates the given camera with the transformation of the XR camera and parent object.
  38032. *
  38033. * @inner
  38034. * @param {Camera} camera - The camera to update.
  38035. * @param {ArrayCamera} cameraXR - The XR camera.
  38036. * @param {Object3D} parent - The parent 3D object.
  38037. */
  38038. function updateUserCamera( camera, cameraXR, parent ) {
  38039. if ( parent === null ) {
  38040. camera.matrix.copy( cameraXR.matrixWorld );
  38041. } else {
  38042. camera.matrix.copy( parent.matrixWorld );
  38043. camera.matrix.invert();
  38044. camera.matrix.multiply( cameraXR.matrixWorld );
  38045. }
  38046. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38047. camera.updateMatrixWorld( true );
  38048. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  38049. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  38050. if ( camera.isPerspectiveCamera ) {
  38051. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  38052. camera.zoom = 1;
  38053. }
  38054. }
  38055. function onSessionEvent( event ) {
  38056. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  38057. if ( controllerIndex === -1 ) {
  38058. return;
  38059. }
  38060. const controller = this._controllers[ controllerIndex ];
  38061. if ( controller !== undefined ) {
  38062. const referenceSpace = this.getReferenceSpace();
  38063. controller.update( event.inputSource, event.frame, referenceSpace );
  38064. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  38065. }
  38066. }
  38067. function onSessionEnd() {
  38068. const session = this._session;
  38069. const renderer = this._renderer;
  38070. session.removeEventListener( 'select', this._onSessionEvent );
  38071. session.removeEventListener( 'selectstart', this._onSessionEvent );
  38072. session.removeEventListener( 'selectend', this._onSessionEvent );
  38073. session.removeEventListener( 'squeeze', this._onSessionEvent );
  38074. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  38075. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  38076. session.removeEventListener( 'end', this._onSessionEnd );
  38077. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38078. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38079. const inputSource = this._controllerInputSources[ i ];
  38080. if ( inputSource === null ) continue;
  38081. this._controllerInputSources[ i ] = null;
  38082. this._controllers[ i ].disconnect( inputSource );
  38083. }
  38084. this._currentDepthNear = null;
  38085. this._currentDepthFar = null;
  38086. // restore framebuffer/rendering state
  38087. renderer._resetXRState();
  38088. this._session = null;
  38089. this._xrRenderTarget = null;
  38090. // switch layers back to emulated
  38091. if ( this._sessionUsesLayers === true ) {
  38092. for ( const layer of this._layers ) {
  38093. // Recreate layer render target to reset state
  38094. layer.renderTarget = new XRRenderTarget(
  38095. layer.pixelwidth,
  38096. layer.pixelheight,
  38097. {
  38098. format: RGBAFormat,
  38099. type: UnsignedByteType,
  38100. depthTexture: new DepthTexture(
  38101. layer.pixelwidth,
  38102. layer.pixelheight,
  38103. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  38104. undefined,
  38105. undefined,
  38106. undefined,
  38107. undefined,
  38108. undefined,
  38109. undefined,
  38110. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  38111. ),
  38112. stencilBuffer: layer.stencilBuffer,
  38113. resolveDepthBuffer: false,
  38114. resolveStencilBuffer: false
  38115. } );
  38116. layer.renderTarget.isXRRenderTarget = false;
  38117. layer.plane.material = layer.material;
  38118. layer.material.map = layer.renderTarget.texture;
  38119. layer.material.map.offset.y = 1;
  38120. layer.material.map.repeat.y = -1;
  38121. delete layer.xrlayer;
  38122. }
  38123. }
  38124. //
  38125. this.isPresenting = false;
  38126. this._useMultiview = false;
  38127. renderer._animation.stop();
  38128. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  38129. renderer._animation.setContext( this._currentAnimationContext );
  38130. renderer._animation.start();
  38131. renderer.setPixelRatio( this._currentPixelRatio );
  38132. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  38133. this.dispatchEvent( { type: 'sessionend' } );
  38134. }
  38135. function onInputSourcesChange( event ) {
  38136. const controllers = this._controllers;
  38137. const controllerInputSources = this._controllerInputSources;
  38138. // Notify disconnected
  38139. for ( let i = 0; i < event.removed.length; i ++ ) {
  38140. const inputSource = event.removed[ i ];
  38141. const index = controllerInputSources.indexOf( inputSource );
  38142. if ( index >= 0 ) {
  38143. controllerInputSources[ index ] = null;
  38144. controllers[ index ].disconnect( inputSource );
  38145. }
  38146. }
  38147. // Notify connected
  38148. for ( let i = 0; i < event.added.length; i ++ ) {
  38149. const inputSource = event.added[ i ];
  38150. let controllerIndex = controllerInputSources.indexOf( inputSource );
  38151. if ( controllerIndex === -1 ) {
  38152. // Assign input source a controller that currently has no input source
  38153. for ( let i = 0; i < controllers.length; i ++ ) {
  38154. if ( i >= controllerInputSources.length ) {
  38155. controllerInputSources.push( inputSource );
  38156. controllerIndex = i;
  38157. break;
  38158. } else if ( controllerInputSources[ i ] === null ) {
  38159. controllerInputSources[ i ] = inputSource;
  38160. controllerIndex = i;
  38161. break;
  38162. }
  38163. }
  38164. // If all controllers do currently receive input we ignore new ones
  38165. if ( controllerIndex === -1 ) break;
  38166. }
  38167. const controller = controllers[ controllerIndex ];
  38168. if ( controller ) {
  38169. controller.connect( inputSource );
  38170. }
  38171. }
  38172. }
  38173. // Creation method for native WebXR layers
  38174. function createXRLayer( layer ) {
  38175. if ( layer.type === 'quad' ) {
  38176. return this._glBinding.createQuadLayer( {
  38177. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38178. width: layer.width / 2,
  38179. height: layer.height / 2,
  38180. space: this._referenceSpace,
  38181. viewPixelWidth: layer.pixelwidth,
  38182. viewPixelHeight: layer.pixelheight,
  38183. clearOnAccess: false
  38184. } );
  38185. } else {
  38186. return this._glBinding.createCylinderLayer( {
  38187. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38188. radius: layer.radius,
  38189. centralAngle: layer.centralAngle,
  38190. aspectRatio: layer.aspectRatio,
  38191. space: this._referenceSpace,
  38192. viewPixelWidth: layer.pixelwidth,
  38193. viewPixelHeight: layer.pixelheight,
  38194. clearOnAccess: false
  38195. } );
  38196. }
  38197. }
  38198. // Animation Loop
  38199. function onAnimationFrame( time, frame ) {
  38200. if ( frame === undefined ) return;
  38201. const cameraXR = this._cameraXR;
  38202. const renderer = this._renderer;
  38203. const backend = renderer.backend;
  38204. const glBaseLayer = this._glBaseLayer;
  38205. const referenceSpace = this.getReferenceSpace();
  38206. const pose = frame.getViewerPose( referenceSpace );
  38207. this._xrFrame = frame;
  38208. if ( pose !== null ) {
  38209. const views = pose.views;
  38210. if ( this._glBaseLayer !== null ) {
  38211. backend.setXRTarget( glBaseLayer.framebuffer );
  38212. }
  38213. let cameraXRNeedsUpdate = false;
  38214. // check if it's necessary to rebuild cameraXR's camera list
  38215. if ( views.length !== cameraXR.cameras.length ) {
  38216. cameraXR.cameras.length = 0;
  38217. cameraXRNeedsUpdate = true;
  38218. }
  38219. for ( let i = 0; i < views.length; i ++ ) {
  38220. const view = views[ i ];
  38221. let viewport;
  38222. if ( this._supportsLayers === true ) {
  38223. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  38224. viewport = glSubImage.viewport;
  38225. // For side-by-side projection, we only produce a single texture for both eyes.
  38226. if ( i === 0 ) {
  38227. backend.setXRRenderTargetTextures(
  38228. this._xrRenderTarget,
  38229. glSubImage.colorTexture,
  38230. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  38231. );
  38232. }
  38233. } else {
  38234. viewport = glBaseLayer.getViewport( view );
  38235. }
  38236. let camera = this._cameras[ i ];
  38237. if ( camera === undefined ) {
  38238. camera = new PerspectiveCamera();
  38239. camera.layers.enable( i );
  38240. camera.viewport = new Vector4();
  38241. this._cameras[ i ] = camera;
  38242. }
  38243. camera.matrix.fromArray( view.transform.matrix );
  38244. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38245. camera.projectionMatrix.fromArray( view.projectionMatrix );
  38246. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38247. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  38248. if ( i === 0 ) {
  38249. cameraXR.matrix.copy( camera.matrix );
  38250. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  38251. }
  38252. if ( cameraXRNeedsUpdate === true ) {
  38253. cameraXR.cameras.push( camera );
  38254. }
  38255. }
  38256. renderer.setOutputRenderTarget( this._xrRenderTarget );
  38257. }
  38258. //
  38259. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38260. const inputSource = this._controllerInputSources[ i ];
  38261. const controller = this._controllers[ i ];
  38262. if ( inputSource !== null && controller !== undefined ) {
  38263. controller.update( inputSource, frame, referenceSpace );
  38264. }
  38265. }
  38266. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  38267. if ( frame.detectedPlanes ) {
  38268. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  38269. }
  38270. this._xrFrame = null;
  38271. }
  38272. const _scene = /*@__PURE__*/ new Scene();
  38273. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  38274. const _screen = /*@__PURE__*/ new Vector4();
  38275. const _frustum = /*@__PURE__*/ new Frustum();
  38276. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  38277. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  38278. const _vector4 = /*@__PURE__*/ new Vector4();
  38279. /**
  38280. * Base class for renderers.
  38281. */
  38282. class Renderer {
  38283. /**
  38284. * Renderer options.
  38285. *
  38286. * @typedef {Object} Renderer~Options
  38287. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  38288. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  38289. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  38290. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  38291. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  38292. * @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
  38293. * to overwrite the default.
  38294. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  38295. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  38296. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  38297. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  38298. */
  38299. /**
  38300. * Constructs a new renderer.
  38301. *
  38302. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  38303. * @param {Renderer~Options} [parameters] - The configuration parameter.
  38304. */
  38305. constructor( backend, parameters = {} ) {
  38306. /**
  38307. * This flag can be used for type testing.
  38308. *
  38309. * @type {boolean}
  38310. * @readonly
  38311. * @default true
  38312. */
  38313. this.isRenderer = true;
  38314. //
  38315. const {
  38316. logarithmicDepthBuffer = false,
  38317. alpha = true,
  38318. depth = true,
  38319. stencil = false,
  38320. antialias = false,
  38321. samples = 0,
  38322. getFallback = null,
  38323. colorBufferType = HalfFloatType,
  38324. multiview = false
  38325. } = parameters;
  38326. /**
  38327. * A reference to the canvas element the renderer is drawing to.
  38328. * This value of this property will automatically be created by
  38329. * the renderer.
  38330. *
  38331. * @type {HTMLCanvasElement|OffscreenCanvas}
  38332. */
  38333. this.domElement = backend.getDomElement();
  38334. /**
  38335. * A reference to the current backend.
  38336. *
  38337. * @type {Backend}
  38338. */
  38339. this.backend = backend;
  38340. /**
  38341. * The number of MSAA samples.
  38342. *
  38343. * @type {number}
  38344. * @default 0
  38345. */
  38346. this.samples = samples || ( antialias === true ) ? 4 : 0;
  38347. /**
  38348. * Whether the renderer should automatically clear the current rendering target
  38349. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  38350. * or the current bound render target (custom framebuffer).
  38351. *
  38352. * @type {boolean}
  38353. * @default true
  38354. */
  38355. this.autoClear = true;
  38356. /**
  38357. * When `autoClear` is set to `true`, this property defines whether the renderer
  38358. * should clear the color buffer.
  38359. *
  38360. * @type {boolean}
  38361. * @default true
  38362. */
  38363. this.autoClearColor = true;
  38364. /**
  38365. * When `autoClear` is set to `true`, this property defines whether the renderer
  38366. * should clear the depth buffer.
  38367. *
  38368. * @type {boolean}
  38369. * @default true
  38370. */
  38371. this.autoClearDepth = true;
  38372. /**
  38373. * When `autoClear` is set to `true`, this property defines whether the renderer
  38374. * should clear the stencil buffer.
  38375. *
  38376. * @type {boolean}
  38377. * @default true
  38378. */
  38379. this.autoClearStencil = true;
  38380. /**
  38381. * Whether the default framebuffer should be transparent or opaque.
  38382. *
  38383. * @type {boolean}
  38384. * @default true
  38385. */
  38386. this.alpha = alpha;
  38387. /**
  38388. * Whether logarithmic depth buffer is enabled or not.
  38389. *
  38390. * @type {boolean}
  38391. * @default false
  38392. */
  38393. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  38394. /**
  38395. * Defines the output color space of the renderer.
  38396. *
  38397. * @type {string}
  38398. * @default SRGBColorSpace
  38399. */
  38400. this.outputColorSpace = SRGBColorSpace;
  38401. /**
  38402. * Defines the tone mapping of the renderer.
  38403. *
  38404. * @type {number}
  38405. * @default NoToneMapping
  38406. */
  38407. this.toneMapping = NoToneMapping;
  38408. /**
  38409. * Defines the tone mapping exposure.
  38410. *
  38411. * @type {number}
  38412. * @default 1
  38413. */
  38414. this.toneMappingExposure = 1.0;
  38415. /**
  38416. * Whether the renderer should sort its render lists or not.
  38417. *
  38418. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  38419. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  38420. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  38421. * e.g. manually determining each object's rendering order.
  38422. *
  38423. * @type {boolean}
  38424. * @default true
  38425. */
  38426. this.sortObjects = true;
  38427. /**
  38428. * Whether the default framebuffer should have a depth buffer or not.
  38429. *
  38430. * @type {boolean}
  38431. * @default true
  38432. */
  38433. this.depth = depth;
  38434. /**
  38435. * Whether the default framebuffer should have a stencil buffer or not.
  38436. *
  38437. * @type {boolean}
  38438. * @default false
  38439. */
  38440. this.stencil = stencil;
  38441. /**
  38442. * Holds a series of statistical information about the GPU memory
  38443. * and the rendering process. Useful for debugging and monitoring.
  38444. *
  38445. * @type {Info}
  38446. */
  38447. this.info = new Info();
  38448. /**
  38449. * Stores override nodes for specific transformations or calculations.
  38450. * These nodes can be used to replace default behavior in the rendering pipeline.
  38451. *
  38452. * @type {Object}
  38453. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  38454. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  38455. */
  38456. this.overrideNodes = {
  38457. modelViewMatrix: null,
  38458. modelNormalViewMatrix: null
  38459. };
  38460. /**
  38461. * The node library defines how certain library objects like materials, lights
  38462. * or tone mapping functions are mapped to node types. This is required since
  38463. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  38464. * be part of the scene graph, they are internally represented as nodes for
  38465. * further processing.
  38466. *
  38467. * @type {NodeLibrary}
  38468. */
  38469. this.library = new NodeLibrary();
  38470. /**
  38471. * A map-like data structure for managing lights.
  38472. *
  38473. * @type {Lighting}
  38474. */
  38475. this.lighting = new Lighting();
  38476. // internals
  38477. /**
  38478. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  38479. *
  38480. * @private
  38481. * @type {?Function}
  38482. */
  38483. this._getFallback = getFallback;
  38484. /**
  38485. * The renderer's pixel ratio.
  38486. *
  38487. * @private
  38488. * @type {number}
  38489. * @default 1
  38490. */
  38491. this._pixelRatio = 1;
  38492. /**
  38493. * The width of the renderer's default framebuffer in logical pixel unit.
  38494. *
  38495. * @private
  38496. * @type {number}
  38497. */
  38498. this._width = this.domElement.width;
  38499. /**
  38500. * The height of the renderer's default framebuffer in logical pixel unit.
  38501. *
  38502. * @private
  38503. * @type {number}
  38504. */
  38505. this._height = this.domElement.height;
  38506. /**
  38507. * The viewport of the renderer in logical pixel unit.
  38508. *
  38509. * @private
  38510. * @type {Vector4}
  38511. */
  38512. this._viewport = new Vector4( 0, 0, this._width, this._height );
  38513. /**
  38514. * The scissor rectangle of the renderer in logical pixel unit.
  38515. *
  38516. * @private
  38517. * @type {Vector4}
  38518. */
  38519. this._scissor = new Vector4( 0, 0, this._width, this._height );
  38520. /**
  38521. * Whether the scissor test should be enabled or not.
  38522. *
  38523. * @private
  38524. * @type {boolean}
  38525. */
  38526. this._scissorTest = false;
  38527. /**
  38528. * A reference to a renderer module for managing shader attributes.
  38529. *
  38530. * @private
  38531. * @type {?Attributes}
  38532. * @default null
  38533. */
  38534. this._attributes = null;
  38535. /**
  38536. * A reference to a renderer module for managing geometries.
  38537. *
  38538. * @private
  38539. * @type {?Geometries}
  38540. * @default null
  38541. */
  38542. this._geometries = null;
  38543. /**
  38544. * A reference to a renderer module for managing node related logic.
  38545. *
  38546. * @private
  38547. * @type {?Nodes}
  38548. * @default null
  38549. */
  38550. this._nodes = null;
  38551. /**
  38552. * A reference to a renderer module for managing the internal animation loop.
  38553. *
  38554. * @private
  38555. * @type {?Animation}
  38556. * @default null
  38557. */
  38558. this._animation = null;
  38559. /**
  38560. * A reference to a renderer module for managing shader program bindings.
  38561. *
  38562. * @private
  38563. * @type {?Bindings}
  38564. * @default null
  38565. */
  38566. this._bindings = null;
  38567. /**
  38568. * A reference to a renderer module for managing render objects.
  38569. *
  38570. * @private
  38571. * @type {?RenderObjects}
  38572. * @default null
  38573. */
  38574. this._objects = null;
  38575. /**
  38576. * A reference to a renderer module for managing render and compute pipelines.
  38577. *
  38578. * @private
  38579. * @type {?Pipelines}
  38580. * @default null
  38581. */
  38582. this._pipelines = null;
  38583. /**
  38584. * A reference to a renderer module for managing render bundles.
  38585. *
  38586. * @private
  38587. * @type {?RenderBundles}
  38588. * @default null
  38589. */
  38590. this._bundles = null;
  38591. /**
  38592. * A reference to a renderer module for managing render lists.
  38593. *
  38594. * @private
  38595. * @type {?RenderLists}
  38596. * @default null
  38597. */
  38598. this._renderLists = null;
  38599. /**
  38600. * A reference to a renderer module for managing render contexts.
  38601. *
  38602. * @private
  38603. * @type {?RenderContexts}
  38604. * @default null
  38605. */
  38606. this._renderContexts = null;
  38607. /**
  38608. * A reference to a renderer module for managing textures.
  38609. *
  38610. * @private
  38611. * @type {?Textures}
  38612. * @default null
  38613. */
  38614. this._textures = null;
  38615. /**
  38616. * A reference to a renderer module for backgrounds.
  38617. *
  38618. * @private
  38619. * @type {?Background}
  38620. * @default null
  38621. */
  38622. this._background = null;
  38623. /**
  38624. * This fullscreen quad is used for internal render passes
  38625. * like the tone mapping and color space output pass.
  38626. *
  38627. * @private
  38628. * @type {QuadMesh}
  38629. */
  38630. this._quad = new QuadMesh( new NodeMaterial() );
  38631. this._quad.material.name = 'Renderer_output';
  38632. /**
  38633. * A reference to the current render context.
  38634. *
  38635. * @private
  38636. * @type {?RenderContext}
  38637. * @default null
  38638. */
  38639. this._currentRenderContext = null;
  38640. /**
  38641. * A custom sort function for the opaque render list.
  38642. *
  38643. * @private
  38644. * @type {?Function}
  38645. * @default null
  38646. */
  38647. this._opaqueSort = null;
  38648. /**
  38649. * A custom sort function for the transparent render list.
  38650. *
  38651. * @private
  38652. * @type {?Function}
  38653. * @default null
  38654. */
  38655. this._transparentSort = null;
  38656. /**
  38657. * The framebuffer target.
  38658. *
  38659. * @private
  38660. * @type {?RenderTarget}
  38661. * @default null
  38662. */
  38663. this._frameBufferTarget = null;
  38664. const alphaClear = this.alpha === true ? 0 : 1;
  38665. /**
  38666. * The clear color value.
  38667. *
  38668. * @private
  38669. * @type {Color4}
  38670. */
  38671. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  38672. /**
  38673. * The clear depth value.
  38674. *
  38675. * @private
  38676. * @type {number}
  38677. * @default 1
  38678. */
  38679. this._clearDepth = 1;
  38680. /**
  38681. * The clear stencil value.
  38682. *
  38683. * @private
  38684. * @type {number}
  38685. * @default 0
  38686. */
  38687. this._clearStencil = 0;
  38688. /**
  38689. * The current render target.
  38690. *
  38691. * @private
  38692. * @type {?RenderTarget}
  38693. * @default null
  38694. */
  38695. this._renderTarget = null;
  38696. /**
  38697. * The active cube face.
  38698. *
  38699. * @private
  38700. * @type {number}
  38701. * @default 0
  38702. */
  38703. this._activeCubeFace = 0;
  38704. /**
  38705. * The active mipmap level.
  38706. *
  38707. * @private
  38708. * @type {number}
  38709. * @default 0
  38710. */
  38711. this._activeMipmapLevel = 0;
  38712. /**
  38713. * The current output render target.
  38714. *
  38715. * @private
  38716. * @type {?RenderTarget}
  38717. * @default null
  38718. */
  38719. this._outputRenderTarget = null;
  38720. /**
  38721. * The MRT setting.
  38722. *
  38723. * @private
  38724. * @type {?MRTNode}
  38725. * @default null
  38726. */
  38727. this._mrt = null;
  38728. /**
  38729. * This function defines how a render object is going
  38730. * to be rendered.
  38731. *
  38732. * @private
  38733. * @type {?Function}
  38734. * @default null
  38735. */
  38736. this._renderObjectFunction = null;
  38737. /**
  38738. * Used to keep track of the current render object function.
  38739. *
  38740. * @private
  38741. * @type {?Function}
  38742. * @default null
  38743. */
  38744. this._currentRenderObjectFunction = null;
  38745. /**
  38746. * Used to keep track of the current render bundle.
  38747. *
  38748. * @private
  38749. * @type {?RenderBundle}
  38750. * @default null
  38751. */
  38752. this._currentRenderBundle = null;
  38753. /**
  38754. * Next to `_renderObjectFunction()`, this function provides another hook
  38755. * for influencing the render process of a render object. It is meant for internal
  38756. * use and only relevant for `compileAsync()` right now. Instead of using
  38757. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  38758. * a different function might be used which performs no draw but just the node
  38759. * and pipeline updates.
  38760. *
  38761. * @private
  38762. * @type {?Function}
  38763. * @default null
  38764. */
  38765. this._handleObjectFunction = this._renderObjectDirect;
  38766. /**
  38767. * Indicates whether the device has been lost or not. In WebGL terms, the device
  38768. * lost is considered as a context lost. When this is set to `true`, rendering
  38769. * isn't possible anymore.
  38770. *
  38771. * @private
  38772. * @type {boolean}
  38773. * @default false
  38774. */
  38775. this._isDeviceLost = false;
  38776. /**
  38777. * A callback function that defines what should happen when a device/context lost occurs.
  38778. *
  38779. * @type {Function}
  38780. */
  38781. this.onDeviceLost = this._onDeviceLost;
  38782. /**
  38783. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  38784. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  38785. * This will reduce rendering quality though.
  38786. *
  38787. * @private
  38788. * @type {number}
  38789. * @default HalfFloatType
  38790. */
  38791. this._colorBufferType = colorBufferType;
  38792. /**
  38793. * Whether the renderer has been initialized or not.
  38794. *
  38795. * @private
  38796. * @type {boolean}
  38797. * @default false
  38798. */
  38799. this._initialized = false;
  38800. /**
  38801. * A reference to the promise which initializes the renderer.
  38802. *
  38803. * @private
  38804. * @type {?Promise<this>}
  38805. * @default null
  38806. */
  38807. this._initPromise = null;
  38808. /**
  38809. * An array of compilation promises which are used in `compileAsync()`.
  38810. *
  38811. * @private
  38812. * @type {?Array<Promise>}
  38813. * @default null
  38814. */
  38815. this._compilationPromises = null;
  38816. /**
  38817. * Whether the renderer should render transparent render objects or not.
  38818. *
  38819. * @type {boolean}
  38820. * @default true
  38821. */
  38822. this.transparent = true;
  38823. /**
  38824. * Whether the renderer should render opaque render objects or not.
  38825. *
  38826. * @type {boolean}
  38827. * @default true
  38828. */
  38829. this.opaque = true;
  38830. /**
  38831. * Shadow map configuration
  38832. * @typedef {Object} ShadowMapConfig
  38833. * @property {boolean} enabled - Whether to globally enable shadows or not.
  38834. * @property {number} type - The shadow map type.
  38835. */
  38836. /**
  38837. * The renderer's shadow configuration.
  38838. *
  38839. * @type {ShadowMapConfig}
  38840. */
  38841. this.shadowMap = {
  38842. enabled: false,
  38843. type: PCFShadowMap
  38844. };
  38845. /**
  38846. * XR configuration.
  38847. * @typedef {Object} XRConfig
  38848. * @property {boolean} enabled - Whether to globally enable XR or not.
  38849. */
  38850. /**
  38851. * The renderer's XR manager.
  38852. *
  38853. * @type {XRManager}
  38854. */
  38855. this.xr = new XRManager( this, multiview );
  38856. /**
  38857. * Debug configuration.
  38858. * @typedef {Object} DebugConfig
  38859. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  38860. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  38861. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  38862. */
  38863. /**
  38864. * The renderer's debug configuration.
  38865. *
  38866. * @type {DebugConfig}
  38867. */
  38868. this.debug = {
  38869. checkShaderErrors: true,
  38870. onShaderError: null,
  38871. getShaderAsync: async ( scene, camera, object ) => {
  38872. await this.compileAsync( scene, camera );
  38873. const renderList = this._renderLists.get( scene, camera );
  38874. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  38875. const material = scene.overrideMaterial || object.material;
  38876. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  38877. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  38878. return { fragmentShader, vertexShader };
  38879. }
  38880. };
  38881. }
  38882. /**
  38883. * Initializes the renderer so it is ready for usage.
  38884. *
  38885. * @async
  38886. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  38887. */
  38888. async init() {
  38889. if ( this._initialized ) {
  38890. throw new Error( 'Renderer: Backend has already been initialized.' );
  38891. }
  38892. if ( this._initPromise !== null ) {
  38893. return this._initPromise;
  38894. }
  38895. this._initPromise = new Promise( async ( resolve, reject ) => {
  38896. let backend = this.backend;
  38897. try {
  38898. await backend.init( this );
  38899. } catch ( error ) {
  38900. if ( this._getFallback !== null ) {
  38901. // try the fallback
  38902. try {
  38903. this.backend = backend = this._getFallback( error );
  38904. await backend.init( this );
  38905. } catch ( error ) {
  38906. reject( error );
  38907. return;
  38908. }
  38909. } else {
  38910. reject( error );
  38911. return;
  38912. }
  38913. }
  38914. this._nodes = new Nodes( this, backend );
  38915. this._animation = new Animation( this._nodes, this.info );
  38916. this._attributes = new Attributes( backend );
  38917. this._background = new Background( this, this._nodes );
  38918. this._geometries = new Geometries( this._attributes, this.info );
  38919. this._textures = new Textures( this, backend, this.info );
  38920. this._pipelines = new Pipelines( backend, this._nodes );
  38921. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  38922. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  38923. this._renderLists = new RenderLists( this.lighting );
  38924. this._bundles = new RenderBundles();
  38925. this._renderContexts = new RenderContexts();
  38926. //
  38927. this._animation.start();
  38928. this._initialized = true;
  38929. resolve( this );
  38930. } );
  38931. return this._initPromise;
  38932. }
  38933. /**
  38934. * The coordinate system of the renderer. The value of this property
  38935. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  38936. * `THREE.WebGPUCoordinateSystem`.
  38937. *
  38938. * @readonly
  38939. * @type {number}
  38940. */
  38941. get coordinateSystem() {
  38942. return this.backend.coordinateSystem;
  38943. }
  38944. /**
  38945. * Compiles all materials in the given scene. This can be useful to avoid a
  38946. * phenomenon which is called "shader compilation stutter", which occurs when
  38947. * rendering an object with a new shader for the first time.
  38948. *
  38949. * If you want to add a 3D object to an existing scene, use the third optional
  38950. * parameter for applying the target scene. Note that the (target) scene's lighting
  38951. * and environment must be configured before calling this method.
  38952. *
  38953. * @async
  38954. * @param {Object3D} scene - The scene or 3D object to precompile.
  38955. * @param {Camera} camera - The camera that is used to render the scene.
  38956. * @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.
  38957. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  38958. */
  38959. async compileAsync( scene, camera, targetScene = null ) {
  38960. if ( this._isDeviceLost === true ) return;
  38961. if ( this._initialized === false ) await this.init();
  38962. // preserve render tree
  38963. const nodeFrame = this._nodes.nodeFrame;
  38964. const previousRenderId = nodeFrame.renderId;
  38965. const previousRenderContext = this._currentRenderContext;
  38966. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38967. const previousCompilationPromises = this._compilationPromises;
  38968. //
  38969. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38970. if ( targetScene === null ) targetScene = scene;
  38971. const renderTarget = this._renderTarget;
  38972. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  38973. const activeMipmapLevel = this._activeMipmapLevel;
  38974. const compilationPromises = [];
  38975. this._currentRenderContext = renderContext;
  38976. this._currentRenderObjectFunction = this.renderObject;
  38977. this._handleObjectFunction = this._createObjectPipeline;
  38978. this._compilationPromises = compilationPromises;
  38979. nodeFrame.renderId ++;
  38980. //
  38981. nodeFrame.update();
  38982. //
  38983. renderContext.depth = this.depth;
  38984. renderContext.stencil = this.stencil;
  38985. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38986. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  38987. //
  38988. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38989. //
  38990. const renderList = this._renderLists.get( scene, camera );
  38991. renderList.begin();
  38992. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  38993. // include lights from target scene
  38994. if ( targetScene !== scene ) {
  38995. targetScene.traverseVisible( function ( object ) {
  38996. if ( object.isLight && object.layers.test( camera.layers ) ) {
  38997. renderList.pushLight( object );
  38998. }
  38999. } );
  39000. }
  39001. renderList.finish();
  39002. //
  39003. if ( renderTarget !== null ) {
  39004. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  39005. const renderTargetData = this._textures.get( renderTarget );
  39006. renderContext.textures = renderTargetData.textures;
  39007. renderContext.depthTexture = renderTargetData.depthTexture;
  39008. } else {
  39009. renderContext.textures = null;
  39010. renderContext.depthTexture = null;
  39011. }
  39012. //
  39013. this._background.update( sceneRef, renderList, renderContext );
  39014. // process render lists
  39015. const opaqueObjects = renderList.opaque;
  39016. const transparentObjects = renderList.transparent;
  39017. const transparentDoublePassObjects = renderList.transparentDoublePass;
  39018. const lightsNode = renderList.lightsNode;
  39019. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39020. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39021. // restore render tree
  39022. nodeFrame.renderId = previousRenderId;
  39023. this._currentRenderContext = previousRenderContext;
  39024. this._currentRenderObjectFunction = previousRenderObjectFunction;
  39025. this._compilationPromises = previousCompilationPromises;
  39026. this._handleObjectFunction = this._renderObjectDirect;
  39027. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  39028. await Promise.all( compilationPromises );
  39029. }
  39030. /**
  39031. * Renders the scene in an async fashion.
  39032. *
  39033. * @async
  39034. * @param {Object3D} scene - The scene or 3D object to render.
  39035. * @param {Camera} camera - The camera.
  39036. * @return {Promise} A Promise that resolves when the render has been finished.
  39037. */
  39038. async renderAsync( scene, camera ) {
  39039. if ( this._initialized === false ) await this.init();
  39040. this._renderScene( scene, camera );
  39041. }
  39042. /**
  39043. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  39044. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  39045. *
  39046. * @async
  39047. * @return {Promise} A Promise that resolves when synchronization has been finished.
  39048. */
  39049. async waitForGPU() {
  39050. await this.backend.waitForGPU();
  39051. }
  39052. /**
  39053. * Enables or disables high precision for model-view and normal-view matrices.
  39054. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  39055. *
  39056. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  39057. *
  39058. * @param {boolean} value - Whether to enable or disable high precision.
  39059. * @type {boolean}
  39060. */
  39061. set highPrecision( value ) {
  39062. if ( value === true ) {
  39063. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  39064. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  39065. } else if ( this.highPrecision ) {
  39066. this.overrideNodes.modelViewMatrix = null;
  39067. this.overrideNodes.modelNormalViewMatrix = null;
  39068. }
  39069. }
  39070. /**
  39071. * Returns whether high precision is enabled or not.
  39072. *
  39073. * @return {boolean} Whether high precision is enabled or not.
  39074. * @type {boolean}
  39075. */
  39076. get highPrecision() {
  39077. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  39078. }
  39079. /**
  39080. * Sets the given MRT configuration.
  39081. *
  39082. * @param {MRTNode} mrt - The MRT node to set.
  39083. * @return {Renderer} A reference to this renderer.
  39084. */
  39085. setMRT( mrt ) {
  39086. this._mrt = mrt;
  39087. return this;
  39088. }
  39089. /**
  39090. * Returns the MRT configuration.
  39091. *
  39092. * @return {MRTNode} The MRT configuration.
  39093. */
  39094. getMRT() {
  39095. return this._mrt;
  39096. }
  39097. /**
  39098. * Returns the color buffer type.
  39099. *
  39100. * @return {number} The color buffer type.
  39101. */
  39102. getColorBufferType() {
  39103. return this._colorBufferType;
  39104. }
  39105. /**
  39106. * Default implementation of the device lost callback.
  39107. *
  39108. * @private
  39109. * @param {Object} info - Information about the context lost.
  39110. */
  39111. _onDeviceLost( info ) {
  39112. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  39113. if ( info.reason ) {
  39114. errorMessage += `\nReason: ${info.reason}`;
  39115. }
  39116. console.error( errorMessage );
  39117. this._isDeviceLost = true;
  39118. }
  39119. /**
  39120. * Renders the given render bundle.
  39121. *
  39122. * @private
  39123. * @param {Object} bundle - Render bundle data.
  39124. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  39125. * @param {LightsNode} lightsNode - The lights node.
  39126. */
  39127. _renderBundle( bundle, sceneRef, lightsNode ) {
  39128. const { bundleGroup, camera, renderList } = bundle;
  39129. const renderContext = this._currentRenderContext;
  39130. //
  39131. const renderBundle = this._bundles.get( bundleGroup, camera );
  39132. const renderBundleData = this.backend.get( renderBundle );
  39133. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  39134. //
  39135. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  39136. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  39137. renderBundleData.renderContexts.add( renderContext );
  39138. if ( renderBundleNeedsUpdate ) {
  39139. this.backend.beginBundle( renderContext );
  39140. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  39141. renderBundleData.renderObjects = [];
  39142. }
  39143. this._currentRenderBundle = renderBundle;
  39144. const {
  39145. transparentDoublePass: transparentDoublePassObjects,
  39146. transparent: transparentObjects,
  39147. opaque: opaqueObjects
  39148. } = renderList;
  39149. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39150. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39151. this._currentRenderBundle = null;
  39152. //
  39153. this.backend.finishBundle( renderContext, renderBundle );
  39154. renderBundleData.version = bundleGroup.version;
  39155. } else {
  39156. const { renderObjects } = renderBundleData;
  39157. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  39158. const renderObject = renderObjects[ i ];
  39159. if ( this._nodes.needsRefresh( renderObject ) ) {
  39160. this._nodes.updateBefore( renderObject );
  39161. this._nodes.updateForRender( renderObject );
  39162. this._bindings.updateForRender( renderObject );
  39163. this._nodes.updateAfter( renderObject );
  39164. }
  39165. }
  39166. }
  39167. this.backend.addBundle( renderContext, renderBundle );
  39168. }
  39169. /**
  39170. * Renders the scene or 3D object with the given camera. This method can only be called
  39171. * if the renderer has been initialized.
  39172. *
  39173. * The target of the method is the default framebuffer (meaning the canvas)
  39174. * or alternatively a render target when specified via `setRenderTarget()`.
  39175. *
  39176. * @param {Object3D} scene - The scene or 3D object to render.
  39177. * @param {Camera} camera - The camera to render the scene with.
  39178. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  39179. * Only returned when the renderer has not been initialized.
  39180. */
  39181. render( scene, camera ) {
  39182. if ( this._initialized === false ) {
  39183. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  39184. return this.renderAsync( scene, camera );
  39185. }
  39186. this._renderScene( scene, camera );
  39187. }
  39188. /**
  39189. * Returns an internal render target which is used when computing the output tone mapping
  39190. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  39191. * pass and not inline to achieve more correct results.
  39192. *
  39193. * @private
  39194. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  39195. */
  39196. _getFrameBufferTarget() {
  39197. const { currentToneMapping, currentColorSpace } = this;
  39198. const useToneMapping = currentToneMapping !== NoToneMapping;
  39199. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  39200. if ( useToneMapping === false && useColorSpace === false ) return null;
  39201. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  39202. const { depth, stencil } = this;
  39203. let frameBufferTarget = this._frameBufferTarget;
  39204. if ( frameBufferTarget === null ) {
  39205. frameBufferTarget = new RenderTarget( width, height, {
  39206. depthBuffer: depth,
  39207. stencilBuffer: stencil,
  39208. type: this._colorBufferType,
  39209. format: RGBAFormat,
  39210. colorSpace: ColorManagement.workingColorSpace,
  39211. generateMipmaps: false,
  39212. minFilter: LinearFilter,
  39213. magFilter: LinearFilter,
  39214. samples: this.samples
  39215. } );
  39216. frameBufferTarget.isPostProcessingRenderTarget = true;
  39217. this._frameBufferTarget = frameBufferTarget;
  39218. }
  39219. const outputRenderTarget = this.getOutputRenderTarget();
  39220. frameBufferTarget.depthBuffer = depth;
  39221. frameBufferTarget.stencilBuffer = stencil;
  39222. if ( outputRenderTarget !== null ) {
  39223. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  39224. } else {
  39225. frameBufferTarget.setSize( width, height, 1 );
  39226. }
  39227. frameBufferTarget.viewport.copy( this._viewport );
  39228. frameBufferTarget.scissor.copy( this._scissor );
  39229. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  39230. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  39231. frameBufferTarget.scissorTest = this._scissorTest;
  39232. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  39233. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  39234. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  39235. return frameBufferTarget;
  39236. }
  39237. /**
  39238. * Renders the scene or 3D object with the given camera.
  39239. *
  39240. * @private
  39241. * @param {Object3D} scene - The scene or 3D object to render.
  39242. * @param {Camera} camera - The camera to render the scene with.
  39243. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  39244. * @return {RenderContext} The current render context.
  39245. */
  39246. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  39247. if ( this._isDeviceLost === true ) return;
  39248. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  39249. // preserve render tree
  39250. const nodeFrame = this._nodes.nodeFrame;
  39251. const previousRenderId = nodeFrame.renderId;
  39252. const previousRenderContext = this._currentRenderContext;
  39253. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  39254. //
  39255. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  39256. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  39257. const activeCubeFace = this._activeCubeFace;
  39258. const activeMipmapLevel = this._activeMipmapLevel;
  39259. //
  39260. let renderTarget;
  39261. if ( frameBufferTarget !== null ) {
  39262. renderTarget = frameBufferTarget;
  39263. this.setRenderTarget( renderTarget );
  39264. } else {
  39265. renderTarget = outputRenderTarget;
  39266. }
  39267. //
  39268. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  39269. this._currentRenderContext = renderContext;
  39270. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  39271. //
  39272. this.info.calls ++;
  39273. this.info.render.calls ++;
  39274. this.info.render.frameCalls ++;
  39275. nodeFrame.renderId = this.info.calls;
  39276. //
  39277. const coordinateSystem = this.coordinateSystem;
  39278. const xr = this.xr;
  39279. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  39280. camera.coordinateSystem = coordinateSystem;
  39281. camera.updateProjectionMatrix();
  39282. if ( camera.isArrayCamera ) {
  39283. for ( const subCamera of camera.cameras ) {
  39284. subCamera.coordinateSystem = coordinateSystem;
  39285. subCamera.updateProjectionMatrix();
  39286. }
  39287. }
  39288. }
  39289. //
  39290. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  39291. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  39292. if ( xr.enabled === true && xr.isPresenting === true ) {
  39293. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  39294. camera = xr.getCamera(); // use XR camera for rendering
  39295. }
  39296. //
  39297. let viewport = this._viewport;
  39298. let scissor = this._scissor;
  39299. let pixelRatio = this._pixelRatio;
  39300. if ( renderTarget !== null ) {
  39301. viewport = renderTarget.viewport;
  39302. scissor = renderTarget.scissor;
  39303. pixelRatio = 1;
  39304. }
  39305. this.getDrawingBufferSize( _drawingBufferSize );
  39306. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  39307. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  39308. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  39309. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  39310. renderContext.viewportValue.width >>= activeMipmapLevel;
  39311. renderContext.viewportValue.height >>= activeMipmapLevel;
  39312. renderContext.viewportValue.minDepth = minDepth;
  39313. renderContext.viewportValue.maxDepth = maxDepth;
  39314. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  39315. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  39316. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  39317. renderContext.scissorValue.width >>= activeMipmapLevel;
  39318. renderContext.scissorValue.height >>= activeMipmapLevel;
  39319. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  39320. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  39321. //
  39322. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  39323. //
  39324. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  39325. if ( ! camera.isArrayCamera ) {
  39326. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  39327. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  39328. }
  39329. const renderList = this._renderLists.get( scene, camera );
  39330. renderList.begin();
  39331. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  39332. renderList.finish();
  39333. if ( this.sortObjects === true ) {
  39334. renderList.sort( this._opaqueSort, this._transparentSort );
  39335. }
  39336. //
  39337. if ( renderTarget !== null ) {
  39338. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  39339. const renderTargetData = this._textures.get( renderTarget );
  39340. renderContext.textures = renderTargetData.textures;
  39341. renderContext.depthTexture = renderTargetData.depthTexture;
  39342. renderContext.width = renderTargetData.width;
  39343. renderContext.height = renderTargetData.height;
  39344. renderContext.renderTarget = renderTarget;
  39345. renderContext.depth = renderTarget.depthBuffer;
  39346. renderContext.stencil = renderTarget.stencilBuffer;
  39347. } else {
  39348. renderContext.textures = null;
  39349. renderContext.depthTexture = null;
  39350. renderContext.width = this.domElement.width;
  39351. renderContext.height = this.domElement.height;
  39352. renderContext.depth = this.depth;
  39353. renderContext.stencil = this.stencil;
  39354. }
  39355. renderContext.width >>= activeMipmapLevel;
  39356. renderContext.height >>= activeMipmapLevel;
  39357. renderContext.activeCubeFace = activeCubeFace;
  39358. renderContext.activeMipmapLevel = activeMipmapLevel;
  39359. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  39360. //
  39361. this._background.update( sceneRef, renderList, renderContext );
  39362. //
  39363. renderContext.camera = camera;
  39364. this.backend.beginRender( renderContext );
  39365. // process render lists
  39366. const {
  39367. bundles,
  39368. lightsNode,
  39369. transparentDoublePass: transparentDoublePassObjects,
  39370. transparent: transparentObjects,
  39371. opaque: opaqueObjects
  39372. } = renderList;
  39373. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  39374. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39375. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39376. // finish render pass
  39377. this.backend.finishRender( renderContext );
  39378. // restore render tree
  39379. nodeFrame.renderId = previousRenderId;
  39380. this._currentRenderContext = previousRenderContext;
  39381. this._currentRenderObjectFunction = previousRenderObjectFunction;
  39382. //
  39383. if ( frameBufferTarget !== null ) {
  39384. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  39385. this._renderOutput( renderTarget );
  39386. }
  39387. //
  39388. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  39389. //
  39390. return renderContext;
  39391. }
  39392. _setXRLayerSize( width, height ) {
  39393. this._width = width;
  39394. this._height = height;
  39395. this.setViewport( 0, 0, width, height );
  39396. }
  39397. /**
  39398. * The output pass performs tone mapping and color space conversion.
  39399. *
  39400. * @private
  39401. * @param {RenderTarget} renderTarget - The current render target.
  39402. */
  39403. _renderOutput( renderTarget ) {
  39404. const quad = this._quad;
  39405. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  39406. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  39407. quad.material.needsUpdate = true;
  39408. }
  39409. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  39410. const currentAutoClear = this.autoClear;
  39411. const currentXR = this.xr.enabled;
  39412. this.autoClear = false;
  39413. this.xr.enabled = false;
  39414. this._renderScene( quad, quad.camera, false );
  39415. this.autoClear = currentAutoClear;
  39416. this.xr.enabled = currentXR;
  39417. }
  39418. /**
  39419. * Returns the maximum available anisotropy for texture filtering.
  39420. *
  39421. * @return {number} The maximum available anisotropy.
  39422. */
  39423. getMaxAnisotropy() {
  39424. return this.backend.getMaxAnisotropy();
  39425. }
  39426. /**
  39427. * Returns the active cube face.
  39428. *
  39429. * @return {number} The active cube face.
  39430. */
  39431. getActiveCubeFace() {
  39432. return this._activeCubeFace;
  39433. }
  39434. /**
  39435. * Returns the active mipmap level.
  39436. *
  39437. * @return {number} The active mipmap level.
  39438. */
  39439. getActiveMipmapLevel() {
  39440. return this._activeMipmapLevel;
  39441. }
  39442. /**
  39443. * Applications are advised to always define the animation loop
  39444. * with this method and not manually with `requestAnimationFrame()`
  39445. * for best compatibility.
  39446. *
  39447. * @async
  39448. * @param {?Function} callback - The application's animation loop.
  39449. * @return {Promise} A Promise that resolves when the set has been executed.
  39450. */
  39451. async setAnimationLoop( callback ) {
  39452. if ( this._initialized === false ) await this.init();
  39453. this._animation.setAnimationLoop( callback );
  39454. }
  39455. /**
  39456. * Can be used to transfer buffer data from a storage buffer attribute
  39457. * from the GPU to the CPU in context of compute shaders.
  39458. *
  39459. * @async
  39460. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39461. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39462. */
  39463. async getArrayBufferAsync( attribute ) {
  39464. return await this.backend.getArrayBufferAsync( attribute );
  39465. }
  39466. /**
  39467. * Returns the rendering context.
  39468. *
  39469. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  39470. */
  39471. getContext() {
  39472. return this.backend.getContext();
  39473. }
  39474. /**
  39475. * Returns the pixel ratio.
  39476. *
  39477. * @return {number} The pixel ratio.
  39478. */
  39479. getPixelRatio() {
  39480. return this._pixelRatio;
  39481. }
  39482. /**
  39483. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39484. *
  39485. * @param {Vector2} target - The method writes the result in this target object.
  39486. * @return {Vector2} The drawing buffer size.
  39487. */
  39488. getDrawingBufferSize( target ) {
  39489. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39490. }
  39491. /**
  39492. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39493. *
  39494. * @param {Vector2} target - The method writes the result in this target object.
  39495. * @return {Vector2} The renderer's size in logical pixels.
  39496. */
  39497. getSize( target ) {
  39498. return target.set( this._width, this._height );
  39499. }
  39500. /**
  39501. * Sets the given pixel ratio and resizes the canvas if necessary.
  39502. *
  39503. * @param {number} [value=1] - The pixel ratio.
  39504. */
  39505. setPixelRatio( value = 1 ) {
  39506. if ( this._pixelRatio === value ) return;
  39507. this._pixelRatio = value;
  39508. this.setSize( this._width, this._height, false );
  39509. }
  39510. /**
  39511. * This method allows to define the drawing buffer size by specifying
  39512. * width, height and pixel ratio all at once. The size of the drawing
  39513. * buffer is computed with this formula:
  39514. * ```js
  39515. * size.x = width * pixelRatio;
  39516. * size.y = height * pixelRatio;
  39517. * ```
  39518. *
  39519. * @param {number} width - The width in logical pixels.
  39520. * @param {number} height - The height in logical pixels.
  39521. * @param {number} pixelRatio - The pixel ratio.
  39522. */
  39523. setDrawingBufferSize( width, height, pixelRatio ) {
  39524. // Renderer can't be resized while presenting in XR.
  39525. if ( this.xr && this.xr.isPresenting ) return;
  39526. this._width = width;
  39527. this._height = height;
  39528. this._pixelRatio = pixelRatio;
  39529. this.domElement.width = Math.floor( width * pixelRatio );
  39530. this.domElement.height = Math.floor( height * pixelRatio );
  39531. this.setViewport( 0, 0, width, height );
  39532. if ( this._initialized ) this.backend.updateSize();
  39533. }
  39534. /**
  39535. * Sets the size of the renderer.
  39536. *
  39537. * @param {number} width - The width in logical pixels.
  39538. * @param {number} height - The height in logical pixels.
  39539. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39540. */
  39541. setSize( width, height, updateStyle = true ) {
  39542. // Renderer can't be resized while presenting in XR.
  39543. if ( this.xr && this.xr.isPresenting ) return;
  39544. this._width = width;
  39545. this._height = height;
  39546. this.domElement.width = Math.floor( width * this._pixelRatio );
  39547. this.domElement.height = Math.floor( height * this._pixelRatio );
  39548. if ( updateStyle === true ) {
  39549. this.domElement.style.width = width + 'px';
  39550. this.domElement.style.height = height + 'px';
  39551. }
  39552. this.setViewport( 0, 0, width, height );
  39553. if ( this._initialized ) this.backend.updateSize();
  39554. }
  39555. /**
  39556. * Defines a manual sort function for the opaque render list.
  39557. * Pass `null` to use the default sort.
  39558. *
  39559. * @param {Function} method - The sort function.
  39560. */
  39561. setOpaqueSort( method ) {
  39562. this._opaqueSort = method;
  39563. }
  39564. /**
  39565. * Defines a manual sort function for the transparent render list.
  39566. * Pass `null` to use the default sort.
  39567. *
  39568. * @param {Function} method - The sort function.
  39569. */
  39570. setTransparentSort( method ) {
  39571. this._transparentSort = method;
  39572. }
  39573. /**
  39574. * Returns the scissor rectangle.
  39575. *
  39576. * @param {Vector4} target - The method writes the result in this target object.
  39577. * @return {Vector4} The scissor rectangle.
  39578. */
  39579. getScissor( target ) {
  39580. const scissor = this._scissor;
  39581. target.x = scissor.x;
  39582. target.y = scissor.y;
  39583. target.width = scissor.width;
  39584. target.height = scissor.height;
  39585. return target;
  39586. }
  39587. /**
  39588. * Defines the scissor rectangle.
  39589. *
  39590. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39591. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39592. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39593. * @param {number} width - The width of the scissor box in logical pixel unit.
  39594. * @param {number} height - The height of the scissor box in logical pixel unit.
  39595. */
  39596. setScissor( x, y, width, height ) {
  39597. const scissor = this._scissor;
  39598. if ( x.isVector4 ) {
  39599. scissor.copy( x );
  39600. } else {
  39601. scissor.set( x, y, width, height );
  39602. }
  39603. }
  39604. /**
  39605. * Returns the scissor test value.
  39606. *
  39607. * @return {boolean} Whether the scissor test should be enabled or not.
  39608. */
  39609. getScissorTest() {
  39610. return this._scissorTest;
  39611. }
  39612. /**
  39613. * Defines the scissor test.
  39614. *
  39615. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39616. */
  39617. setScissorTest( boolean ) {
  39618. this._scissorTest = boolean;
  39619. this.backend.setScissorTest( boolean );
  39620. }
  39621. /**
  39622. * Returns the viewport definition.
  39623. *
  39624. * @param {Vector4} target - The method writes the result in this target object.
  39625. * @return {Vector4} The viewport definition.
  39626. */
  39627. getViewport( target ) {
  39628. return target.copy( this._viewport );
  39629. }
  39630. /**
  39631. * Defines the viewport.
  39632. *
  39633. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39634. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39635. * @param {number} width - The width of the viewport in logical pixel unit.
  39636. * @param {number} height - The height of the viewport in logical pixel unit.
  39637. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  39638. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  39639. */
  39640. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39641. const viewport = this._viewport;
  39642. if ( x.isVector4 ) {
  39643. viewport.copy( x );
  39644. } else {
  39645. viewport.set( x, y, width, height );
  39646. }
  39647. viewport.minDepth = minDepth;
  39648. viewport.maxDepth = maxDepth;
  39649. }
  39650. /**
  39651. * Returns the clear color.
  39652. *
  39653. * @param {Color} target - The method writes the result in this target object.
  39654. * @return {Color} The clear color.
  39655. */
  39656. getClearColor( target ) {
  39657. return target.copy( this._clearColor );
  39658. }
  39659. /**
  39660. * Defines the clear color and optionally the clear alpha.
  39661. *
  39662. * @param {Color} color - The clear color.
  39663. * @param {number} [alpha=1] - The clear alpha.
  39664. */
  39665. setClearColor( color, alpha = 1 ) {
  39666. this._clearColor.set( color );
  39667. this._clearColor.a = alpha;
  39668. }
  39669. /**
  39670. * Returns the clear alpha.
  39671. *
  39672. * @return {number} The clear alpha.
  39673. */
  39674. getClearAlpha() {
  39675. return this._clearColor.a;
  39676. }
  39677. /**
  39678. * Defines the clear alpha.
  39679. *
  39680. * @param {number} alpha - The clear alpha.
  39681. */
  39682. setClearAlpha( alpha ) {
  39683. this._clearColor.a = alpha;
  39684. }
  39685. /**
  39686. * Returns the clear depth.
  39687. *
  39688. * @return {number} The clear depth.
  39689. */
  39690. getClearDepth() {
  39691. return this._clearDepth;
  39692. }
  39693. /**
  39694. * Defines the clear depth.
  39695. *
  39696. * @param {number} depth - The clear depth.
  39697. */
  39698. setClearDepth( depth ) {
  39699. this._clearDepth = depth;
  39700. }
  39701. /**
  39702. * Returns the clear stencil.
  39703. *
  39704. * @return {number} The clear stencil.
  39705. */
  39706. getClearStencil() {
  39707. return this._clearStencil;
  39708. }
  39709. /**
  39710. * Defines the clear stencil.
  39711. *
  39712. * @param {number} stencil - The clear stencil.
  39713. */
  39714. setClearStencil( stencil ) {
  39715. this._clearStencil = stencil;
  39716. }
  39717. /**
  39718. * This method performs an occlusion query for the given 3D object.
  39719. * It returns `true` if the given 3D object is fully occluded by other
  39720. * 3D objects in the scene.
  39721. *
  39722. * @param {Object3D} object - The 3D object to test.
  39723. * @return {boolean} Whether the 3D object is fully occluded or not.
  39724. */
  39725. isOccluded( object ) {
  39726. const renderContext = this._currentRenderContext;
  39727. return renderContext && this.backend.isOccluded( renderContext, object );
  39728. }
  39729. /**
  39730. * Performs a manual clear operation. This method ignores `autoClear` properties.
  39731. *
  39732. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  39733. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  39734. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  39735. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39736. * Only returned when the renderer has not been initialized.
  39737. */
  39738. clear( color = true, depth = true, stencil = true ) {
  39739. if ( this._initialized === false ) {
  39740. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  39741. return this.clearAsync( color, depth, stencil );
  39742. }
  39743. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  39744. let renderContext = null;
  39745. if ( renderTarget !== null ) {
  39746. this._textures.updateRenderTarget( renderTarget );
  39747. const renderTargetData = this._textures.get( renderTarget );
  39748. renderContext = this._renderContexts.getForClear( renderTarget );
  39749. renderContext.textures = renderTargetData.textures;
  39750. renderContext.depthTexture = renderTargetData.depthTexture;
  39751. renderContext.width = renderTargetData.width;
  39752. renderContext.height = renderTargetData.height;
  39753. renderContext.renderTarget = renderTarget;
  39754. renderContext.depth = renderTarget.depthBuffer;
  39755. renderContext.stencil = renderTarget.stencilBuffer;
  39756. // #30329
  39757. renderContext.clearColorValue = this.backend.getClearColor();
  39758. renderContext.activeCubeFace = this.getActiveCubeFace();
  39759. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  39760. }
  39761. this.backend.clear( color, depth, stencil, renderContext );
  39762. if ( renderTarget !== null && this._renderTarget === null ) {
  39763. this._renderOutput( renderTarget );
  39764. }
  39765. }
  39766. /**
  39767. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  39768. *
  39769. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39770. * Only returned when the renderer has not been initialized.
  39771. */
  39772. clearColor() {
  39773. return this.clear( true, false, false );
  39774. }
  39775. /**
  39776. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  39777. *
  39778. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39779. * Only returned when the renderer has not been initialized.
  39780. */
  39781. clearDepth() {
  39782. return this.clear( false, true, false );
  39783. }
  39784. /**
  39785. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  39786. *
  39787. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39788. * Only returned when the renderer has not been initialized.
  39789. */
  39790. clearStencil() {
  39791. return this.clear( false, false, true );
  39792. }
  39793. /**
  39794. * Async version of {@link Renderer#clear}.
  39795. *
  39796. * @async
  39797. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  39798. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  39799. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  39800. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39801. */
  39802. async clearAsync( color = true, depth = true, stencil = true ) {
  39803. if ( this._initialized === false ) await this.init();
  39804. this.clear( color, depth, stencil );
  39805. }
  39806. /**
  39807. * Async version of {@link Renderer#clearColor}.
  39808. *
  39809. * @async
  39810. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39811. */
  39812. async clearColorAsync() {
  39813. this.clearAsync( true, false, false );
  39814. }
  39815. /**
  39816. * Async version of {@link Renderer#clearDepth}.
  39817. *
  39818. * @async
  39819. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39820. */
  39821. async clearDepthAsync() {
  39822. this.clearAsync( false, true, false );
  39823. }
  39824. /**
  39825. * Async version of {@link Renderer#clearStencil}.
  39826. *
  39827. * @async
  39828. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39829. */
  39830. async clearStencilAsync() {
  39831. this.clearAsync( false, false, true );
  39832. }
  39833. /**
  39834. * The current tone mapping of the renderer. When not producing screen output,
  39835. * the tone mapping is always `NoToneMapping`.
  39836. *
  39837. * @type {number}
  39838. */
  39839. get currentToneMapping() {
  39840. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  39841. }
  39842. /**
  39843. * The current color space of the renderer. When not producing screen output,
  39844. * the color space is always the working color space.
  39845. *
  39846. * @type {string}
  39847. */
  39848. get currentColorSpace() {
  39849. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  39850. }
  39851. /**
  39852. * Returns `true` if the rendering settings are set to screen output.
  39853. *
  39854. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  39855. */
  39856. get isOutputTarget() {
  39857. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  39858. }
  39859. /**
  39860. * Frees all internal resources of the renderer. Call this method if the renderer
  39861. * is no longer in use by your app.
  39862. */
  39863. dispose() {
  39864. this.info.dispose();
  39865. this.backend.dispose();
  39866. this._animation.dispose();
  39867. this._objects.dispose();
  39868. this._pipelines.dispose();
  39869. this._nodes.dispose();
  39870. this._bindings.dispose();
  39871. this._renderLists.dispose();
  39872. this._renderContexts.dispose();
  39873. this._textures.dispose();
  39874. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  39875. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  39876. if ( queryPool !== null ) queryPool.dispose();
  39877. } );
  39878. this.setRenderTarget( null );
  39879. this.setAnimationLoop( null );
  39880. }
  39881. /**
  39882. * Sets the given render target. Calling this method means the renderer does not
  39883. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  39884. * Use `null` as the first argument to reset the state.
  39885. *
  39886. * @param {?RenderTarget} renderTarget - The render target to set.
  39887. * @param {number} [activeCubeFace=0] - The active cube face.
  39888. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  39889. */
  39890. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  39891. this._renderTarget = renderTarget;
  39892. this._activeCubeFace = activeCubeFace;
  39893. this._activeMipmapLevel = activeMipmapLevel;
  39894. }
  39895. /**
  39896. * Returns the current render target.
  39897. *
  39898. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  39899. */
  39900. getRenderTarget() {
  39901. return this._renderTarget;
  39902. }
  39903. /**
  39904. * Sets the output render target for the renderer.
  39905. *
  39906. * @param {Object} renderTarget - The render target to set as the output target.
  39907. */
  39908. setOutputRenderTarget( renderTarget ) {
  39909. this._outputRenderTarget = renderTarget;
  39910. }
  39911. /**
  39912. * Returns the current output target.
  39913. *
  39914. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  39915. */
  39916. getOutputRenderTarget() {
  39917. return this._outputRenderTarget;
  39918. }
  39919. /**
  39920. * Resets the renderer to the initial state before WebXR started.
  39921. *
  39922. */
  39923. _resetXRState() {
  39924. this.backend.setXRTarget( null );
  39925. this.setOutputRenderTarget( null );
  39926. this.setRenderTarget( null );
  39927. this._frameBufferTarget.dispose();
  39928. this._frameBufferTarget = null;
  39929. }
  39930. /**
  39931. * Callback for {@link Renderer#setRenderObjectFunction}.
  39932. *
  39933. * @callback renderObjectFunction
  39934. * @param {Object3D} object - The 3D object.
  39935. * @param {Scene} scene - The scene the 3D object belongs to.
  39936. * @param {Camera} camera - The camera the object should be rendered with.
  39937. * @param {BufferGeometry} geometry - The object's geometry.
  39938. * @param {Material} material - The object's material.
  39939. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39940. * @param {LightsNode} lightsNode - The current lights node.
  39941. * @param {ClippingContext} clippingContext - The clipping context.
  39942. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39943. */
  39944. /**
  39945. * Sets the given render object function. Calling this method overwrites the default implementation
  39946. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  39947. * if you want to modify the way objects are rendered. For example you can define things like "every
  39948. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  39949. * The custom function must always call `renderObject()` in its implementation.
  39950. *
  39951. * Use `null` as the first argument to reset the state.
  39952. *
  39953. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  39954. */
  39955. setRenderObjectFunction( renderObjectFunction ) {
  39956. this._renderObjectFunction = renderObjectFunction;
  39957. }
  39958. /**
  39959. * Returns the current render object function.
  39960. *
  39961. * @return {?Function} The current render object function. Returns `null` if no function is set.
  39962. */
  39963. getRenderObjectFunction() {
  39964. return this._renderObjectFunction;
  39965. }
  39966. /**
  39967. * Execute a single or an array of compute nodes. This method can only be called
  39968. * if the renderer has been initialized.
  39969. *
  39970. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  39971. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  39972. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  39973. */
  39974. compute( computeNodes, dispatchSizeOrCount = null ) {
  39975. if ( this._isDeviceLost === true ) return;
  39976. if ( this._initialized === false ) {
  39977. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  39978. return this.computeAsync( computeNodes );
  39979. }
  39980. //
  39981. const nodeFrame = this._nodes.nodeFrame;
  39982. const previousRenderId = nodeFrame.renderId;
  39983. //
  39984. this.info.calls ++;
  39985. this.info.compute.calls ++;
  39986. this.info.compute.frameCalls ++;
  39987. nodeFrame.renderId = this.info.calls;
  39988. //
  39989. const backend = this.backend;
  39990. const pipelines = this._pipelines;
  39991. const bindings = this._bindings;
  39992. const nodes = this._nodes;
  39993. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  39994. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  39995. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  39996. }
  39997. backend.beginCompute( computeNodes );
  39998. for ( const computeNode of computeList ) {
  39999. // onInit
  40000. if ( pipelines.has( computeNode ) === false ) {
  40001. const dispose = () => {
  40002. computeNode.removeEventListener( 'dispose', dispose );
  40003. pipelines.delete( computeNode );
  40004. bindings.delete( computeNode );
  40005. nodes.delete( computeNode );
  40006. };
  40007. computeNode.addEventListener( 'dispose', dispose );
  40008. //
  40009. const onInitFn = computeNode.onInitFunction;
  40010. if ( onInitFn !== null ) {
  40011. onInitFn.call( computeNode, { renderer: this } );
  40012. }
  40013. }
  40014. nodes.updateForCompute( computeNode );
  40015. bindings.updateForCompute( computeNode );
  40016. const computeBindings = bindings.getForCompute( computeNode );
  40017. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  40018. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  40019. }
  40020. backend.finishCompute( computeNodes );
  40021. //
  40022. nodeFrame.renderId = previousRenderId;
  40023. }
  40024. /**
  40025. * Execute a single or an array of compute nodes.
  40026. *
  40027. * @async
  40028. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  40029. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  40030. * @return {Promise} A Promise that resolve when the compute has finished.
  40031. */
  40032. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  40033. if ( this._initialized === false ) await this.init();
  40034. this.compute( computeNodes, dispatchSizeOrCount );
  40035. }
  40036. /**
  40037. * Checks if the given feature is supported by the selected backend.
  40038. *
  40039. * @async
  40040. * @param {string} name - The feature's name.
  40041. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  40042. */
  40043. async hasFeatureAsync( name ) {
  40044. if ( this._initialized === false ) await this.init();
  40045. return this.backend.hasFeature( name );
  40046. }
  40047. async resolveTimestampsAsync( type = 'render' ) {
  40048. if ( this._initialized === false ) await this.init();
  40049. return this.backend.resolveTimestampsAsync( type );
  40050. }
  40051. /**
  40052. * Checks if the given feature is supported by the selected backend. If the
  40053. * renderer has not been initialized, this method always returns `false`.
  40054. *
  40055. * @param {string} name - The feature's name.
  40056. * @return {boolean} Whether the feature is supported or not.
  40057. */
  40058. hasFeature( name ) {
  40059. if ( this._initialized === false ) {
  40060. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  40061. return false;
  40062. }
  40063. return this.backend.hasFeature( name );
  40064. }
  40065. /**
  40066. * Returns `true` when the renderer has been initialized.
  40067. *
  40068. * @return {boolean} Whether the renderer has been initialized or not.
  40069. */
  40070. hasInitialized() {
  40071. return this._initialized;
  40072. }
  40073. /**
  40074. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  40075. * (which can cause noticeable lags due to decode and GPU upload overhead).
  40076. *
  40077. * @async
  40078. * @param {Texture} texture - The texture.
  40079. * @return {Promise} A Promise that resolves when the texture has been initialized.
  40080. */
  40081. async initTextureAsync( texture ) {
  40082. if ( this._initialized === false ) await this.init();
  40083. this._textures.updateTexture( texture );
  40084. }
  40085. /**
  40086. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  40087. * (which can cause noticeable lags due to decode and GPU upload overhead).
  40088. *
  40089. * This method can only be used if the renderer has been initialized.
  40090. *
  40091. * @param {Texture} texture - The texture.
  40092. */
  40093. initTexture( texture ) {
  40094. if ( this._initialized === false ) {
  40095. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  40096. }
  40097. this._textures.updateTexture( texture );
  40098. }
  40099. /**
  40100. * Copies the current bound framebuffer into the given texture.
  40101. *
  40102. * @param {FramebufferTexture} framebufferTexture - The texture.
  40103. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  40104. */
  40105. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  40106. if ( rectangle !== null ) {
  40107. if ( rectangle.isVector2 ) {
  40108. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  40109. } else if ( rectangle.isVector4 ) {
  40110. rectangle = _vector4.copy( rectangle ).floor();
  40111. } else {
  40112. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  40113. return;
  40114. }
  40115. } else {
  40116. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  40117. }
  40118. //
  40119. let renderContext = this._currentRenderContext;
  40120. let renderTarget;
  40121. if ( renderContext !== null ) {
  40122. renderTarget = renderContext.renderTarget;
  40123. } else {
  40124. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40125. if ( renderTarget !== null ) {
  40126. this._textures.updateRenderTarget( renderTarget );
  40127. renderContext = this._textures.get( renderTarget );
  40128. }
  40129. }
  40130. //
  40131. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  40132. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  40133. }
  40134. /**
  40135. * Copies data of the given source texture into a destination texture.
  40136. *
  40137. * @param {Texture} srcTexture - The source texture.
  40138. * @param {Texture} dstTexture - The destination texture.
  40139. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  40140. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  40141. * @param {number} [srcLevel=0] - The source mip level to copy from.
  40142. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  40143. */
  40144. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  40145. this._textures.updateTexture( srcTexture );
  40146. this._textures.updateTexture( dstTexture );
  40147. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  40148. }
  40149. /**
  40150. * Reads pixel data from the given render target.
  40151. *
  40152. * @async
  40153. * @param {RenderTarget} renderTarget - The render target to read from.
  40154. * @param {number} x - The `x` coordinate of the copy region's origin.
  40155. * @param {number} y - The `y` coordinate of the copy region's origin.
  40156. * @param {number} width - The width of the copy region.
  40157. * @param {number} height - The height of the copy region.
  40158. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  40159. * @param {number} [faceIndex=0] - The active cube face index.
  40160. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  40161. */
  40162. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  40163. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  40164. }
  40165. /**
  40166. * Analyzes the given 3D object's hierarchy and builds render lists from the
  40167. * processed hierarchy.
  40168. *
  40169. * @param {Object3D} object - The 3D object to process (usually a scene).
  40170. * @param {Camera} camera - The camera the object is rendered with.
  40171. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  40172. * @param {RenderList} renderList - The current render list.
  40173. * @param {ClippingContext} clippingContext - The current clipping context.
  40174. */
  40175. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  40176. if ( object.visible === false ) return;
  40177. const visible = object.layers.test( camera.layers );
  40178. if ( visible ) {
  40179. if ( object.isGroup ) {
  40180. groupOrder = object.renderOrder;
  40181. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  40182. } else if ( object.isLOD ) {
  40183. if ( object.autoUpdate === true ) object.update( camera );
  40184. } else if ( object.isLight ) {
  40185. renderList.pushLight( object );
  40186. } else if ( object.isSprite ) {
  40187. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40188. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  40189. if ( this.sortObjects === true ) {
  40190. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  40191. }
  40192. const { geometry, material } = object;
  40193. if ( material.visible ) {
  40194. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  40195. }
  40196. }
  40197. } else if ( object.isLineLoop ) {
  40198. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  40199. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  40200. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40201. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  40202. const { geometry, material } = object;
  40203. if ( this.sortObjects === true ) {
  40204. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  40205. _vector4
  40206. .copy( geometry.boundingSphere.center )
  40207. .applyMatrix4( object.matrixWorld )
  40208. .applyMatrix4( _projScreenMatrix );
  40209. }
  40210. if ( Array.isArray( material ) ) {
  40211. const groups = geometry.groups;
  40212. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  40213. const group = groups[ i ];
  40214. const groupMaterial = material[ group.materialIndex ];
  40215. if ( groupMaterial && groupMaterial.visible ) {
  40216. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  40217. }
  40218. }
  40219. } else if ( material.visible ) {
  40220. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  40221. }
  40222. }
  40223. }
  40224. }
  40225. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  40226. const baseRenderList = renderList;
  40227. // replace render list
  40228. renderList = this._renderLists.get( object, camera );
  40229. renderList.begin();
  40230. baseRenderList.pushBundle( {
  40231. bundleGroup: object,
  40232. camera,
  40233. renderList,
  40234. } );
  40235. renderList.finish();
  40236. }
  40237. const children = object.children;
  40238. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40239. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  40240. }
  40241. }
  40242. /**
  40243. * Renders the given render bundles.
  40244. *
  40245. * @private
  40246. * @param {Array<Object>} bundles - Array with render bundle data.
  40247. * @param {Scene} sceneRef - The scene the render bundles belong to.
  40248. * @param {LightsNode} lightsNode - The current lights node.
  40249. */
  40250. _renderBundles( bundles, sceneRef, lightsNode ) {
  40251. for ( const bundle of bundles ) {
  40252. this._renderBundle( bundle, sceneRef, lightsNode );
  40253. }
  40254. }
  40255. /**
  40256. * Renders the transparent objects from the given render lists.
  40257. *
  40258. * @private
  40259. * @param {Array<Object>} renderList - The transparent render list.
  40260. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  40261. * @param {Camera} camera - The camera the render list should be rendered with.
  40262. * @param {Scene} scene - The scene the render list belongs to.
  40263. * @param {LightsNode} lightsNode - The current lights node.
  40264. */
  40265. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  40266. if ( doublePassList.length > 0 ) {
  40267. // render back side
  40268. for ( const { material } of doublePassList ) {
  40269. material.side = BackSide;
  40270. }
  40271. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  40272. // render front side
  40273. for ( const { material } of doublePassList ) {
  40274. material.side = FrontSide;
  40275. }
  40276. this._renderObjects( renderList, camera, scene, lightsNode );
  40277. // restore
  40278. for ( const { material } of doublePassList ) {
  40279. material.side = DoubleSide;
  40280. }
  40281. } else {
  40282. this._renderObjects( renderList, camera, scene, lightsNode );
  40283. }
  40284. }
  40285. /**
  40286. * Renders the objects from the given render list.
  40287. *
  40288. * @private
  40289. * @param {Array<Object>} renderList - The render list.
  40290. * @param {Camera} camera - The camera the render list should be rendered with.
  40291. * @param {Scene} scene - The scene the render list belongs to.
  40292. * @param {LightsNode} lightsNode - The current lights node.
  40293. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40294. */
  40295. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  40296. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  40297. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  40298. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  40299. }
  40300. }
  40301. /**
  40302. * This method represents the default render object function that manages the render lifecycle
  40303. * of the object.
  40304. *
  40305. * @param {Object3D} object - The 3D object.
  40306. * @param {Scene} scene - The scene the 3D object belongs to.
  40307. * @param {Camera} camera - The camera the object should be rendered with.
  40308. * @param {BufferGeometry} geometry - The object's geometry.
  40309. * @param {Material} material - The object's material.
  40310. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40311. * @param {LightsNode} lightsNode - The current lights node.
  40312. * @param {?ClippingContext} clippingContext - The clipping context.
  40313. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40314. */
  40315. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  40316. let overridePositionNode;
  40317. let overrideColorNode;
  40318. let overrideDepthNode;
  40319. //
  40320. object.onBeforeRender( this, scene, camera, geometry, material, group );
  40321. //
  40322. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  40323. const overrideMaterial = scene.overrideMaterial;
  40324. if ( material.positionNode && material.positionNode.isNode ) {
  40325. overridePositionNode = overrideMaterial.positionNode;
  40326. overrideMaterial.positionNode = material.positionNode;
  40327. }
  40328. overrideMaterial.alphaTest = material.alphaTest;
  40329. overrideMaterial.alphaMap = material.alphaMap;
  40330. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  40331. if ( overrideMaterial.isShadowPassMaterial ) {
  40332. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  40333. if ( material.depthNode && material.depthNode.isNode ) {
  40334. overrideDepthNode = overrideMaterial.depthNode;
  40335. overrideMaterial.depthNode = material.depthNode;
  40336. }
  40337. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  40338. overrideColorNode = overrideMaterial.colorNode;
  40339. overrideMaterial.colorNode = material.castShadowNode;
  40340. }
  40341. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  40342. overridePositionNode = overrideMaterial.positionNode;
  40343. overrideMaterial.positionNode = material.castShadowPositionNode;
  40344. }
  40345. }
  40346. material = overrideMaterial;
  40347. }
  40348. //
  40349. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  40350. material.side = BackSide;
  40351. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  40352. material.side = FrontSide;
  40353. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  40354. material.side = DoubleSide;
  40355. } else {
  40356. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  40357. }
  40358. //
  40359. if ( overridePositionNode !== undefined ) {
  40360. scene.overrideMaterial.positionNode = overridePositionNode;
  40361. }
  40362. if ( overrideDepthNode !== undefined ) {
  40363. scene.overrideMaterial.depthNode = overrideDepthNode;
  40364. }
  40365. if ( overrideColorNode !== undefined ) {
  40366. scene.overrideMaterial.colorNode = overrideColorNode;
  40367. }
  40368. //
  40369. object.onAfterRender( this, scene, camera, geometry, material, group );
  40370. }
  40371. /**
  40372. * This method represents the default `_handleObjectFunction` implementation which creates
  40373. * a render object from the given data and performs the draw command with the selected backend.
  40374. *
  40375. * @private
  40376. * @param {Object3D} object - The 3D object.
  40377. * @param {Material} material - The object's material.
  40378. * @param {Scene} scene - The scene the 3D object belongs to.
  40379. * @param {Camera} camera - The camera the object should be rendered with.
  40380. * @param {LightsNode} lightsNode - The current lights node.
  40381. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40382. * @param {ClippingContext} clippingContext - The clipping context.
  40383. * @param {string} [passId] - An optional ID for identifying the pass.
  40384. */
  40385. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  40386. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  40387. renderObject.drawRange = object.geometry.drawRange;
  40388. renderObject.group = group;
  40389. //
  40390. const needsRefresh = this._nodes.needsRefresh( renderObject );
  40391. if ( needsRefresh ) {
  40392. this._nodes.updateBefore( renderObject );
  40393. this._geometries.updateForRender( renderObject );
  40394. this._nodes.updateForRender( renderObject );
  40395. this._bindings.updateForRender( renderObject );
  40396. }
  40397. this._pipelines.updateForRender( renderObject );
  40398. //
  40399. if ( this._currentRenderBundle !== null ) {
  40400. const renderBundleData = this.backend.get( this._currentRenderBundle );
  40401. renderBundleData.renderObjects.push( renderObject );
  40402. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  40403. }
  40404. this.backend.draw( renderObject, this.info );
  40405. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  40406. }
  40407. /**
  40408. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  40409. * Used in `compileAsync()`.
  40410. *
  40411. * @private
  40412. * @param {Object3D} object - The 3D object.
  40413. * @param {Material} material - The object's material.
  40414. * @param {Scene} scene - The scene the 3D object belongs to.
  40415. * @param {Camera} camera - The camera the object should be rendered with.
  40416. * @param {LightsNode} lightsNode - The current lights node.
  40417. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40418. * @param {ClippingContext} clippingContext - The clipping context.
  40419. * @param {string} [passId] - An optional ID for identifying the pass.
  40420. */
  40421. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  40422. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  40423. renderObject.drawRange = object.geometry.drawRange;
  40424. renderObject.group = group;
  40425. //
  40426. this._nodes.updateBefore( renderObject );
  40427. this._geometries.updateForRender( renderObject );
  40428. this._nodes.updateForRender( renderObject );
  40429. this._bindings.updateForRender( renderObject );
  40430. this._pipelines.getForRender( renderObject, this._compilationPromises );
  40431. this._nodes.updateAfter( renderObject );
  40432. }
  40433. /**
  40434. * Alias for `compileAsync()`.
  40435. *
  40436. * @method
  40437. * @param {Object3D} scene - The scene or 3D object to precompile.
  40438. * @param {Camera} camera - The camera that is used to render the scene.
  40439. * @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.
  40440. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  40441. */
  40442. get compile() {
  40443. return this.compileAsync;
  40444. }
  40445. }
  40446. /**
  40447. * A binding represents the connection between a resource (like a texture, sampler
  40448. * or uniform buffer) and the resource definition in a shader stage.
  40449. *
  40450. * This module is an abstract base class for all concrete bindings types.
  40451. *
  40452. * @abstract
  40453. * @private
  40454. */
  40455. class Binding {
  40456. /**
  40457. * Constructs a new binding.
  40458. *
  40459. * @param {string} [name=''] - The binding's name.
  40460. */
  40461. constructor( name = '' ) {
  40462. /**
  40463. * The binding's name.
  40464. *
  40465. * @type {string}
  40466. */
  40467. this.name = name;
  40468. /**
  40469. * A bitmask that defines in what shader stages the
  40470. * binding's resource is accessible.
  40471. *
  40472. * @type {number}
  40473. */
  40474. this.visibility = 0;
  40475. }
  40476. /**
  40477. * Makes sure binding's resource is visible for the given shader stage.
  40478. *
  40479. * @param {number} visibility - The shader stage.
  40480. */
  40481. setVisibility( visibility ) {
  40482. this.visibility |= visibility;
  40483. }
  40484. /**
  40485. * Clones the binding.
  40486. *
  40487. * @return {Binding} The cloned binding.
  40488. */
  40489. clone() {
  40490. return Object.assign( new this.constructor(), this );
  40491. }
  40492. }
  40493. /**
  40494. * This function is usually called with the length in bytes of an array buffer.
  40495. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  40496. *
  40497. * @function
  40498. * @param {number} floatLength - The buffer length.
  40499. * @return {number} The padded length.
  40500. */
  40501. function getFloatLength( floatLength ) {
  40502. // ensure chunk size alignment (STD140 layout)
  40503. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  40504. }
  40505. /**
  40506. * Represents a buffer binding type.
  40507. *
  40508. * @private
  40509. * @abstract
  40510. * @augments Binding
  40511. */
  40512. class Buffer extends Binding {
  40513. /**
  40514. * Constructs a new buffer.
  40515. *
  40516. * @param {string} name - The buffer's name.
  40517. * @param {TypedArray} [buffer=null] - The buffer.
  40518. */
  40519. constructor( name, buffer = null ) {
  40520. super( name );
  40521. /**
  40522. * This flag can be used for type testing.
  40523. *
  40524. * @type {boolean}
  40525. * @readonly
  40526. * @default true
  40527. */
  40528. this.isBuffer = true;
  40529. /**
  40530. * The bytes per element.
  40531. *
  40532. * @type {number}
  40533. */
  40534. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  40535. /**
  40536. * A reference to the internal buffer.
  40537. *
  40538. * @private
  40539. * @type {TypedArray}
  40540. */
  40541. this._buffer = buffer;
  40542. }
  40543. /**
  40544. * The buffer's byte length.
  40545. *
  40546. * @type {number}
  40547. * @readonly
  40548. */
  40549. get byteLength() {
  40550. return getFloatLength( this._buffer.byteLength );
  40551. }
  40552. /**
  40553. * A reference to the internal buffer.
  40554. *
  40555. * @type {Float32Array}
  40556. * @readonly
  40557. */
  40558. get buffer() {
  40559. return this._buffer;
  40560. }
  40561. /**
  40562. * Updates the binding.
  40563. *
  40564. * @return {boolean} Whether the buffer has been updated and must be
  40565. * uploaded to the GPU.
  40566. */
  40567. update() {
  40568. return true;
  40569. }
  40570. }
  40571. /**
  40572. * Represents a uniform buffer binding type.
  40573. *
  40574. * @private
  40575. * @augments Buffer
  40576. */
  40577. class UniformBuffer extends Buffer {
  40578. /**
  40579. * Constructs a new uniform buffer.
  40580. *
  40581. * @param {string} name - The buffer's name.
  40582. * @param {TypedArray} [buffer=null] - The buffer.
  40583. */
  40584. constructor( name, buffer = null ) {
  40585. super( name, buffer );
  40586. /**
  40587. * This flag can be used for type testing.
  40588. *
  40589. * @type {boolean}
  40590. * @readonly
  40591. * @default true
  40592. */
  40593. this.isUniformBuffer = true;
  40594. }
  40595. }
  40596. let _id$4 = 0;
  40597. /**
  40598. * A special form of uniform buffer binding type.
  40599. * It's buffer value is managed by a node object.
  40600. *
  40601. * @private
  40602. * @augments UniformBuffer
  40603. */
  40604. class NodeUniformBuffer extends UniformBuffer {
  40605. /**
  40606. * Constructs a new node-based uniform buffer.
  40607. *
  40608. * @param {BufferNode} nodeUniform - The uniform buffer node.
  40609. * @param {UniformGroupNode} groupNode - The uniform group node.
  40610. */
  40611. constructor( nodeUniform, groupNode ) {
  40612. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  40613. /**
  40614. * The uniform buffer node.
  40615. *
  40616. * @type {BufferNode}
  40617. */
  40618. this.nodeUniform = nodeUniform;
  40619. /**
  40620. * The uniform group node.
  40621. *
  40622. * @type {UniformGroupNode}
  40623. */
  40624. this.groupNode = groupNode;
  40625. }
  40626. /**
  40627. * The uniform buffer.
  40628. *
  40629. * @type {Float32Array}
  40630. */
  40631. get buffer() {
  40632. return this.nodeUniform.value;
  40633. }
  40634. }
  40635. /**
  40636. * This class represents a uniform buffer binding but with
  40637. * an API that allows to maintain individual uniform objects.
  40638. *
  40639. * @private
  40640. * @augments UniformBuffer
  40641. */
  40642. class UniformsGroup extends UniformBuffer {
  40643. /**
  40644. * Constructs a new uniforms group.
  40645. *
  40646. * @param {string} name - The group's name.
  40647. */
  40648. constructor( name ) {
  40649. super( name );
  40650. /**
  40651. * This flag can be used for type testing.
  40652. *
  40653. * @type {boolean}
  40654. * @readonly
  40655. * @default true
  40656. */
  40657. this.isUniformsGroup = true;
  40658. /**
  40659. * An array with the raw uniform values.
  40660. *
  40661. * @private
  40662. * @type {?Array<number>}
  40663. * @default null
  40664. */
  40665. this._values = null;
  40666. /**
  40667. * An array of uniform objects.
  40668. *
  40669. * The order of uniforms in this array must match the order of uniforms in the shader.
  40670. *
  40671. * @type {Array<Uniform>}
  40672. */
  40673. this.uniforms = [];
  40674. }
  40675. /**
  40676. * Adds a uniform to this group.
  40677. *
  40678. * @param {Uniform} uniform - The uniform to add.
  40679. * @return {UniformsGroup} A reference to this group.
  40680. */
  40681. addUniform( uniform ) {
  40682. this.uniforms.push( uniform );
  40683. return this;
  40684. }
  40685. /**
  40686. * Removes a uniform from this group.
  40687. *
  40688. * @param {Uniform} uniform - The uniform to remove.
  40689. * @return {UniformsGroup} A reference to this group.
  40690. */
  40691. removeUniform( uniform ) {
  40692. const index = this.uniforms.indexOf( uniform );
  40693. if ( index !== -1 ) {
  40694. this.uniforms.splice( index, 1 );
  40695. }
  40696. return this;
  40697. }
  40698. /**
  40699. * An array with the raw uniform values.
  40700. *
  40701. * @type {Array<number>}
  40702. */
  40703. get values() {
  40704. if ( this._values === null ) {
  40705. this._values = Array.from( this.buffer );
  40706. }
  40707. return this._values;
  40708. }
  40709. /**
  40710. * A Float32 array buffer with the uniform values.
  40711. *
  40712. * @type {Float32Array}
  40713. */
  40714. get buffer() {
  40715. let buffer = this._buffer;
  40716. if ( buffer === null ) {
  40717. const byteLength = this.byteLength;
  40718. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  40719. this._buffer = buffer;
  40720. }
  40721. return buffer;
  40722. }
  40723. /**
  40724. * The byte length of the buffer with correct buffer alignment.
  40725. *
  40726. * @type {number}
  40727. */
  40728. get byteLength() {
  40729. const bytesPerElement = this.bytesPerElement;
  40730. let offset = 0; // global buffer offset in bytes
  40731. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  40732. const uniform = this.uniforms[ i ];
  40733. const boundary = uniform.boundary;
  40734. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  40735. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  40736. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  40737. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  40738. offset += chunkPadding;
  40739. // Check for chunk overflow
  40740. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  40741. // Add padding to the end of the chunk
  40742. offset += ( GPU_CHUNK_BYTES - chunkStart );
  40743. }
  40744. uniform.offset = offset / bytesPerElement;
  40745. offset += itemSize;
  40746. }
  40747. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  40748. }
  40749. /**
  40750. * Updates this group by updating each uniform object of
  40751. * the internal uniform list. The uniform objects check if their
  40752. * values has actually changed so this method only returns
  40753. * `true` if there is a real value change.
  40754. *
  40755. * @return {boolean} Whether the uniforms have been updated and
  40756. * must be uploaded to the GPU.
  40757. */
  40758. update() {
  40759. let updated = false;
  40760. for ( const uniform of this.uniforms ) {
  40761. if ( this.updateByType( uniform ) === true ) {
  40762. updated = true;
  40763. }
  40764. }
  40765. return updated;
  40766. }
  40767. /**
  40768. * Updates a given uniform by calling an update method matching
  40769. * the uniforms type.
  40770. *
  40771. * @param {Uniform} uniform - The uniform to update.
  40772. * @return {boolean} Whether the uniform has been updated or not.
  40773. */
  40774. updateByType( uniform ) {
  40775. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  40776. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  40777. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  40778. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  40779. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  40780. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  40781. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  40782. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  40783. }
  40784. /**
  40785. * Updates a given Number uniform.
  40786. *
  40787. * @param {NumberUniform} uniform - The Number uniform.
  40788. * @return {boolean} Whether the uniform has been updated or not.
  40789. */
  40790. updateNumber( uniform ) {
  40791. let updated = false;
  40792. const a = this.values;
  40793. const v = uniform.getValue();
  40794. const offset = uniform.offset;
  40795. const type = uniform.getType();
  40796. if ( a[ offset ] !== v ) {
  40797. const b = this._getBufferForType( type );
  40798. b[ offset ] = a[ offset ] = v;
  40799. updated = true;
  40800. }
  40801. return updated;
  40802. }
  40803. /**
  40804. * Updates a given Vector2 uniform.
  40805. *
  40806. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  40807. * @return {boolean} Whether the uniform has been updated or not.
  40808. */
  40809. updateVector2( uniform ) {
  40810. let updated = false;
  40811. const a = this.values;
  40812. const v = uniform.getValue();
  40813. const offset = uniform.offset;
  40814. const type = uniform.getType();
  40815. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  40816. const b = this._getBufferForType( type );
  40817. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40818. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40819. updated = true;
  40820. }
  40821. return updated;
  40822. }
  40823. /**
  40824. * Updates a given Vector3 uniform.
  40825. *
  40826. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  40827. * @return {boolean} Whether the uniform has been updated or not.
  40828. */
  40829. updateVector3( uniform ) {
  40830. let updated = false;
  40831. const a = this.values;
  40832. const v = uniform.getValue();
  40833. const offset = uniform.offset;
  40834. const type = uniform.getType();
  40835. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  40836. const b = this._getBufferForType( type );
  40837. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40838. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40839. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  40840. updated = true;
  40841. }
  40842. return updated;
  40843. }
  40844. /**
  40845. * Updates a given Vector4 uniform.
  40846. *
  40847. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  40848. * @return {boolean} Whether the uniform has been updated or not.
  40849. */
  40850. updateVector4( uniform ) {
  40851. let updated = false;
  40852. const a = this.values;
  40853. const v = uniform.getValue();
  40854. const offset = uniform.offset;
  40855. const type = uniform.getType();
  40856. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  40857. const b = this._getBufferForType( type );
  40858. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40859. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40860. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  40861. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  40862. updated = true;
  40863. }
  40864. return updated;
  40865. }
  40866. /**
  40867. * Updates a given Color uniform.
  40868. *
  40869. * @param {ColorUniform} uniform - The Color uniform.
  40870. * @return {boolean} Whether the uniform has been updated or not.
  40871. */
  40872. updateColor( uniform ) {
  40873. let updated = false;
  40874. const a = this.values;
  40875. const c = uniform.getValue();
  40876. const offset = uniform.offset;
  40877. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  40878. const b = this.buffer;
  40879. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  40880. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  40881. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  40882. updated = true;
  40883. }
  40884. return updated;
  40885. }
  40886. /**
  40887. * Updates a given Matrix3 uniform.
  40888. *
  40889. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  40890. * @return {boolean} Whether the uniform has been updated or not.
  40891. */
  40892. updateMatrix3( uniform ) {
  40893. let updated = false;
  40894. const a = this.values;
  40895. const e = uniform.getValue().elements;
  40896. const offset = uniform.offset;
  40897. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  40898. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  40899. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  40900. const b = this.buffer;
  40901. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  40902. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  40903. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  40904. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  40905. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  40906. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  40907. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  40908. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  40909. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  40910. updated = true;
  40911. }
  40912. return updated;
  40913. }
  40914. /**
  40915. * Updates a given Matrix4 uniform.
  40916. *
  40917. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  40918. * @return {boolean} Whether the uniform has been updated or not.
  40919. */
  40920. updateMatrix4( uniform ) {
  40921. let updated = false;
  40922. const a = this.values;
  40923. const e = uniform.getValue().elements;
  40924. const offset = uniform.offset;
  40925. if ( arraysEqual( a, e, offset ) === false ) {
  40926. const b = this.buffer;
  40927. b.set( e, offset );
  40928. setArray( a, e, offset );
  40929. updated = true;
  40930. }
  40931. return updated;
  40932. }
  40933. /**
  40934. * Returns a typed array that matches the given data type.
  40935. *
  40936. * @param {string} type - The data type.
  40937. * @return {TypedArray} The typed array.
  40938. */
  40939. _getBufferForType( type ) {
  40940. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  40941. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  40942. return this.buffer;
  40943. }
  40944. }
  40945. /**
  40946. * Sets the values of the second array to the first array.
  40947. *
  40948. * @private
  40949. * @param {TypedArray} a - The first array.
  40950. * @param {TypedArray} b - The second array.
  40951. * @param {number} offset - An index offset for the first array.
  40952. */
  40953. function setArray( a, b, offset ) {
  40954. for ( let i = 0, l = b.length; i < l; i ++ ) {
  40955. a[ offset + i ] = b[ i ];
  40956. }
  40957. }
  40958. /**
  40959. * Returns `true` if the given arrays are equal.
  40960. *
  40961. * @private
  40962. * @param {TypedArray} a - The first array.
  40963. * @param {TypedArray} b - The second array.
  40964. * @param {number} offset - An index offset for the first array.
  40965. * @return {boolean} Whether the given arrays are equal or not.
  40966. */
  40967. function arraysEqual( a, b, offset ) {
  40968. for ( let i = 0, l = b.length; i < l; i ++ ) {
  40969. if ( a[ offset + i ] !== b[ i ] ) return false;
  40970. }
  40971. return true;
  40972. }
  40973. let _id$3 = 0;
  40974. /**
  40975. * A special form of uniforms group that represents
  40976. * the individual uniforms as node-based uniforms.
  40977. *
  40978. * @private
  40979. * @augments UniformsGroup
  40980. */
  40981. class NodeUniformsGroup extends UniformsGroup {
  40982. /**
  40983. * Constructs a new node-based uniforms group.
  40984. *
  40985. * @param {string} name - The group's name.
  40986. * @param {UniformGroupNode} groupNode - The uniform group node.
  40987. */
  40988. constructor( name, groupNode ) {
  40989. super( name );
  40990. /**
  40991. * The group's ID.
  40992. *
  40993. * @type {number}
  40994. */
  40995. this.id = _id$3 ++;
  40996. /**
  40997. * The uniform group node.
  40998. *
  40999. * @type {UniformGroupNode}
  41000. */
  41001. this.groupNode = groupNode;
  41002. /**
  41003. * This flag can be used for type testing.
  41004. *
  41005. * @type {boolean}
  41006. * @readonly
  41007. * @default true
  41008. */
  41009. this.isNodeUniformsGroup = true;
  41010. }
  41011. }
  41012. /**
  41013. * Represents a sampler binding type.
  41014. *
  41015. * @private
  41016. * @augments Binding
  41017. */
  41018. class Sampler extends Binding {
  41019. /**
  41020. * Constructs a new sampler.
  41021. *
  41022. * @param {string} name - The samplers's name.
  41023. * @param {?Texture} texture - The texture this binding is referring to.
  41024. */
  41025. constructor( name, texture ) {
  41026. super( name );
  41027. /**
  41028. * This function is called when the texture is disposed.
  41029. * @type {function}
  41030. * @private
  41031. */
  41032. this._onDisposeTexture = () => {
  41033. this.texture = null;
  41034. };
  41035. /**
  41036. * The texture the sampler is referring to.
  41037. *
  41038. * @type {?Texture}
  41039. */
  41040. this.texture = texture;
  41041. /**
  41042. * The binding's version.
  41043. *
  41044. * @type {number}
  41045. */
  41046. this.version = texture ? texture.version : 0;
  41047. /**
  41048. * The binding's generation which is an additional version
  41049. * qualifier.
  41050. *
  41051. * @type {?number}
  41052. * @default null
  41053. */
  41054. this.generation = null;
  41055. /**
  41056. * This flag can be used for type testing.
  41057. *
  41058. * @type {boolean}
  41059. * @readonly
  41060. * @default true
  41061. */
  41062. this.isSampler = true;
  41063. }
  41064. /**
  41065. * Sets the texture of this sampler.
  41066. * @param {?Texture} value - The texture to set.
  41067. */
  41068. set texture( value ) {
  41069. if ( this._texture === value ) return;
  41070. if ( this._texture ) {
  41071. this._texture.removeEventListener( 'dispose', this._onDisposeTexture );
  41072. }
  41073. this._texture = value;
  41074. this.generation = null;
  41075. this.version = 0;
  41076. if ( this._texture ) {
  41077. this._texture.addEventListener( 'dispose', this._onDisposeTexture );
  41078. }
  41079. }
  41080. /**
  41081. * Gets the texture of this sampler.
  41082. * @return {?Texture} The texture.
  41083. */
  41084. get texture() {
  41085. return this._texture;
  41086. }
  41087. /**
  41088. * Updates the binding.
  41089. *
  41090. * @return {boolean} Whether the texture has been updated and must be
  41091. * uploaded to the GPU.
  41092. */
  41093. update() {
  41094. const { texture, version } = this;
  41095. if ( version !== texture.version ) {
  41096. this.version = texture.version;
  41097. return true;
  41098. }
  41099. return false;
  41100. }
  41101. }
  41102. let _id$2 = 0;
  41103. /**
  41104. * Represents a sampled texture binding type.
  41105. *
  41106. * @private
  41107. * @augments Binding
  41108. */
  41109. class SampledTexture extends Sampler {
  41110. /**
  41111. * Constructs a new sampled texture.
  41112. *
  41113. * @param {string} name - The sampled texture's name.
  41114. * @param {?Texture} texture - The texture this binding is referring to.
  41115. */
  41116. constructor( name, texture ) {
  41117. super( name, texture );
  41118. /**
  41119. * This identifier.
  41120. *
  41121. * @type {number}
  41122. */
  41123. this.id = _id$2 ++;
  41124. /**
  41125. * Whether the texture is a storage texture or not.
  41126. *
  41127. * @type {boolean}
  41128. * @default false
  41129. */
  41130. this.store = false;
  41131. /**
  41132. * This flag can be used for type testing.
  41133. *
  41134. * @type {boolean}
  41135. * @readonly
  41136. * @default true
  41137. */
  41138. this.isSampledTexture = true;
  41139. }
  41140. }
  41141. /**
  41142. * A special form of sampled texture binding type.
  41143. * It's texture value is managed by a node object.
  41144. *
  41145. * @private
  41146. * @augments SampledTexture
  41147. */
  41148. class NodeSampledTexture extends SampledTexture {
  41149. /**
  41150. * Constructs a new node-based sampled texture.
  41151. *
  41152. * @param {string} name - The textures's name.
  41153. * @param {TextureNode} textureNode - The texture node.
  41154. * @param {UniformGroupNode} groupNode - The uniform group node.
  41155. * @param {?string} [access=null] - The access type.
  41156. */
  41157. constructor( name, textureNode, groupNode, access = null ) {
  41158. super( name, textureNode ? textureNode.value : null );
  41159. /**
  41160. * The texture node.
  41161. *
  41162. * @type {TextureNode}
  41163. */
  41164. this.textureNode = textureNode;
  41165. /**
  41166. * The uniform group node.
  41167. *
  41168. * @type {UniformGroupNode}
  41169. */
  41170. this.groupNode = groupNode;
  41171. /**
  41172. * The access type.
  41173. *
  41174. * @type {?string}
  41175. * @default null
  41176. */
  41177. this.access = access;
  41178. }
  41179. /**
  41180. * Updates the binding.
  41181. *
  41182. * @return {boolean} Whether the texture has been updated and must be
  41183. * uploaded to the GPU.
  41184. */
  41185. update() {
  41186. const { textureNode } = this;
  41187. if ( this.texture !== textureNode.value ) {
  41188. this.texture = textureNode.value;
  41189. return true;
  41190. }
  41191. return super.update();
  41192. }
  41193. }
  41194. /**
  41195. * A special form of sampled cube texture binding type.
  41196. * It's texture value is managed by a node object.
  41197. *
  41198. * @private
  41199. * @augments NodeSampledTexture
  41200. */
  41201. class NodeSampledCubeTexture extends NodeSampledTexture {
  41202. /**
  41203. * Constructs a new node-based sampled cube texture.
  41204. *
  41205. * @param {string} name - The textures's name.
  41206. * @param {TextureNode} textureNode - The texture node.
  41207. * @param {UniformGroupNode} groupNode - The uniform group node.
  41208. * @param {?string} [access=null] - The access type.
  41209. */
  41210. constructor( name, textureNode, groupNode, access = null ) {
  41211. super( name, textureNode, groupNode, access );
  41212. /**
  41213. * This flag can be used for type testing.
  41214. *
  41215. * @type {boolean}
  41216. * @readonly
  41217. * @default true
  41218. */
  41219. this.isSampledCubeTexture = true;
  41220. }
  41221. }
  41222. /**
  41223. * A special form of sampled 3D texture binding type.
  41224. * It's texture value is managed by a node object.
  41225. *
  41226. * @private
  41227. * @augments NodeSampledTexture
  41228. */
  41229. class NodeSampledTexture3D extends NodeSampledTexture {
  41230. /**
  41231. * Constructs a new node-based sampled 3D texture.
  41232. *
  41233. * @param {string} name - The textures's name.
  41234. * @param {TextureNode} textureNode - The texture node.
  41235. * @param {UniformGroupNode} groupNode - The uniform group node.
  41236. * @param {?string} [access=null] - The access type.
  41237. */
  41238. constructor( name, textureNode, groupNode, access = null ) {
  41239. super( name, textureNode, groupNode, access );
  41240. /**
  41241. * This flag can be used for type testing.
  41242. *
  41243. * @type {boolean}
  41244. * @readonly
  41245. * @default true
  41246. */
  41247. this.isSampledTexture3D = true;
  41248. }
  41249. }
  41250. const glslMethods = {
  41251. textureDimensions: 'textureSize',
  41252. equals: 'equal'
  41253. };
  41254. const precisionLib = {
  41255. low: 'lowp',
  41256. medium: 'mediump',
  41257. high: 'highp'
  41258. };
  41259. const supports$1 = {
  41260. swizzleAssign: true,
  41261. storageBuffer: false
  41262. };
  41263. const interpolationTypeMap = {
  41264. perspective: 'smooth',
  41265. linear: 'noperspective'
  41266. };
  41267. const interpolationModeMap = {
  41268. 'centroid': 'centroid'
  41269. };
  41270. const defaultPrecisions = `
  41271. precision highp float;
  41272. precision highp int;
  41273. precision highp sampler2D;
  41274. precision highp sampler3D;
  41275. precision highp samplerCube;
  41276. precision highp sampler2DArray;
  41277. precision highp usampler2D;
  41278. precision highp usampler3D;
  41279. precision highp usamplerCube;
  41280. precision highp usampler2DArray;
  41281. precision highp isampler2D;
  41282. precision highp isampler3D;
  41283. precision highp isamplerCube;
  41284. precision highp isampler2DArray;
  41285. precision lowp sampler2DShadow;
  41286. precision lowp sampler2DArrayShadow;
  41287. precision lowp samplerCubeShadow;
  41288. `;
  41289. /**
  41290. * A node builder targeting GLSL.
  41291. *
  41292. * This module generates GLSL shader code from node materials and also
  41293. * generates the respective bindings and vertex buffer definitions. These
  41294. * data are later used by the renderer to create render and compute pipelines
  41295. * for render objects.
  41296. *
  41297. * @augments NodeBuilder
  41298. */
  41299. class GLSLNodeBuilder extends NodeBuilder {
  41300. /**
  41301. * Constructs a new GLSL node builder renderer.
  41302. *
  41303. * @param {Object3D} object - The 3D object.
  41304. * @param {Renderer} renderer - The renderer.
  41305. */
  41306. constructor( object, renderer ) {
  41307. super( object, renderer, new GLSLNodeParser() );
  41308. /**
  41309. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  41310. * another dictionary which manages UBOs per group ('render','frame','object').
  41311. *
  41312. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  41313. */
  41314. this.uniformGroups = {};
  41315. /**
  41316. * An array that holds objects defining the varying and attribute data in
  41317. * context of Transform Feedback.
  41318. *
  41319. * @type {Array<Object<string,AttributeNode|string>>}
  41320. */
  41321. this.transforms = [];
  41322. /**
  41323. * A dictionary that holds for each shader stage a Map of used extensions.
  41324. *
  41325. * @type {Object<string,Map<string,Object>>}
  41326. */
  41327. this.extensions = {};
  41328. /**
  41329. * A dictionary that holds for each shader stage an Array of used builtins.
  41330. *
  41331. * @type {Object<string,Array<string>>}
  41332. */
  41333. this.builtins = { vertex: [], fragment: [], compute: [] };
  41334. }
  41335. /**
  41336. * Checks if the given texture requires a manual conversion to the working color space.
  41337. *
  41338. * @param {Texture} texture - The texture to check.
  41339. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  41340. */
  41341. needsToWorkingColorSpace( texture ) {
  41342. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  41343. }
  41344. /**
  41345. * Returns the native shader method name for a given generic name.
  41346. *
  41347. * @param {string} method - The method name to resolve.
  41348. * @return {string} The resolved GLSL method name.
  41349. */
  41350. getMethod( method ) {
  41351. return glslMethods[ method ] || method;
  41352. }
  41353. /**
  41354. * Returns the native snippet for a ternary operation.
  41355. *
  41356. * @param {string} condSnippet - The condition determining which expression gets resolved.
  41357. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  41358. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  41359. * @return {string} The resolved method name.
  41360. */
  41361. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  41362. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  41363. }
  41364. /**
  41365. * Returns the output struct name. Not relevant for GLSL.
  41366. *
  41367. * @return {string}
  41368. */
  41369. getOutputStructName() {
  41370. return '';
  41371. }
  41372. /**
  41373. * Builds the given shader node.
  41374. *
  41375. * @param {ShaderNodeInternal} shaderNode - The shader node.
  41376. * @return {string} The GLSL function code.
  41377. */
  41378. buildFunctionCode( shaderNode ) {
  41379. const layout = shaderNode.layout;
  41380. const flowData = this.flowShaderNode( shaderNode );
  41381. const parameters = [];
  41382. for ( const input of layout.inputs ) {
  41383. parameters.push( this.getType( input.type ) + ' ' + input.name );
  41384. }
  41385. //
  41386. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  41387. ${ flowData.vars }
  41388. ${ flowData.code }
  41389. return ${ flowData.result };
  41390. }`;
  41391. //
  41392. return code;
  41393. }
  41394. /**
  41395. * Setups the Pixel Buffer Object (PBO) for the given storage
  41396. * buffer node.
  41397. *
  41398. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  41399. */
  41400. setupPBO( storageBufferNode ) {
  41401. const attribute = storageBufferNode.value;
  41402. if ( attribute.pbo === undefined ) {
  41403. const originalArray = attribute.array;
  41404. const numElements = attribute.count * attribute.itemSize;
  41405. const { itemSize } = attribute;
  41406. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  41407. let format = isInteger ? RedIntegerFormat : RedFormat;
  41408. if ( itemSize === 2 ) {
  41409. format = isInteger ? RGIntegerFormat : RGFormat;
  41410. } else if ( itemSize === 3 ) {
  41411. format = isInteger ? RGBIntegerFormat : RGBFormat;
  41412. } else if ( itemSize === 4 ) {
  41413. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  41414. }
  41415. const typeMap = {
  41416. Float32Array: FloatType,
  41417. Uint8Array: UnsignedByteType,
  41418. Uint16Array: UnsignedShortType,
  41419. Uint32Array: UnsignedIntType,
  41420. Int8Array: ByteType,
  41421. Int16Array: ShortType,
  41422. Int32Array: IntType,
  41423. Uint8ClampedArray: UnsignedByteType,
  41424. };
  41425. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  41426. let height = Math.ceil( ( numElements / itemSize ) / width );
  41427. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  41428. const newSize = width * height * itemSize;
  41429. const newArray = new originalArray.constructor( newSize );
  41430. newArray.set( originalArray, 0 );
  41431. attribute.array = newArray;
  41432. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  41433. pboTexture.needsUpdate = true;
  41434. pboTexture.isPBOTexture = true;
  41435. const pbo = new TextureNode( pboTexture, null, null );
  41436. pbo.setPrecision( 'high' );
  41437. attribute.pboNode = pbo;
  41438. attribute.pbo = pbo.value;
  41439. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  41440. }
  41441. }
  41442. /**
  41443. * Returns a GLSL snippet that represents the property name of the given node.
  41444. *
  41445. * @param {Node} node - The node.
  41446. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  41447. * @return {string} The property name.
  41448. */
  41449. getPropertyName( node, shaderStage = this.shaderStage ) {
  41450. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  41451. return shaderStage.charAt( 0 ) + '_' + node.name;
  41452. }
  41453. return super.getPropertyName( node, shaderStage );
  41454. }
  41455. /**
  41456. * Setups the Pixel Buffer Object (PBO) for the given storage
  41457. * buffer node.
  41458. *
  41459. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  41460. * @return {string} The property name.
  41461. */
  41462. generatePBO( storageArrayElementNode ) {
  41463. const { node, indexNode } = storageArrayElementNode;
  41464. const attribute = node.value;
  41465. if ( this.renderer.backend.has( attribute ) ) {
  41466. const attributeData = this.renderer.backend.get( attribute );
  41467. attributeData.pbo = attribute.pbo;
  41468. }
  41469. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  41470. const textureName = this.getPropertyName( nodeUniform );
  41471. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  41472. const indexSnippet = indexNode.build( this, 'uint' );
  41473. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  41474. let propertyName = elementNodeData.propertyName;
  41475. if ( propertyName === undefined ) {
  41476. // property element
  41477. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  41478. propertyName = this.getPropertyName( nodeVar );
  41479. // property size
  41480. const bufferNodeData = this.getDataFromNode( node );
  41481. let propertySizeName = bufferNodeData.propertySizeName;
  41482. if ( propertySizeName === undefined ) {
  41483. propertySizeName = propertyName + 'Size';
  41484. this.getVarFromNode( node, propertySizeName, 'uint' );
  41485. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  41486. bufferNodeData.propertySizeName = propertySizeName;
  41487. }
  41488. //
  41489. const { itemSize } = attribute;
  41490. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  41491. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  41492. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  41493. //
  41494. let prefix = 'vec4';
  41495. if ( attribute.pbo.type === UnsignedIntType ) {
  41496. prefix = 'uvec4';
  41497. } else if ( attribute.pbo.type === IntType ) {
  41498. prefix = 'ivec4';
  41499. }
  41500. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  41501. elementNodeData.propertyName = propertyName;
  41502. }
  41503. return propertyName;
  41504. }
  41505. /**
  41506. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  41507. *
  41508. * @param {Texture} texture - The texture.
  41509. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41510. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41511. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  41512. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  41513. * @return {string} The GLSL snippet.
  41514. */
  41515. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  41516. if ( depthSnippet ) {
  41517. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  41518. } else {
  41519. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  41520. }
  41521. }
  41522. /**
  41523. * Generates the GLSL snippet for sampling/loading the given texture.
  41524. *
  41525. * @param {Texture} texture - The texture.
  41526. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41527. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41528. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  41529. * @return {string} The GLSL snippet.
  41530. */
  41531. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  41532. if ( texture.isDepthTexture ) {
  41533. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  41534. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  41535. } else {
  41536. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  41537. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  41538. }
  41539. }
  41540. /**
  41541. * Generates the GLSL snippet when sampling textures with explicit mip level.
  41542. *
  41543. * @param {Texture} texture - The texture.
  41544. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41545. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41546. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  41547. * @return {string} The GLSL snippet.
  41548. */
  41549. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  41550. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  41551. }
  41552. /**
  41553. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  41554. *
  41555. * @param {Texture} texture - The texture.
  41556. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41557. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41558. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  41559. * @return {string} The GLSL snippet.
  41560. */
  41561. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  41562. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  41563. }
  41564. /**
  41565. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  41566. *
  41567. * @param {Texture} texture - The texture.
  41568. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41569. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41570. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  41571. * @return {string} The GLSL snippet.
  41572. */
  41573. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  41574. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  41575. }
  41576. /**
  41577. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  41578. * against a reference value.
  41579. *
  41580. * @param {Texture} texture - The texture.
  41581. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41582. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41583. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  41584. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  41585. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  41586. * @return {string} The GLSL snippet.
  41587. */
  41588. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41589. if ( shaderStage === 'fragment' ) {
  41590. if ( depthSnippet ) {
  41591. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  41592. }
  41593. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  41594. } else {
  41595. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  41596. }
  41597. }
  41598. /**
  41599. * Returns the variables of the given shader stage as a GLSL string.
  41600. *
  41601. * @param {string} shaderStage - The shader stage.
  41602. * @return {string} The GLSL snippet that defines the variables.
  41603. */
  41604. getVars( shaderStage ) {
  41605. const snippets = [];
  41606. const vars = this.vars[ shaderStage ];
  41607. if ( vars !== undefined ) {
  41608. for ( const variable of vars ) {
  41609. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  41610. }
  41611. }
  41612. return snippets.join( '\n\t' );
  41613. }
  41614. /**
  41615. * Returns the uniforms of the given shader stage as a GLSL string.
  41616. *
  41617. * @param {string} shaderStage - The shader stage.
  41618. * @return {string} The GLSL snippet that defines the uniforms.
  41619. */
  41620. getUniforms( shaderStage ) {
  41621. const uniforms = this.uniforms[ shaderStage ];
  41622. const bindingSnippets = [];
  41623. const uniformGroups = {};
  41624. for ( const uniform of uniforms ) {
  41625. let snippet = null;
  41626. let group = false;
  41627. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  41628. const texture = uniform.node.value;
  41629. let typePrefix = '';
  41630. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  41631. if ( texture.type === UnsignedIntType ) {
  41632. typePrefix = 'u';
  41633. } else if ( texture.type === IntType ) {
  41634. typePrefix = 'i';
  41635. }
  41636. }
  41637. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  41638. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  41639. } else if ( texture.compareFunction ) {
  41640. if ( texture.isArrayTexture === true ) {
  41641. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  41642. } else {
  41643. snippet = `sampler2DShadow ${ uniform.name };`;
  41644. }
  41645. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  41646. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  41647. } else {
  41648. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  41649. }
  41650. } else if ( uniform.type === 'cubeTexture' ) {
  41651. snippet = `samplerCube ${ uniform.name };`;
  41652. } else if ( uniform.type === 'buffer' ) {
  41653. const bufferNode = uniform.node;
  41654. const bufferType = this.getType( bufferNode.bufferType );
  41655. const bufferCount = bufferNode.bufferCount;
  41656. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  41657. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  41658. } else {
  41659. const vectorType = this.getVectorType( uniform.type );
  41660. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  41661. group = true;
  41662. }
  41663. const precision = uniform.node.precision;
  41664. if ( precision !== null ) {
  41665. snippet = precisionLib[ precision ] + ' ' + snippet;
  41666. }
  41667. if ( group ) {
  41668. snippet = '\t' + snippet;
  41669. const groupName = uniform.groupNode.name;
  41670. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  41671. groupSnippets.push( snippet );
  41672. } else {
  41673. snippet = 'uniform ' + snippet;
  41674. bindingSnippets.push( snippet );
  41675. }
  41676. }
  41677. let output = '';
  41678. for ( const name in uniformGroups ) {
  41679. const groupSnippets = uniformGroups[ name ];
  41680. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  41681. }
  41682. output += bindingSnippets.join( '\n' );
  41683. return output;
  41684. }
  41685. /**
  41686. * Returns the type for a given buffer attribute.
  41687. *
  41688. * @param {BufferAttribute} attribute - The buffer attribute.
  41689. * @return {string} The type.
  41690. */
  41691. getTypeFromAttribute( attribute ) {
  41692. let nodeType = super.getTypeFromAttribute( attribute );
  41693. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  41694. let dataAttribute = attribute;
  41695. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  41696. const array = dataAttribute.array;
  41697. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  41698. nodeType = nodeType.slice( 1 );
  41699. }
  41700. }
  41701. return nodeType;
  41702. }
  41703. /**
  41704. * Returns the shader attributes of the given shader stage as a GLSL string.
  41705. *
  41706. * @param {string} shaderStage - The shader stage.
  41707. * @return {string} The GLSL snippet that defines the shader attributes.
  41708. */
  41709. getAttributes( shaderStage ) {
  41710. let snippet = '';
  41711. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41712. const attributes = this.getAttributesArray();
  41713. let location = 0;
  41714. for ( const attribute of attributes ) {
  41715. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  41716. }
  41717. }
  41718. return snippet;
  41719. }
  41720. /**
  41721. * Returns the members of the given struct type node as a GLSL string.
  41722. *
  41723. * @param {StructTypeNode} struct - The struct type node.
  41724. * @return {string} The GLSL snippet that defines the struct members.
  41725. */
  41726. getStructMembers( struct ) {
  41727. const snippets = [];
  41728. for ( const member of struct.members ) {
  41729. snippets.push( `\t${ member.type } ${ member.name };` );
  41730. }
  41731. return snippets.join( '\n' );
  41732. }
  41733. /**
  41734. * Returns the structs of the given shader stage as a GLSL string.
  41735. *
  41736. * @param {string} shaderStage - The shader stage.
  41737. * @return {string} The GLSL snippet that defines the structs.
  41738. */
  41739. getStructs( shaderStage ) {
  41740. const snippets = [];
  41741. const structs = this.structs[ shaderStage ];
  41742. const outputSnippet = [];
  41743. for ( const struct of structs ) {
  41744. if ( struct.output ) {
  41745. for ( const member of struct.members ) {
  41746. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  41747. }
  41748. } else {
  41749. let snippet = 'struct ' + struct.name + ' {\n';
  41750. snippet += this.getStructMembers( struct );
  41751. snippet += '\n};\n';
  41752. snippets.push( snippet );
  41753. }
  41754. }
  41755. if ( outputSnippet.length === 0 ) {
  41756. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  41757. }
  41758. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  41759. }
  41760. /**
  41761. * Returns the varyings of the given shader stage as a GLSL string.
  41762. *
  41763. * @param {string} shaderStage - The shader stage.
  41764. * @return {string} The GLSL snippet that defines the varyings.
  41765. */
  41766. getVaryings( shaderStage ) {
  41767. let snippet = '';
  41768. const varyings = this.varyings;
  41769. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41770. for ( const varying of varyings ) {
  41771. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  41772. const type = this.getType( varying.type );
  41773. if ( varying.needsInterpolation ) {
  41774. if ( varying.interpolationType ) {
  41775. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  41776. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  41777. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  41778. } else {
  41779. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  41780. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  41781. }
  41782. } else {
  41783. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  41784. }
  41785. }
  41786. } else if ( shaderStage === 'fragment' ) {
  41787. for ( const varying of varyings ) {
  41788. if ( varying.needsInterpolation ) {
  41789. const type = this.getType( varying.type );
  41790. if ( varying.interpolationType ) {
  41791. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  41792. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  41793. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  41794. } else {
  41795. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  41796. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  41797. }
  41798. }
  41799. }
  41800. }
  41801. for ( const builtin of this.builtins[ shaderStage ] ) {
  41802. snippet += `${builtin};\n`;
  41803. }
  41804. return snippet;
  41805. }
  41806. /**
  41807. * Returns the vertex index builtin.
  41808. *
  41809. * @return {string} The vertex index.
  41810. */
  41811. getVertexIndex() {
  41812. return 'uint( gl_VertexID )';
  41813. }
  41814. /**
  41815. * Returns the instance index builtin.
  41816. *
  41817. * @return {string} The instance index.
  41818. */
  41819. getInstanceIndex() {
  41820. return 'uint( gl_InstanceID )';
  41821. }
  41822. /**
  41823. * Returns the invocation local index builtin.
  41824. *
  41825. * @return {string} The invocation local index.
  41826. */
  41827. getInvocationLocalIndex() {
  41828. const workgroupSize = this.object.workgroupSize;
  41829. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  41830. return `uint( gl_InstanceID ) % ${size}u`;
  41831. }
  41832. /**
  41833. * Returns the draw index builtin.
  41834. *
  41835. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  41836. */
  41837. getDrawIndex() {
  41838. const extensions = this.renderer.backend.extensions;
  41839. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  41840. return 'uint( gl_DrawID )';
  41841. }
  41842. return null;
  41843. }
  41844. /**
  41845. * Returns the front facing builtin.
  41846. *
  41847. * @return {string} The front facing builtin.
  41848. */
  41849. getFrontFacing() {
  41850. return 'gl_FrontFacing';
  41851. }
  41852. /**
  41853. * Returns the frag coord builtin.
  41854. *
  41855. * @return {string} The frag coord builtin.
  41856. */
  41857. getFragCoord() {
  41858. return 'gl_FragCoord.xy';
  41859. }
  41860. /**
  41861. * Returns the frag depth builtin.
  41862. *
  41863. * @return {string} The frag depth builtin.
  41864. */
  41865. getFragDepth() {
  41866. return 'gl_FragDepth';
  41867. }
  41868. /**
  41869. * Enables the given extension.
  41870. *
  41871. * @param {string} name - The extension name.
  41872. * @param {string} behavior - The extension behavior.
  41873. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  41874. */
  41875. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  41876. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  41877. if ( map.has( name ) === false ) {
  41878. map.set( name, {
  41879. name,
  41880. behavior
  41881. } );
  41882. }
  41883. }
  41884. /**
  41885. * Returns the enabled extensions of the given shader stage as a GLSL string.
  41886. *
  41887. * @param {string} shaderStage - The shader stage.
  41888. * @return {string} The GLSL snippet that defines the enabled extensions.
  41889. */
  41890. getExtensions( shaderStage ) {
  41891. const snippets = [];
  41892. if ( shaderStage === 'vertex' ) {
  41893. const ext = this.renderer.backend.extensions;
  41894. const isBatchedMesh = this.object.isBatchedMesh;
  41895. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  41896. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  41897. }
  41898. }
  41899. const extensions = this.extensions[ shaderStage ];
  41900. if ( extensions !== undefined ) {
  41901. for ( const { name, behavior } of extensions.values() ) {
  41902. snippets.push( `#extension ${name} : ${behavior}` );
  41903. }
  41904. }
  41905. return snippets.join( '\n' );
  41906. }
  41907. /**
  41908. * Returns the clip distances builtin.
  41909. *
  41910. * @return {string} The clip distances builtin.
  41911. */
  41912. getClipDistance() {
  41913. return 'gl_ClipDistance';
  41914. }
  41915. /**
  41916. * Whether the requested feature is available or not.
  41917. *
  41918. * @param {string} name - The requested feature.
  41919. * @return {boolean} Whether the requested feature is supported or not.
  41920. */
  41921. isAvailable( name ) {
  41922. let result = supports$1[ name ];
  41923. if ( result === undefined ) {
  41924. let extensionName;
  41925. result = false;
  41926. switch ( name ) {
  41927. case 'float32Filterable':
  41928. extensionName = 'OES_texture_float_linear';
  41929. break;
  41930. case 'clipDistance':
  41931. extensionName = 'WEBGL_clip_cull_distance';
  41932. break;
  41933. }
  41934. if ( extensionName !== undefined ) {
  41935. const extensions = this.renderer.backend.extensions;
  41936. if ( extensions.has( extensionName ) ) {
  41937. extensions.get( extensionName );
  41938. result = true;
  41939. }
  41940. }
  41941. supports$1[ name ] = result;
  41942. }
  41943. return result;
  41944. }
  41945. /**
  41946. * Whether to flip texture data along its vertical axis or not.
  41947. *
  41948. * @return {boolean} Returns always `true` in context of GLSL.
  41949. */
  41950. isFlipY() {
  41951. return true;
  41952. }
  41953. /**
  41954. * Enables hardware clipping.
  41955. *
  41956. * @param {string} planeCount - The clipping plane count.
  41957. */
  41958. enableHardwareClipping( planeCount ) {
  41959. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  41960. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  41961. }
  41962. /**
  41963. * Enables multiview.
  41964. */
  41965. enableMultiview() {
  41966. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  41967. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  41968. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  41969. }
  41970. /**
  41971. * Registers a transform in context of Transform Feedback.
  41972. *
  41973. * @param {string} varyingName - The varying name.
  41974. * @param {AttributeNode} attributeNode - The attribute node.
  41975. */
  41976. registerTransform( varyingName, attributeNode ) {
  41977. this.transforms.push( { varyingName, attributeNode } );
  41978. }
  41979. /**
  41980. * Returns the transforms of the given shader stage as a GLSL string.
  41981. *
  41982. * @param {string} shaderStage - The shader stage.
  41983. * @return {string} The GLSL snippet that defines the transforms.
  41984. */
  41985. getTransforms( /* shaderStage */ ) {
  41986. const transforms = this.transforms;
  41987. let snippet = '';
  41988. for ( let i = 0; i < transforms.length; i ++ ) {
  41989. const transform = transforms[ i ];
  41990. const attributeName = this.getPropertyName( transform.attributeNode );
  41991. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  41992. }
  41993. return snippet;
  41994. }
  41995. /**
  41996. * Returns a GLSL struct based on the given name and variables.
  41997. *
  41998. * @private
  41999. * @param {string} name - The struct name.
  42000. * @param {string} vars - The struct variables.
  42001. * @return {string} The GLSL snippet representing a struct.
  42002. */
  42003. _getGLSLUniformStruct( name, vars ) {
  42004. return `
  42005. layout( std140 ) uniform ${name} {
  42006. ${vars}
  42007. };`;
  42008. }
  42009. /**
  42010. * Returns a GLSL vertex shader based on the given shader data.
  42011. *
  42012. * @private
  42013. * @param {Object} shaderData - The shader data.
  42014. * @return {string} The vertex shader.
  42015. */
  42016. _getGLSLVertexCode( shaderData ) {
  42017. return `#version 300 es
  42018. ${ this.getSignature() }
  42019. // extensions
  42020. ${shaderData.extensions}
  42021. // precision
  42022. ${ defaultPrecisions }
  42023. // uniforms
  42024. ${shaderData.uniforms}
  42025. // varyings
  42026. ${shaderData.varyings}
  42027. // attributes
  42028. ${shaderData.attributes}
  42029. // codes
  42030. ${shaderData.codes}
  42031. void main() {
  42032. // vars
  42033. ${shaderData.vars}
  42034. // transforms
  42035. ${shaderData.transforms}
  42036. // flow
  42037. ${shaderData.flow}
  42038. gl_PointSize = 1.0;
  42039. }
  42040. `;
  42041. }
  42042. /**
  42043. * Returns a GLSL fragment shader based on the given shader data.
  42044. *
  42045. * @private
  42046. * @param {Object} shaderData - The shader data.
  42047. * @return {string} The vertex shader.
  42048. */
  42049. _getGLSLFragmentCode( shaderData ) {
  42050. return `#version 300 es
  42051. ${ this.getSignature() }
  42052. // extensions
  42053. ${shaderData.extensions}
  42054. // precision
  42055. ${ defaultPrecisions }
  42056. // uniforms
  42057. ${shaderData.uniforms}
  42058. // varyings
  42059. ${shaderData.varyings}
  42060. // codes
  42061. ${shaderData.codes}
  42062. // structs
  42063. ${shaderData.structs}
  42064. void main() {
  42065. // vars
  42066. ${shaderData.vars}
  42067. // flow
  42068. ${shaderData.flow}
  42069. }
  42070. `;
  42071. }
  42072. /**
  42073. * Controls the code build of the shader stages.
  42074. */
  42075. buildCode() {
  42076. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  42077. this.sortBindingGroups();
  42078. for ( const shaderStage in shadersData ) {
  42079. let flow = '// code\n\n';
  42080. flow += this.flowCode[ shaderStage ];
  42081. const flowNodes = this.flowNodes[ shaderStage ];
  42082. const mainNode = flowNodes[ flowNodes.length - 1 ];
  42083. for ( const node of flowNodes ) {
  42084. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  42085. const slotName = node.name;
  42086. if ( slotName ) {
  42087. if ( flow.length > 0 ) flow += '\n';
  42088. flow += `\t// flow -> ${ slotName }\n\t`;
  42089. }
  42090. flow += `${ flowSlotData.code }\n\t`;
  42091. if ( node === mainNode && shaderStage !== 'compute' ) {
  42092. flow += '// result\n\t';
  42093. if ( shaderStage === 'vertex' ) {
  42094. flow += 'gl_Position = ';
  42095. flow += `${ flowSlotData.result };`;
  42096. } else if ( shaderStage === 'fragment' ) {
  42097. if ( ! node.outputNode.isOutputStructNode ) {
  42098. flow += 'fragColor = ';
  42099. flow += `${ flowSlotData.result };`;
  42100. }
  42101. }
  42102. }
  42103. }
  42104. const stageData = shadersData[ shaderStage ];
  42105. stageData.extensions = this.getExtensions( shaderStage );
  42106. stageData.uniforms = this.getUniforms( shaderStage );
  42107. stageData.attributes = this.getAttributes( shaderStage );
  42108. stageData.varyings = this.getVaryings( shaderStage );
  42109. stageData.vars = this.getVars( shaderStage );
  42110. stageData.structs = this.getStructs( shaderStage );
  42111. stageData.codes = this.getCodes( shaderStage );
  42112. stageData.transforms = this.getTransforms( shaderStage );
  42113. stageData.flow = flow;
  42114. }
  42115. if ( this.material !== null ) {
  42116. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  42117. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  42118. } else {
  42119. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  42120. }
  42121. }
  42122. /**
  42123. * This method is one of the more important ones since it's responsible
  42124. * for generating a matching binding instance for the given uniform node.
  42125. *
  42126. * These bindings are later used in the renderer to create bind groups
  42127. * and layouts.
  42128. *
  42129. * @param {UniformNode} node - The uniform node.
  42130. * @param {string} type - The node data type.
  42131. * @param {string} shaderStage - The shader stage.
  42132. * @param {?string} [name=null] - An optional uniform name.
  42133. * @return {NodeUniform} The node uniform object.
  42134. */
  42135. getUniformFromNode( node, type, shaderStage, name = null ) {
  42136. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42137. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42138. let uniformGPU = nodeData.uniformGPU;
  42139. if ( uniformGPU === undefined ) {
  42140. const group = node.groupNode;
  42141. const groupName = group.name;
  42142. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42143. if ( type === 'texture' ) {
  42144. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  42145. bindings.push( uniformGPU );
  42146. } else if ( type === 'cubeTexture' ) {
  42147. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  42148. bindings.push( uniformGPU );
  42149. } else if ( type === 'texture3D' ) {
  42150. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  42151. bindings.push( uniformGPU );
  42152. } else if ( type === 'buffer' ) {
  42153. node.name = `NodeBuffer_${ node.id }`;
  42154. uniformNode.name = `buffer${ node.id }`;
  42155. const buffer = new NodeUniformBuffer( node, group );
  42156. buffer.name = node.name;
  42157. bindings.push( buffer );
  42158. uniformGPU = buffer;
  42159. } else {
  42160. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42161. let uniformsGroup = uniformsStage[ groupName ];
  42162. if ( uniformsGroup === undefined ) {
  42163. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  42164. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42165. uniformsStage[ groupName ] = uniformsGroup;
  42166. bindings.push( uniformsGroup );
  42167. }
  42168. uniformGPU = this.getNodeUniform( uniformNode, type );
  42169. uniformsGroup.addUniform( uniformGPU );
  42170. }
  42171. nodeData.uniformGPU = uniformGPU;
  42172. }
  42173. return uniformNode;
  42174. }
  42175. }
  42176. let _vector2 = null;
  42177. let _color4 = null;
  42178. /**
  42179. * Most of the rendering related logic is implemented in the
  42180. * {@link Renderer} module and related management components.
  42181. * Sometimes it is required though to execute commands which are
  42182. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  42183. * This abstract base class defines an interface that encapsulates
  42184. * all backend-related logic. Derived classes for each backend must
  42185. * implement the interface.
  42186. *
  42187. * @abstract
  42188. * @private
  42189. */
  42190. class Backend {
  42191. /**
  42192. * Constructs a new backend.
  42193. *
  42194. * @param {Object} parameters - An object holding parameters for the backend.
  42195. */
  42196. constructor( parameters = {} ) {
  42197. /**
  42198. * The parameters of the backend.
  42199. *
  42200. * @type {Object}
  42201. */
  42202. this.parameters = Object.assign( {}, parameters );
  42203. /**
  42204. * This weak map holds backend-specific data of objects
  42205. * like textures, attributes or render targets.
  42206. *
  42207. * @type {WeakMap}
  42208. */
  42209. this.data = new WeakMap();
  42210. /**
  42211. * A reference to the renderer.
  42212. *
  42213. * @type {?Renderer}
  42214. * @default null
  42215. */
  42216. this.renderer = null;
  42217. /**
  42218. * A reference to the canvas element the renderer is drawing to.
  42219. *
  42220. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  42221. * @default null
  42222. */
  42223. this.domElement = null;
  42224. /**
  42225. * A reference to the timestamp query pool.
  42226. *
  42227. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  42228. */
  42229. this.timestampQueryPool = {
  42230. 'render': null,
  42231. 'compute': null
  42232. };
  42233. /**
  42234. * Whether to track timestamps with a Timestamp Query API or not.
  42235. *
  42236. * @type {boolean}
  42237. * @default false
  42238. */
  42239. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42240. }
  42241. /**
  42242. * Initializes the backend so it is ready for usage. Concrete backends
  42243. * are supposed to implement their rendering context creation and related
  42244. * operations in this method.
  42245. *
  42246. * @async
  42247. * @param {Renderer} renderer - The renderer.
  42248. * @return {Promise} A Promise that resolves when the backend has been initialized.
  42249. */
  42250. async init( renderer ) {
  42251. this.renderer = renderer;
  42252. }
  42253. /**
  42254. * The coordinate system of the backend.
  42255. *
  42256. * @abstract
  42257. * @type {number}
  42258. * @readonly
  42259. */
  42260. get coordinateSystem() {}
  42261. // render context
  42262. /**
  42263. * This method is executed at the beginning of a render call and
  42264. * can be used by the backend to prepare the state for upcoming
  42265. * draw calls.
  42266. *
  42267. * @abstract
  42268. * @param {RenderContext} renderContext - The render context.
  42269. */
  42270. beginRender( /*renderContext*/ ) {}
  42271. /**
  42272. * This method is executed at the end of a render call and
  42273. * can be used by the backend to finalize work after draw
  42274. * calls.
  42275. *
  42276. * @abstract
  42277. * @param {RenderContext} renderContext - The render context.
  42278. */
  42279. finishRender( /*renderContext*/ ) {}
  42280. /**
  42281. * This method is executed at the beginning of a compute call and
  42282. * can be used by the backend to prepare the state for upcoming
  42283. * compute tasks.
  42284. *
  42285. * @abstract
  42286. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42287. */
  42288. beginCompute( /*computeGroup*/ ) {}
  42289. /**
  42290. * This method is executed at the end of a compute call and
  42291. * can be used by the backend to finalize work after compute
  42292. * tasks.
  42293. *
  42294. * @abstract
  42295. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42296. */
  42297. finishCompute( /*computeGroup*/ ) {}
  42298. // render object
  42299. /**
  42300. * Executes a draw command for the given render object.
  42301. *
  42302. * @abstract
  42303. * @param {RenderObject} renderObject - The render object to draw.
  42304. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  42305. */
  42306. draw( /*renderObject, info*/ ) { }
  42307. // compute node
  42308. /**
  42309. * Executes a compute command for the given compute node.
  42310. *
  42311. * @abstract
  42312. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  42313. * @param {Node} computeNode - The compute node.
  42314. * @param {Array<BindGroup>} bindings - The bindings.
  42315. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42316. */
  42317. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  42318. // program
  42319. /**
  42320. * Creates a shader program from the given programmable stage.
  42321. *
  42322. * @abstract
  42323. * @param {ProgrammableStage} program - The programmable stage.
  42324. */
  42325. createProgram( /*program*/ ) { }
  42326. /**
  42327. * Destroys the shader program of the given programmable stage.
  42328. *
  42329. * @abstract
  42330. * @param {ProgrammableStage} program - The programmable stage.
  42331. */
  42332. destroyProgram( /*program*/ ) { }
  42333. // bindings
  42334. /**
  42335. * Creates bindings from the given bind group definition.
  42336. *
  42337. * @abstract
  42338. * @param {BindGroup} bindGroup - The bind group.
  42339. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42340. * @param {number} cacheIndex - The cache index.
  42341. * @param {number} version - The version.
  42342. */
  42343. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  42344. /**
  42345. * Updates the given bind group definition.
  42346. *
  42347. * @abstract
  42348. * @param {BindGroup} bindGroup - The bind group.
  42349. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42350. * @param {number} cacheIndex - The cache index.
  42351. * @param {number} version - The version.
  42352. */
  42353. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  42354. /**
  42355. * Updates a buffer binding.
  42356. *
  42357. * @abstract
  42358. * @param {Buffer} binding - The buffer binding to update.
  42359. */
  42360. updateBinding( /*binding*/ ) { }
  42361. // pipeline
  42362. /**
  42363. * Creates a render pipeline for the given render object.
  42364. *
  42365. * @abstract
  42366. * @param {RenderObject} renderObject - The render object.
  42367. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  42368. */
  42369. createRenderPipeline( /*renderObject, promises*/ ) { }
  42370. /**
  42371. * Creates a compute pipeline for the given compute node.
  42372. *
  42373. * @abstract
  42374. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42375. * @param {Array<BindGroup>} bindings - The bindings.
  42376. */
  42377. createComputePipeline( /*computePipeline, bindings*/ ) { }
  42378. // cache key
  42379. /**
  42380. * Returns `true` if the render pipeline requires an update.
  42381. *
  42382. * @abstract
  42383. * @param {RenderObject} renderObject - The render object.
  42384. * @return {boolean} Whether the render pipeline requires an update or not.
  42385. */
  42386. needsRenderUpdate( /*renderObject*/ ) { }
  42387. /**
  42388. * Returns a cache key that is used to identify render pipelines.
  42389. *
  42390. * @abstract
  42391. * @param {RenderObject} renderObject - The render object.
  42392. * @return {string} The cache key.
  42393. */
  42394. getRenderCacheKey( /*renderObject*/ ) { }
  42395. // node builder
  42396. /**
  42397. * Returns a node builder for the given render object.
  42398. *
  42399. * @abstract
  42400. * @param {RenderObject} renderObject - The render object.
  42401. * @param {Renderer} renderer - The renderer.
  42402. * @return {NodeBuilder} The node builder.
  42403. */
  42404. createNodeBuilder( /*renderObject, renderer*/ ) { }
  42405. // textures
  42406. /**
  42407. * Creates a GPU sampler for the given texture.
  42408. *
  42409. * @abstract
  42410. * @param {Texture} texture - The texture to create the sampler for.
  42411. */
  42412. createSampler( /*texture*/ ) { }
  42413. /**
  42414. * Destroys the GPU sampler for the given texture.
  42415. *
  42416. * @abstract
  42417. * @param {Texture} texture - The texture to destroy the sampler for.
  42418. */
  42419. destroySampler( /*texture*/ ) {}
  42420. /**
  42421. * Creates a default texture for the given texture that can be used
  42422. * as a placeholder until the actual texture is ready for usage.
  42423. *
  42424. * @abstract
  42425. * @param {Texture} texture - The texture to create a default texture for.
  42426. */
  42427. createDefaultTexture( /*texture*/ ) { }
  42428. /**
  42429. * Defines a texture on the GPU for the given texture object.
  42430. *
  42431. * @abstract
  42432. * @param {Texture} texture - The texture.
  42433. * @param {Object} [options={}] - Optional configuration parameter.
  42434. */
  42435. createTexture( /*texture, options={}*/ ) { }
  42436. /**
  42437. * Uploads the updated texture data to the GPU.
  42438. *
  42439. * @abstract
  42440. * @param {Texture} texture - The texture.
  42441. * @param {Object} [options={}] - Optional configuration parameter.
  42442. */
  42443. updateTexture( /*texture, options = {}*/ ) { }
  42444. /**
  42445. * Generates mipmaps for the given texture.
  42446. *
  42447. * @abstract
  42448. * @param {Texture} texture - The texture.
  42449. */
  42450. generateMipmaps( /*texture*/ ) { }
  42451. /**
  42452. * Destroys the GPU data for the given texture object.
  42453. *
  42454. * @abstract
  42455. * @param {Texture} texture - The texture.
  42456. */
  42457. destroyTexture( /*texture*/ ) { }
  42458. /**
  42459. * Returns texture data as a typed array.
  42460. *
  42461. * @abstract
  42462. * @async
  42463. * @param {Texture} texture - The texture to copy.
  42464. * @param {number} x - The x coordinate of the copy origin.
  42465. * @param {number} y - The y coordinate of the copy origin.
  42466. * @param {number} width - The width of the copy.
  42467. * @param {number} height - The height of the copy.
  42468. * @param {number} faceIndex - The face index.
  42469. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42470. */
  42471. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  42472. /**
  42473. * Copies data of the given source texture to the given destination texture.
  42474. *
  42475. * @abstract
  42476. * @param {Texture} srcTexture - The source texture.
  42477. * @param {Texture} dstTexture - The destination texture.
  42478. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  42479. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42480. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42481. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42482. */
  42483. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  42484. /**
  42485. * Copies the current bound framebuffer to the given texture.
  42486. *
  42487. * @abstract
  42488. * @param {Texture} texture - The destination texture.
  42489. * @param {RenderContext} renderContext - The render context.
  42490. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42491. */
  42492. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  42493. // attributes
  42494. /**
  42495. * Creates the GPU buffer of a shader attribute.
  42496. *
  42497. * @abstract
  42498. * @param {BufferAttribute} attribute - The buffer attribute.
  42499. */
  42500. createAttribute( /*attribute*/ ) { }
  42501. /**
  42502. * Creates the GPU buffer of an indexed shader attribute.
  42503. *
  42504. * @abstract
  42505. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  42506. */
  42507. createIndexAttribute( /*attribute*/ ) { }
  42508. /**
  42509. * Creates the GPU buffer of a storage attribute.
  42510. *
  42511. * @abstract
  42512. * @param {BufferAttribute} attribute - The buffer attribute.
  42513. */
  42514. createStorageAttribute( /*attribute*/ ) { }
  42515. /**
  42516. * Updates the GPU buffer of a shader attribute.
  42517. *
  42518. * @abstract
  42519. * @param {BufferAttribute} attribute - The buffer attribute to update.
  42520. */
  42521. updateAttribute( /*attribute*/ ) { }
  42522. /**
  42523. * Destroys the GPU buffer of a shader attribute.
  42524. *
  42525. * @abstract
  42526. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  42527. */
  42528. destroyAttribute( /*attribute*/ ) { }
  42529. // canvas
  42530. /**
  42531. * Returns the backend's rendering context.
  42532. *
  42533. * @abstract
  42534. * @return {Object} The rendering context.
  42535. */
  42536. getContext() { }
  42537. /**
  42538. * Backends can use this method if they have to run
  42539. * logic when the renderer gets resized.
  42540. *
  42541. * @abstract
  42542. */
  42543. updateSize() { }
  42544. /**
  42545. * Updates the viewport with the values from the given render context.
  42546. *
  42547. * @abstract
  42548. * @param {RenderContext} renderContext - The render context.
  42549. */
  42550. updateViewport( /*renderContext*/ ) {}
  42551. // utils
  42552. /**
  42553. * Returns `true` if the given 3D object is fully occluded by other
  42554. * 3D objects in the scene. Backends must implement this method by using
  42555. * a Occlusion Query API.
  42556. *
  42557. * @abstract
  42558. * @param {RenderContext} renderContext - The render context.
  42559. * @param {Object3D} object - The 3D object to test.
  42560. * @return {boolean} Whether the 3D object is fully occluded or not.
  42561. */
  42562. isOccluded( /*renderContext, object*/ ) {}
  42563. /**
  42564. * Resolves the time stamp for the given render context and type.
  42565. *
  42566. * @async
  42567. * @abstract
  42568. * @param {string} [type='render'] - The type of the time stamp.
  42569. * @return {Promise<number>} A Promise that resolves with the time stamp.
  42570. */
  42571. async resolveTimestampsAsync( type = 'render' ) {
  42572. if ( ! this.trackTimestamp ) {
  42573. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  42574. return;
  42575. }
  42576. const queryPool = this.timestampQueryPool[ type ];
  42577. if ( ! queryPool ) {
  42578. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  42579. return;
  42580. }
  42581. const duration = await queryPool.resolveQueriesAsync();
  42582. this.renderer.info[ type ].timestamp = duration;
  42583. return duration;
  42584. }
  42585. /**
  42586. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  42587. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  42588. *
  42589. * @async
  42590. * @abstract
  42591. * @return {Promise} A Promise that resolves when synchronization has been finished.
  42592. */
  42593. async waitForGPU() {}
  42594. /**
  42595. * This method performs a readback operation by moving buffer data from
  42596. * a storage buffer attribute from the GPU to the CPU.
  42597. *
  42598. * @async
  42599. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42600. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42601. */
  42602. async getArrayBufferAsync( /* attribute */ ) {}
  42603. /**
  42604. * Checks if the given feature is supported by the backend.
  42605. *
  42606. * @async
  42607. * @abstract
  42608. * @param {string} name - The feature's name.
  42609. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42610. */
  42611. async hasFeatureAsync( /*name*/ ) { }
  42612. /**
  42613. * Checks if the given feature is supported by the backend.
  42614. *
  42615. * @abstract
  42616. * @param {string} name - The feature's name.
  42617. * @return {boolean} Whether the feature is supported or not.
  42618. */
  42619. hasFeature( /*name*/ ) {}
  42620. /**
  42621. * Returns the maximum anisotropy texture filtering value.
  42622. *
  42623. * @abstract
  42624. * @return {number} The maximum anisotropy texture filtering value.
  42625. */
  42626. getMaxAnisotropy() {}
  42627. /**
  42628. * Returns the drawing buffer size.
  42629. *
  42630. * @return {Vector2} The drawing buffer size.
  42631. */
  42632. getDrawingBufferSize() {
  42633. _vector2 = _vector2 || new Vector2();
  42634. return this.renderer.getDrawingBufferSize( _vector2 );
  42635. }
  42636. /**
  42637. * Defines the scissor test.
  42638. *
  42639. * @abstract
  42640. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42641. */
  42642. setScissorTest( /*boolean*/ ) { }
  42643. /**
  42644. * Returns the clear color and alpha into a single
  42645. * color object.
  42646. *
  42647. * @return {Color4} The clear color.
  42648. */
  42649. getClearColor() {
  42650. const renderer = this.renderer;
  42651. _color4 = _color4 || new Color4();
  42652. renderer.getClearColor( _color4 );
  42653. _color4.getRGB( _color4 );
  42654. return _color4;
  42655. }
  42656. /**
  42657. * Returns the DOM element. If no DOM element exists, the backend
  42658. * creates a new one.
  42659. *
  42660. * @return {HTMLCanvasElement} The DOM element.
  42661. */
  42662. getDomElement() {
  42663. let domElement = this.domElement;
  42664. if ( domElement === null ) {
  42665. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  42666. // OffscreenCanvas does not have setAttribute, see #22811
  42667. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  42668. this.domElement = domElement;
  42669. }
  42670. return domElement;
  42671. }
  42672. /**
  42673. * Sets a dictionary for the given object into the
  42674. * internal data structure.
  42675. *
  42676. * @param {Object} object - The object.
  42677. * @param {Object} value - The dictionary to set.
  42678. */
  42679. set( object, value ) {
  42680. this.data.set( object, value );
  42681. }
  42682. /**
  42683. * Returns the dictionary for the given object.
  42684. *
  42685. * @param {Object} object - The object.
  42686. * @return {Object} The object's dictionary.
  42687. */
  42688. get( object ) {
  42689. let map = this.data.get( object );
  42690. if ( map === undefined ) {
  42691. map = {};
  42692. this.data.set( object, map );
  42693. }
  42694. return map;
  42695. }
  42696. /**
  42697. * Checks if the given object has a dictionary
  42698. * with data defined.
  42699. *
  42700. * @param {Object} object - The object.
  42701. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  42702. */
  42703. has( object ) {
  42704. return this.data.has( object );
  42705. }
  42706. /**
  42707. * Deletes an object from the internal data structure.
  42708. *
  42709. * @param {Object} object - The object to delete.
  42710. */
  42711. delete( object ) {
  42712. this.data.delete( object );
  42713. }
  42714. /**
  42715. * Frees internal resources.
  42716. *
  42717. * @abstract
  42718. */
  42719. dispose() { }
  42720. }
  42721. let _id$1 = 0;
  42722. /**
  42723. * This module is internally used in context of compute shaders.
  42724. * This type of shader is not natively supported in WebGL 2 and
  42725. * thus implemented via Transform Feedback. `DualAttributeData`
  42726. * manages the related data.
  42727. *
  42728. * @private
  42729. */
  42730. class DualAttributeData {
  42731. constructor( attributeData, dualBuffer ) {
  42732. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  42733. this.type = attributeData.type;
  42734. this.bufferType = attributeData.bufferType;
  42735. this.pbo = attributeData.pbo;
  42736. this.byteLength = attributeData.byteLength;
  42737. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  42738. this.version = attributeData.version;
  42739. this.isInteger = attributeData.isInteger;
  42740. this.activeBufferIndex = 0;
  42741. this.baseId = attributeData.id;
  42742. }
  42743. get id() {
  42744. return `${ this.baseId }|${ this.activeBufferIndex }`;
  42745. }
  42746. get bufferGPU() {
  42747. return this.buffers[ this.activeBufferIndex ];
  42748. }
  42749. get transformBuffer() {
  42750. return this.buffers[ this.activeBufferIndex ^ 1 ];
  42751. }
  42752. switchBuffers() {
  42753. this.activeBufferIndex ^= 1;
  42754. }
  42755. }
  42756. /**
  42757. * A WebGL 2 backend utility module for managing shader attributes.
  42758. *
  42759. * @private
  42760. */
  42761. class WebGLAttributeUtils {
  42762. /**
  42763. * Constructs a new utility object.
  42764. *
  42765. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42766. */
  42767. constructor( backend ) {
  42768. /**
  42769. * A reference to the WebGL 2 backend.
  42770. *
  42771. * @type {WebGLBackend}
  42772. */
  42773. this.backend = backend;
  42774. }
  42775. /**
  42776. * Creates the GPU buffer for the given buffer attribute.
  42777. *
  42778. * @param {BufferAttribute} attribute - The buffer attribute.
  42779. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  42780. */
  42781. createAttribute( attribute, bufferType ) {
  42782. const backend = this.backend;
  42783. const { gl } = backend;
  42784. const array = attribute.array;
  42785. const usage = attribute.usage || gl.STATIC_DRAW;
  42786. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42787. const bufferData = backend.get( bufferAttribute );
  42788. let bufferGPU = bufferData.bufferGPU;
  42789. if ( bufferGPU === undefined ) {
  42790. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  42791. bufferData.bufferGPU = bufferGPU;
  42792. bufferData.bufferType = bufferType;
  42793. bufferData.version = bufferAttribute.version;
  42794. }
  42795. //attribute.onUploadCallback();
  42796. let type;
  42797. if ( array instanceof Float32Array ) {
  42798. type = gl.FLOAT;
  42799. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42800. type = gl.HALF_FLOAT;
  42801. } else if ( array instanceof Uint16Array ) {
  42802. if ( attribute.isFloat16BufferAttribute ) {
  42803. type = gl.HALF_FLOAT;
  42804. } else {
  42805. type = gl.UNSIGNED_SHORT;
  42806. }
  42807. } else if ( array instanceof Int16Array ) {
  42808. type = gl.SHORT;
  42809. } else if ( array instanceof Uint32Array ) {
  42810. type = gl.UNSIGNED_INT;
  42811. } else if ( array instanceof Int32Array ) {
  42812. type = gl.INT;
  42813. } else if ( array instanceof Int8Array ) {
  42814. type = gl.BYTE;
  42815. } else if ( array instanceof Uint8Array ) {
  42816. type = gl.UNSIGNED_BYTE;
  42817. } else if ( array instanceof Uint8ClampedArray ) {
  42818. type = gl.UNSIGNED_BYTE;
  42819. } else {
  42820. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  42821. }
  42822. let attributeData = {
  42823. bufferGPU,
  42824. bufferType,
  42825. type,
  42826. byteLength: array.byteLength,
  42827. bytesPerElement: array.BYTES_PER_ELEMENT,
  42828. version: attribute.version,
  42829. pbo: attribute.pbo,
  42830. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  42831. id: _id$1 ++
  42832. };
  42833. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  42834. // create buffer for transform feedback use
  42835. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  42836. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  42837. }
  42838. backend.set( attribute, attributeData );
  42839. }
  42840. /**
  42841. * Updates the GPU buffer of the given buffer attribute.
  42842. *
  42843. * @param {BufferAttribute} attribute - The buffer attribute.
  42844. */
  42845. updateAttribute( attribute ) {
  42846. const backend = this.backend;
  42847. const { gl } = backend;
  42848. const array = attribute.array;
  42849. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42850. const bufferData = backend.get( bufferAttribute );
  42851. const bufferType = bufferData.bufferType;
  42852. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  42853. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  42854. if ( updateRanges.length === 0 ) {
  42855. // Not using update ranges
  42856. gl.bufferSubData( bufferType, 0, array );
  42857. } else {
  42858. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42859. const range = updateRanges[ i ];
  42860. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42861. array, range.start, range.count );
  42862. }
  42863. bufferAttribute.clearUpdateRanges();
  42864. }
  42865. gl.bindBuffer( bufferType, null );
  42866. bufferData.version = bufferAttribute.version;
  42867. }
  42868. /**
  42869. * Destroys the GPU buffer of the given buffer attribute.
  42870. *
  42871. * @param {BufferAttribute} attribute - The buffer attribute.
  42872. */
  42873. destroyAttribute( attribute ) {
  42874. const backend = this.backend;
  42875. const { gl } = backend;
  42876. if ( attribute.isInterleavedBufferAttribute ) {
  42877. backend.delete( attribute.data );
  42878. }
  42879. const attributeData = backend.get( attribute );
  42880. gl.deleteBuffer( attributeData.bufferGPU );
  42881. backend.delete( attribute );
  42882. }
  42883. /**
  42884. * This method performs a readback operation by moving buffer data from
  42885. * a storage buffer attribute from the GPU to the CPU.
  42886. *
  42887. * @async
  42888. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42889. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42890. */
  42891. async getArrayBufferAsync( attribute ) {
  42892. const backend = this.backend;
  42893. const { gl } = backend;
  42894. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42895. const { bufferGPU } = backend.get( bufferAttribute );
  42896. const array = attribute.array;
  42897. const byteLength = array.byteLength;
  42898. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  42899. const writeBuffer = gl.createBuffer();
  42900. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  42901. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  42902. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  42903. await backend.utils._clientWaitAsync();
  42904. const dstBuffer = new attribute.array.constructor( array.length );
  42905. // Ensure the buffer is bound before reading
  42906. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  42907. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  42908. gl.deleteBuffer( writeBuffer );
  42909. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  42910. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  42911. return dstBuffer.buffer;
  42912. }
  42913. /**
  42914. * Creates a WebGL buffer with the given data.
  42915. *
  42916. * @private
  42917. * @param {WebGL2RenderingContext} gl - The rendering context.
  42918. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  42919. * @param {TypedArray} array - The array of the buffer attribute.
  42920. * @param {GLenum} usage - The usage.
  42921. * @return {WebGLBuffer} The WebGL buffer.
  42922. */
  42923. _createBuffer( gl, bufferType, array, usage ) {
  42924. const bufferGPU = gl.createBuffer();
  42925. gl.bindBuffer( bufferType, bufferGPU );
  42926. gl.bufferData( bufferType, array, usage );
  42927. gl.bindBuffer( bufferType, null );
  42928. return bufferGPU;
  42929. }
  42930. }
  42931. let equationToGL, factorToGL;
  42932. /**
  42933. * A WebGL 2 backend utility module for managing the WebGL state.
  42934. *
  42935. * The major goal of this module is to reduce the number of state changes
  42936. * by caching the WEbGL state with a series of variables. In this way, the
  42937. * renderer only executes state change commands when necessary which
  42938. * improves the overall performance.
  42939. *
  42940. * @private
  42941. */
  42942. class WebGLState {
  42943. /**
  42944. * Constructs a new utility object.
  42945. *
  42946. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42947. */
  42948. constructor( backend ) {
  42949. /**
  42950. * A reference to the WebGL 2 backend.
  42951. *
  42952. * @type {WebGLBackend}
  42953. */
  42954. this.backend = backend;
  42955. /**
  42956. * A reference to the rendering context.
  42957. *
  42958. * @type {WebGL2RenderingContext}
  42959. */
  42960. this.gl = this.backend.gl;
  42961. // Below properties are intended to cache
  42962. // the WebGL state and are not explicitly
  42963. // documented for convenience reasons.
  42964. this.enabled = {};
  42965. this.currentFlipSided = null;
  42966. this.currentCullFace = null;
  42967. this.currentProgram = null;
  42968. this.currentBlendingEnabled = false;
  42969. this.currentBlending = null;
  42970. this.currentBlendSrc = null;
  42971. this.currentBlendDst = null;
  42972. this.currentBlendSrcAlpha = null;
  42973. this.currentBlendDstAlpha = null;
  42974. this.currentPremultipledAlpha = null;
  42975. this.currentPolygonOffsetFactor = null;
  42976. this.currentPolygonOffsetUnits = null;
  42977. this.currentColorMask = null;
  42978. this.currentDepthFunc = null;
  42979. this.currentDepthMask = null;
  42980. this.currentStencilFunc = null;
  42981. this.currentStencilRef = null;
  42982. this.currentStencilFuncMask = null;
  42983. this.currentStencilFail = null;
  42984. this.currentStencilZFail = null;
  42985. this.currentStencilZPass = null;
  42986. this.currentStencilMask = null;
  42987. this.currentLineWidth = null;
  42988. this.currentClippingPlanes = 0;
  42989. this.currentVAO = null;
  42990. this.currentIndex = null;
  42991. this.currentBoundFramebuffers = {};
  42992. this.currentDrawbuffers = new WeakMap();
  42993. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  42994. this.currentTextureSlot = null;
  42995. this.currentBoundTextures = {};
  42996. this.currentBoundBufferBases = {};
  42997. this._init();
  42998. }
  42999. /**
  43000. * Inits the state of the utility.
  43001. *
  43002. * @private
  43003. */
  43004. _init() {
  43005. const gl = this.gl;
  43006. // Store only WebGL constants here.
  43007. equationToGL = {
  43008. [ AddEquation ]: gl.FUNC_ADD,
  43009. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  43010. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  43011. };
  43012. factorToGL = {
  43013. [ ZeroFactor ]: gl.ZERO,
  43014. [ OneFactor ]: gl.ONE,
  43015. [ SrcColorFactor ]: gl.SRC_COLOR,
  43016. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  43017. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  43018. [ DstColorFactor ]: gl.DST_COLOR,
  43019. [ DstAlphaFactor ]: gl.DST_ALPHA,
  43020. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  43021. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  43022. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  43023. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  43024. };
  43025. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  43026. const viewportParam = gl.getParameter( gl.VIEWPORT );
  43027. this.currentScissor = new Vector4().fromArray( scissorParam );
  43028. this.currentViewport = new Vector4().fromArray( viewportParam );
  43029. this._tempVec4 = new Vector4();
  43030. }
  43031. /**
  43032. * Enables the given WebGL capability.
  43033. *
  43034. * This method caches the capability state so
  43035. * `gl.enable()` is only called when necessary.
  43036. *
  43037. * @param {GLenum} id - The capability to enable.
  43038. */
  43039. enable( id ) {
  43040. const { enabled } = this;
  43041. if ( enabled[ id ] !== true ) {
  43042. this.gl.enable( id );
  43043. enabled[ id ] = true;
  43044. }
  43045. }
  43046. /**
  43047. * Disables the given WebGL capability.
  43048. *
  43049. * This method caches the capability state so
  43050. * `gl.disable()` is only called when necessary.
  43051. *
  43052. * @param {GLenum} id - The capability to enable.
  43053. */
  43054. disable( id ) {
  43055. const { enabled } = this;
  43056. if ( enabled[ id ] !== false ) {
  43057. this.gl.disable( id );
  43058. enabled[ id ] = false;
  43059. }
  43060. }
  43061. /**
  43062. * Specifies whether polygons are front- or back-facing
  43063. * by setting the winding orientation.
  43064. *
  43065. * This method caches the state so `gl.frontFace()` is only
  43066. * called when necessary.
  43067. *
  43068. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  43069. */
  43070. setFlipSided( flipSided ) {
  43071. if ( this.currentFlipSided !== flipSided ) {
  43072. const { gl } = this;
  43073. if ( flipSided ) {
  43074. gl.frontFace( gl.CW );
  43075. } else {
  43076. gl.frontFace( gl.CCW );
  43077. }
  43078. this.currentFlipSided = flipSided;
  43079. }
  43080. }
  43081. /**
  43082. * Specifies whether or not front- and/or back-facing
  43083. * polygons can be culled.
  43084. *
  43085. * This method caches the state so `gl.cullFace()` is only
  43086. * called when necessary.
  43087. *
  43088. * @param {number} cullFace - Defines which polygons are candidates for culling.
  43089. */
  43090. setCullFace( cullFace ) {
  43091. const { gl } = this;
  43092. if ( cullFace !== CullFaceNone ) {
  43093. this.enable( gl.CULL_FACE );
  43094. if ( cullFace !== this.currentCullFace ) {
  43095. if ( cullFace === CullFaceBack ) {
  43096. gl.cullFace( gl.BACK );
  43097. } else if ( cullFace === CullFaceFront ) {
  43098. gl.cullFace( gl.FRONT );
  43099. } else {
  43100. gl.cullFace( gl.FRONT_AND_BACK );
  43101. }
  43102. }
  43103. } else {
  43104. this.disable( gl.CULL_FACE );
  43105. }
  43106. this.currentCullFace = cullFace;
  43107. }
  43108. /**
  43109. * Specifies the width of line primitives.
  43110. *
  43111. * This method caches the state so `gl.lineWidth()` is only
  43112. * called when necessary.
  43113. *
  43114. * @param {number} width - The line width.
  43115. */
  43116. setLineWidth( width ) {
  43117. const { currentLineWidth, gl } = this;
  43118. if ( width !== currentLineWidth ) {
  43119. gl.lineWidth( width );
  43120. this.currentLineWidth = width;
  43121. }
  43122. }
  43123. /**
  43124. * Defines the blending.
  43125. *
  43126. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  43127. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  43128. *
  43129. * @param {number} blending - The blending type.
  43130. * @param {number} blendEquation - The blending equation.
  43131. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  43132. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  43133. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  43134. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  43135. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  43136. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  43137. */
  43138. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  43139. const { gl } = this;
  43140. if ( blending === NoBlending ) {
  43141. if ( this.currentBlendingEnabled === true ) {
  43142. this.disable( gl.BLEND );
  43143. this.currentBlendingEnabled = false;
  43144. }
  43145. return;
  43146. }
  43147. if ( this.currentBlendingEnabled === false ) {
  43148. this.enable( gl.BLEND );
  43149. this.currentBlendingEnabled = true;
  43150. }
  43151. if ( blending !== CustomBlending ) {
  43152. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  43153. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  43154. gl.blendEquation( gl.FUNC_ADD );
  43155. this.currentBlendEquation = AddEquation;
  43156. this.currentBlendEquationAlpha = AddEquation;
  43157. }
  43158. if ( premultipliedAlpha ) {
  43159. switch ( blending ) {
  43160. case NormalBlending:
  43161. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  43162. break;
  43163. case AdditiveBlending:
  43164. gl.blendFunc( gl.ONE, gl.ONE );
  43165. break;
  43166. case SubtractiveBlending:
  43167. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  43168. break;
  43169. case MultiplyBlending:
  43170. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  43171. break;
  43172. default:
  43173. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  43174. break;
  43175. }
  43176. } else {
  43177. switch ( blending ) {
  43178. case NormalBlending:
  43179. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  43180. break;
  43181. case AdditiveBlending:
  43182. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  43183. break;
  43184. case SubtractiveBlending:
  43185. console.error( 'THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  43186. break;
  43187. case MultiplyBlending:
  43188. console.error( 'THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  43189. break;
  43190. default:
  43191. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  43192. break;
  43193. }
  43194. }
  43195. this.currentBlendSrc = null;
  43196. this.currentBlendDst = null;
  43197. this.currentBlendSrcAlpha = null;
  43198. this.currentBlendDstAlpha = null;
  43199. this.currentBlending = blending;
  43200. this.currentPremultipledAlpha = premultipliedAlpha;
  43201. }
  43202. return;
  43203. }
  43204. // custom blending
  43205. blendEquationAlpha = blendEquationAlpha || blendEquation;
  43206. blendSrcAlpha = blendSrcAlpha || blendSrc;
  43207. blendDstAlpha = blendDstAlpha || blendDst;
  43208. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  43209. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  43210. this.currentBlendEquation = blendEquation;
  43211. this.currentBlendEquationAlpha = blendEquationAlpha;
  43212. }
  43213. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  43214. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  43215. this.currentBlendSrc = blendSrc;
  43216. this.currentBlendDst = blendDst;
  43217. this.currentBlendSrcAlpha = blendSrcAlpha;
  43218. this.currentBlendDstAlpha = blendDstAlpha;
  43219. }
  43220. this.currentBlending = blending;
  43221. this.currentPremultipledAlpha = false;
  43222. }
  43223. /**
  43224. * Specifies whether colors can be written when rendering
  43225. * into a framebuffer or not.
  43226. *
  43227. * This method caches the state so `gl.colorMask()` is only
  43228. * called when necessary.
  43229. *
  43230. * @param {boolean} colorMask - The color mask.
  43231. */
  43232. setColorMask( colorMask ) {
  43233. if ( this.currentColorMask !== colorMask ) {
  43234. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  43235. this.currentColorMask = colorMask;
  43236. }
  43237. }
  43238. /**
  43239. * Specifies whether the depth test is enabled or not.
  43240. *
  43241. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  43242. */
  43243. setDepthTest( depthTest ) {
  43244. const { gl } = this;
  43245. if ( depthTest ) {
  43246. this.enable( gl.DEPTH_TEST );
  43247. } else {
  43248. this.disable( gl.DEPTH_TEST );
  43249. }
  43250. }
  43251. /**
  43252. * Specifies whether depth values can be written when rendering
  43253. * into a framebuffer or not.
  43254. *
  43255. * This method caches the state so `gl.depthMask()` is only
  43256. * called when necessary.
  43257. *
  43258. * @param {boolean} depthMask - The depth mask.
  43259. */
  43260. setDepthMask( depthMask ) {
  43261. if ( this.currentDepthMask !== depthMask ) {
  43262. this.gl.depthMask( depthMask );
  43263. this.currentDepthMask = depthMask;
  43264. }
  43265. }
  43266. /**
  43267. * Specifies the depth compare function.
  43268. *
  43269. * This method caches the state so `gl.depthFunc()` is only
  43270. * called when necessary.
  43271. *
  43272. * @param {number} depthFunc - The depth compare function.
  43273. */
  43274. setDepthFunc( depthFunc ) {
  43275. if ( this.currentDepthFunc !== depthFunc ) {
  43276. const { gl } = this;
  43277. switch ( depthFunc ) {
  43278. case NeverDepth:
  43279. gl.depthFunc( gl.NEVER );
  43280. break;
  43281. case AlwaysDepth:
  43282. gl.depthFunc( gl.ALWAYS );
  43283. break;
  43284. case LessDepth:
  43285. gl.depthFunc( gl.LESS );
  43286. break;
  43287. case LessEqualDepth:
  43288. gl.depthFunc( gl.LEQUAL );
  43289. break;
  43290. case EqualDepth:
  43291. gl.depthFunc( gl.EQUAL );
  43292. break;
  43293. case GreaterEqualDepth:
  43294. gl.depthFunc( gl.GEQUAL );
  43295. break;
  43296. case GreaterDepth:
  43297. gl.depthFunc( gl.GREATER );
  43298. break;
  43299. case NotEqualDepth:
  43300. gl.depthFunc( gl.NOTEQUAL );
  43301. break;
  43302. default:
  43303. gl.depthFunc( gl.LEQUAL );
  43304. }
  43305. this.currentDepthFunc = depthFunc;
  43306. }
  43307. }
  43308. /**
  43309. * Specifies the scissor box.
  43310. *
  43311. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  43312. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  43313. * @param {number} width - The width of the viewport.
  43314. * @param {number} height - The height of the viewport.
  43315. *
  43316. */
  43317. scissor( x, y, width, height ) {
  43318. const scissor = this._tempVec4.set( x, y, width, height );
  43319. if ( this.currentScissor.equals( scissor ) === false ) {
  43320. const { gl } = this;
  43321. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  43322. this.currentScissor.copy( scissor );
  43323. }
  43324. }
  43325. /**
  43326. * Specifies the viewport.
  43327. *
  43328. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  43329. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  43330. * @param {number} width - The width of the viewport.
  43331. * @param {number} height - The height of the viewport.
  43332. *
  43333. */
  43334. viewport( x, y, width, height ) {
  43335. const viewport = this._tempVec4.set( x, y, width, height );
  43336. if ( this.currentViewport.equals( viewport ) === false ) {
  43337. const { gl } = this;
  43338. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  43339. this.currentViewport.copy( viewport );
  43340. }
  43341. }
  43342. /**
  43343. * Defines the scissor test.
  43344. *
  43345. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43346. */
  43347. setScissorTest( boolean ) {
  43348. const gl = this.gl;
  43349. if ( boolean ) {
  43350. gl.enable( gl.SCISSOR_TEST );
  43351. } else {
  43352. gl.disable( gl.SCISSOR_TEST );
  43353. }
  43354. }
  43355. /**
  43356. * Specifies whether the stencil test is enabled or not.
  43357. *
  43358. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  43359. */
  43360. setStencilTest( stencilTest ) {
  43361. const { gl } = this;
  43362. if ( stencilTest ) {
  43363. this.enable( gl.STENCIL_TEST );
  43364. } else {
  43365. this.disable( gl.STENCIL_TEST );
  43366. }
  43367. }
  43368. /**
  43369. * Specifies whether stencil values can be written when rendering
  43370. * into a framebuffer or not.
  43371. *
  43372. * This method caches the state so `gl.stencilMask()` is only
  43373. * called when necessary.
  43374. *
  43375. * @param {boolean} stencilMask - The stencil mask.
  43376. */
  43377. setStencilMask( stencilMask ) {
  43378. if ( this.currentStencilMask !== stencilMask ) {
  43379. this.gl.stencilMask( stencilMask );
  43380. this.currentStencilMask = stencilMask;
  43381. }
  43382. }
  43383. /**
  43384. * Specifies whether the stencil test functions.
  43385. *
  43386. * This method caches the state so `gl.stencilFunc()` is only
  43387. * called when necessary.
  43388. *
  43389. * @param {number} stencilFunc - The stencil compare function.
  43390. * @param {number} stencilRef - The reference value for the stencil test.
  43391. * @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.
  43392. */
  43393. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  43394. if ( this.currentStencilFunc !== stencilFunc ||
  43395. this.currentStencilRef !== stencilRef ||
  43396. this.currentStencilFuncMask !== stencilMask ) {
  43397. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  43398. this.currentStencilFunc = stencilFunc;
  43399. this.currentStencilRef = stencilRef;
  43400. this.currentStencilFuncMask = stencilMask;
  43401. }
  43402. }
  43403. /**
  43404. * Specifies whether the stencil test operation.
  43405. *
  43406. * This method caches the state so `gl.stencilOp()` is only
  43407. * called when necessary.
  43408. *
  43409. * @param {number} stencilFail - The function to use when the stencil test fails.
  43410. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  43411. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  43412. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  43413. */
  43414. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  43415. if ( this.currentStencilFail !== stencilFail ||
  43416. this.currentStencilZFail !== stencilZFail ||
  43417. this.currentStencilZPass !== stencilZPass ) {
  43418. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  43419. this.currentStencilFail = stencilFail;
  43420. this.currentStencilZFail = stencilZFail;
  43421. this.currentStencilZPass = stencilZPass;
  43422. }
  43423. }
  43424. /**
  43425. * Configures the WebGL state for the given material.
  43426. *
  43427. * @param {Material} material - The material to configure the state for.
  43428. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  43429. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  43430. */
  43431. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  43432. const { gl } = this;
  43433. material.side === DoubleSide
  43434. ? this.disable( gl.CULL_FACE )
  43435. : this.enable( gl.CULL_FACE );
  43436. let flipSided = ( material.side === BackSide );
  43437. if ( frontFaceCW ) flipSided = ! flipSided;
  43438. this.setFlipSided( flipSided );
  43439. ( material.blending === NormalBlending && material.transparent === false )
  43440. ? this.setBlending( NoBlending )
  43441. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  43442. this.setDepthFunc( material.depthFunc );
  43443. this.setDepthTest( material.depthTest );
  43444. this.setDepthMask( material.depthWrite );
  43445. this.setColorMask( material.colorWrite );
  43446. const stencilWrite = material.stencilWrite;
  43447. this.setStencilTest( stencilWrite );
  43448. if ( stencilWrite ) {
  43449. this.setStencilMask( material.stencilWriteMask );
  43450. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  43451. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  43452. }
  43453. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  43454. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  43455. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  43456. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  43457. if ( hardwareClippingPlanes > 0 ) {
  43458. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  43459. const CLIP_DISTANCE0_WEBGL = 0x3000;
  43460. for ( let i = 0; i < 8; i ++ ) {
  43461. if ( i < hardwareClippingPlanes ) {
  43462. this.enable( CLIP_DISTANCE0_WEBGL + i );
  43463. } else {
  43464. this.disable( CLIP_DISTANCE0_WEBGL + i );
  43465. }
  43466. }
  43467. }
  43468. }
  43469. }
  43470. /**
  43471. * Specifies the polygon offset.
  43472. *
  43473. * This method caches the state so `gl.polygonOffset()` is only
  43474. * called when necessary.
  43475. *
  43476. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  43477. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  43478. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  43479. */
  43480. setPolygonOffset( polygonOffset, factor, units ) {
  43481. const { gl } = this;
  43482. if ( polygonOffset ) {
  43483. this.enable( gl.POLYGON_OFFSET_FILL );
  43484. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  43485. gl.polygonOffset( factor, units );
  43486. this.currentPolygonOffsetFactor = factor;
  43487. this.currentPolygonOffsetUnits = units;
  43488. }
  43489. } else {
  43490. this.disable( gl.POLYGON_OFFSET_FILL );
  43491. }
  43492. }
  43493. /**
  43494. * Defines the usage of the given WebGL program.
  43495. *
  43496. * This method caches the state so `gl.useProgram()` is only
  43497. * called when necessary.
  43498. *
  43499. * @param {WebGLProgram} program - The WebGL program to use.
  43500. * @return {boolean} Whether a program change has been executed or not.
  43501. */
  43502. useProgram( program ) {
  43503. if ( this.currentProgram !== program ) {
  43504. this.gl.useProgram( program );
  43505. this.currentProgram = program;
  43506. return true;
  43507. }
  43508. return false;
  43509. }
  43510. /**
  43511. * Sets the vertex state by binding the given VAO and element buffer.
  43512. *
  43513. * @param {WebGLVertexArrayObject} vao - The VAO.
  43514. * @param {WebGLBuffer} indexBuffer - The index buffer.
  43515. * @return {boolean} Whether a vertex state has been changed or not.
  43516. */
  43517. setVertexState( vao, indexBuffer = null ) {
  43518. const gl = this.gl;
  43519. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  43520. gl.bindVertexArray( vao );
  43521. if ( indexBuffer !== null ) {
  43522. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  43523. }
  43524. this.currentVAO = vao;
  43525. this.currentIndex = indexBuffer;
  43526. return true;
  43527. }
  43528. return false;
  43529. }
  43530. /**
  43531. * Resets the vertex array state by resetting the VAO and element buffer.
  43532. */
  43533. resetVertexState() {
  43534. const gl = this.gl;
  43535. gl.bindVertexArray( null );
  43536. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  43537. this.currentVAO = null;
  43538. this.currentIndex = null;
  43539. }
  43540. // framebuffer
  43541. /**
  43542. * Binds the given framebuffer.
  43543. *
  43544. * This method caches the state so `gl.bindFramebuffer()` is only
  43545. * called when necessary.
  43546. *
  43547. * @param {number} target - The binding point (target).
  43548. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  43549. * @return {boolean} Whether a bind has been executed or not.
  43550. */
  43551. bindFramebuffer( target, framebuffer ) {
  43552. const { gl, currentBoundFramebuffers } = this;
  43553. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  43554. gl.bindFramebuffer( target, framebuffer );
  43555. currentBoundFramebuffers[ target ] = framebuffer;
  43556. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  43557. if ( target === gl.DRAW_FRAMEBUFFER ) {
  43558. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  43559. }
  43560. if ( target === gl.FRAMEBUFFER ) {
  43561. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  43562. }
  43563. return true;
  43564. }
  43565. return false;
  43566. }
  43567. /**
  43568. * Defines draw buffers to which fragment colors are written into.
  43569. * Configures the MRT setup of custom framebuffers.
  43570. *
  43571. * This method caches the state so `gl.drawBuffers()` is only
  43572. * called when necessary.
  43573. *
  43574. * @param {RenderContext} renderContext - The render context.
  43575. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  43576. */
  43577. drawBuffers( renderContext, framebuffer ) {
  43578. const { gl } = this;
  43579. let drawBuffers = [];
  43580. let needsUpdate = false;
  43581. if ( renderContext.textures !== null ) {
  43582. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  43583. if ( drawBuffers === undefined ) {
  43584. drawBuffers = [];
  43585. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  43586. }
  43587. const textures = renderContext.textures;
  43588. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  43589. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  43590. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  43591. }
  43592. drawBuffers.length = textures.length;
  43593. needsUpdate = true;
  43594. }
  43595. } else {
  43596. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  43597. drawBuffers[ 0 ] = gl.BACK;
  43598. needsUpdate = true;
  43599. }
  43600. }
  43601. if ( needsUpdate ) {
  43602. gl.drawBuffers( drawBuffers );
  43603. }
  43604. }
  43605. // texture
  43606. /**
  43607. * Makes the given texture unit active.
  43608. *
  43609. * This method caches the state so `gl.activeTexture()` is only
  43610. * called when necessary.
  43611. *
  43612. * @param {number} webglSlot - The texture unit to make active.
  43613. */
  43614. activeTexture( webglSlot ) {
  43615. const { gl, currentTextureSlot, maxTextures } = this;
  43616. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  43617. if ( currentTextureSlot !== webglSlot ) {
  43618. gl.activeTexture( webglSlot );
  43619. this.currentTextureSlot = webglSlot;
  43620. }
  43621. }
  43622. /**
  43623. * Binds the given WebGL texture to a target.
  43624. *
  43625. * This method caches the state so `gl.bindTexture()` is only
  43626. * called when necessary.
  43627. *
  43628. * @param {number} webglType - The binding point (target).
  43629. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  43630. * @param {number} webglSlot - The texture.
  43631. */
  43632. bindTexture( webglType, webglTexture, webglSlot ) {
  43633. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  43634. if ( webglSlot === undefined ) {
  43635. if ( currentTextureSlot === null ) {
  43636. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  43637. } else {
  43638. webglSlot = currentTextureSlot;
  43639. }
  43640. }
  43641. let boundTexture = currentBoundTextures[ webglSlot ];
  43642. if ( boundTexture === undefined ) {
  43643. boundTexture = { type: undefined, texture: undefined };
  43644. currentBoundTextures[ webglSlot ] = boundTexture;
  43645. }
  43646. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  43647. if ( currentTextureSlot !== webglSlot ) {
  43648. gl.activeTexture( webglSlot );
  43649. this.currentTextureSlot = webglSlot;
  43650. }
  43651. gl.bindTexture( webglType, webglTexture );
  43652. boundTexture.type = webglType;
  43653. boundTexture.texture = webglTexture;
  43654. }
  43655. }
  43656. /**
  43657. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  43658. *
  43659. * This method caches the state so `gl.bindBufferBase()` is only
  43660. * called when necessary.
  43661. *
  43662. * @param {number} target - The target for the bind operation.
  43663. * @param {number} index - The index of the target.
  43664. * @param {WebGLBuffer} buffer - The WebGL buffer.
  43665. * @return {boolean} Whether a bind has been executed or not.
  43666. */
  43667. bindBufferBase( target, index, buffer ) {
  43668. const { gl } = this;
  43669. const key = `${target}-${index}`;
  43670. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  43671. gl.bindBufferBase( target, index, buffer );
  43672. this.currentBoundBufferBases[ key ] = buffer;
  43673. return true;
  43674. }
  43675. return false;
  43676. }
  43677. /**
  43678. * Unbinds the current bound texture.
  43679. *
  43680. * This method caches the state so `gl.bindTexture()` is only
  43681. * called when necessary.
  43682. */
  43683. unbindTexture() {
  43684. const { gl, currentTextureSlot, currentBoundTextures } = this;
  43685. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  43686. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  43687. gl.bindTexture( boundTexture.type, null );
  43688. boundTexture.type = undefined;
  43689. boundTexture.texture = undefined;
  43690. }
  43691. }
  43692. }
  43693. /**
  43694. * A WebGL 2 backend utility module with common helpers.
  43695. *
  43696. * @private
  43697. */
  43698. class WebGLUtils {
  43699. /**
  43700. * Constructs a new utility object.
  43701. *
  43702. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43703. */
  43704. constructor( backend ) {
  43705. /**
  43706. * A reference to the WebGL 2 backend.
  43707. *
  43708. * @type {WebGLBackend}
  43709. */
  43710. this.backend = backend;
  43711. /**
  43712. * A reference to the rendering context.
  43713. *
  43714. * @type {WebGL2RenderingContext}
  43715. */
  43716. this.gl = this.backend.gl;
  43717. /**
  43718. * A reference to a backend module holding extension-related
  43719. * utility functions.
  43720. *
  43721. * @type {WebGLExtensions}
  43722. */
  43723. this.extensions = backend.extensions;
  43724. }
  43725. /**
  43726. * Converts the given three.js constant into a WebGL constant.
  43727. * The method currently supports the conversion of texture formats
  43728. * and types.
  43729. *
  43730. * @param {number} p - The three.js constant.
  43731. * @param {string} [colorSpace=NoColorSpace] - The color space.
  43732. * @return {?number} The corresponding WebGL constant.
  43733. */
  43734. convert( p, colorSpace = NoColorSpace ) {
  43735. const { gl, extensions } = this;
  43736. let extension;
  43737. const transfer = ColorManagement.getTransfer( colorSpace );
  43738. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  43739. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  43740. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  43741. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  43742. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  43743. if ( p === ByteType ) return gl.BYTE;
  43744. if ( p === ShortType ) return gl.SHORT;
  43745. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  43746. if ( p === IntType ) return gl.INT;
  43747. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  43748. if ( p === FloatType ) return gl.FLOAT;
  43749. if ( p === HalfFloatType ) {
  43750. return gl.HALF_FLOAT;
  43751. }
  43752. if ( p === AlphaFormat ) return gl.ALPHA;
  43753. if ( p === RGBFormat ) return gl.RGB;
  43754. if ( p === RGBAFormat ) return gl.RGBA;
  43755. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  43756. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  43757. // WebGL2 formats.
  43758. if ( p === RedFormat ) return gl.RED;
  43759. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  43760. if ( p === RGFormat ) return gl.RG;
  43761. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  43762. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  43763. // S3TC
  43764. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  43765. if ( transfer === SRGBTransfer ) {
  43766. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  43767. if ( extension !== null ) {
  43768. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  43769. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  43770. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  43771. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  43772. } else {
  43773. return null;
  43774. }
  43775. } else {
  43776. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  43777. if ( extension !== null ) {
  43778. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  43779. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  43780. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  43781. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  43782. } else {
  43783. return null;
  43784. }
  43785. }
  43786. }
  43787. // PVRTC
  43788. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  43789. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  43790. if ( extension !== null ) {
  43791. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  43792. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  43793. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  43794. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  43795. } else {
  43796. return null;
  43797. }
  43798. }
  43799. // ETC
  43800. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  43801. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  43802. if ( extension !== null ) {
  43803. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  43804. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  43805. } else {
  43806. return null;
  43807. }
  43808. }
  43809. // ASTC
  43810. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  43811. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  43812. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  43813. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  43814. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  43815. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  43816. if ( extension !== null ) {
  43817. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  43818. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  43819. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  43820. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  43821. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  43822. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  43823. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  43824. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  43825. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  43826. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  43827. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  43828. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  43829. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  43830. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  43831. } else {
  43832. return null;
  43833. }
  43834. }
  43835. // BPTC
  43836. if ( p === RGBA_BPTC_Format ) {
  43837. extension = extensions.get( 'EXT_texture_compression_bptc' );
  43838. if ( extension !== null ) {
  43839. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  43840. } else {
  43841. return null;
  43842. }
  43843. }
  43844. // RGTC
  43845. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  43846. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  43847. if ( extension !== null ) {
  43848. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  43849. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  43850. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  43851. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  43852. } else {
  43853. return null;
  43854. }
  43855. }
  43856. //
  43857. if ( p === UnsignedInt248Type ) {
  43858. return gl.UNSIGNED_INT_24_8;
  43859. }
  43860. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  43861. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  43862. }
  43863. /**
  43864. * This method can be used to synchronize the CPU with the GPU by waiting until
  43865. * ongoing GPU commands have been completed.
  43866. *
  43867. * @private
  43868. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  43869. */
  43870. _clientWaitAsync() {
  43871. const { gl } = this;
  43872. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  43873. gl.flush();
  43874. return new Promise( ( resolve, reject ) => {
  43875. function test() {
  43876. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  43877. if ( res === gl.WAIT_FAILED ) {
  43878. gl.deleteSync( sync );
  43879. reject();
  43880. return;
  43881. }
  43882. if ( res === gl.TIMEOUT_EXPIRED ) {
  43883. requestAnimationFrame( test );
  43884. return;
  43885. }
  43886. gl.deleteSync( sync );
  43887. resolve();
  43888. }
  43889. test();
  43890. } );
  43891. }
  43892. }
  43893. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  43894. /**
  43895. * A WebGL 2 backend utility module for managing textures.
  43896. *
  43897. * @private
  43898. */
  43899. class WebGLTextureUtils {
  43900. /**
  43901. * Constructs a new utility object.
  43902. *
  43903. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43904. */
  43905. constructor( backend ) {
  43906. /**
  43907. * A reference to the WebGL 2 backend.
  43908. *
  43909. * @type {WebGLBackend}
  43910. */
  43911. this.backend = backend;
  43912. /**
  43913. * A reference to the rendering context.
  43914. *
  43915. * @type {WebGL2RenderingContext}
  43916. */
  43917. this.gl = backend.gl;
  43918. /**
  43919. * A reference to a backend module holding extension-related
  43920. * utility functions.
  43921. *
  43922. * @type {WebGLExtensions}
  43923. */
  43924. this.extensions = backend.extensions;
  43925. /**
  43926. * A dictionary for managing default textures. The key
  43927. * is the binding point (target), the value the WEbGL texture object.
  43928. *
  43929. * @type {Object<GLenum,WebGLTexture>}
  43930. */
  43931. this.defaultTextures = {};
  43932. if ( initialized === false ) {
  43933. this._init();
  43934. initialized = true;
  43935. }
  43936. }
  43937. /**
  43938. * Inits the state of the utility.
  43939. *
  43940. * @private
  43941. */
  43942. _init() {
  43943. const gl = this.gl;
  43944. // Store only WebGL constants here.
  43945. wrappingToGL = {
  43946. [ RepeatWrapping ]: gl.REPEAT,
  43947. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  43948. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  43949. };
  43950. filterToGL = {
  43951. [ NearestFilter ]: gl.NEAREST,
  43952. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  43953. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  43954. [ LinearFilter ]: gl.LINEAR,
  43955. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  43956. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  43957. };
  43958. compareToGL = {
  43959. [ NeverCompare ]: gl.NEVER,
  43960. [ AlwaysCompare ]: gl.ALWAYS,
  43961. [ LessCompare ]: gl.LESS,
  43962. [ LessEqualCompare ]: gl.LEQUAL,
  43963. [ EqualCompare ]: gl.EQUAL,
  43964. [ GreaterEqualCompare ]: gl.GEQUAL,
  43965. [ GreaterCompare ]: gl.GREATER,
  43966. [ NotEqualCompare ]: gl.NOTEQUAL
  43967. };
  43968. }
  43969. /**
  43970. * Returns the native texture type for the given texture.
  43971. *
  43972. * @param {Texture} texture - The texture.
  43973. * @return {GLenum} The native texture type.
  43974. */
  43975. getGLTextureType( texture ) {
  43976. const { gl } = this;
  43977. let glTextureType;
  43978. if ( texture.isCubeTexture === true ) {
  43979. glTextureType = gl.TEXTURE_CUBE_MAP;
  43980. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43981. glTextureType = gl.TEXTURE_2D_ARRAY;
  43982. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  43983. glTextureType = gl.TEXTURE_3D;
  43984. } else {
  43985. glTextureType = gl.TEXTURE_2D;
  43986. }
  43987. return glTextureType;
  43988. }
  43989. /**
  43990. * Returns the native texture type for the given texture.
  43991. *
  43992. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  43993. * @param {GLenum} glFormat - The WebGL format.
  43994. * @param {GLenum} glType - The WebGL type.
  43995. * @param {string} colorSpace - The texture's color space.
  43996. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  43997. * @return {GLenum} The internal format.
  43998. */
  43999. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  44000. const { gl, extensions } = this;
  44001. if ( internalFormatName !== null ) {
  44002. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  44003. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  44004. }
  44005. let internalFormat = glFormat;
  44006. if ( glFormat === gl.RED ) {
  44007. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  44008. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  44009. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  44010. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  44011. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  44012. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  44013. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  44014. if ( glType === gl.INT ) internalFormat = gl.R32I;
  44015. }
  44016. if ( glFormat === gl.RED_INTEGER ) {
  44017. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  44018. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  44019. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  44020. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  44021. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  44022. if ( glType === gl.INT ) internalFormat = gl.R32I;
  44023. }
  44024. if ( glFormat === gl.RG ) {
  44025. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  44026. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  44027. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  44028. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  44029. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  44030. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  44031. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  44032. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  44033. }
  44034. if ( glFormat === gl.RG_INTEGER ) {
  44035. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  44036. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  44037. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  44038. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  44039. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  44040. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  44041. }
  44042. if ( glFormat === gl.RGB ) {
  44043. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  44044. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  44045. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  44046. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  44047. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  44048. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  44049. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  44050. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  44051. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  44052. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  44053. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  44054. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  44055. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  44056. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  44057. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  44058. }
  44059. if ( glFormat === gl.RGB_INTEGER ) {
  44060. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  44061. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  44062. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  44063. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  44064. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  44065. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  44066. }
  44067. if ( glFormat === gl.RGBA ) {
  44068. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  44069. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  44070. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  44071. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  44072. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  44073. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  44074. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  44075. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  44076. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  44077. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  44078. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  44079. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  44080. }
  44081. if ( glFormat === gl.RGBA_INTEGER ) {
  44082. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  44083. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  44084. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  44085. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  44086. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  44087. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  44088. }
  44089. if ( glFormat === gl.DEPTH_COMPONENT ) {
  44090. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  44091. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  44092. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  44093. }
  44094. if ( glFormat === gl.DEPTH_STENCIL ) {
  44095. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  44096. }
  44097. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  44098. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  44099. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  44100. extensions.get( 'EXT_color_buffer_float' );
  44101. }
  44102. return internalFormat;
  44103. }
  44104. /**
  44105. * Sets the texture parameters for the given texture.
  44106. *
  44107. * @param {GLenum} textureType - The texture type.
  44108. * @param {Texture} texture - The texture.
  44109. */
  44110. setTextureParameters( textureType, texture ) {
  44111. const { gl, extensions, backend } = this;
  44112. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  44113. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  44114. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  44115. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  44116. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  44117. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  44118. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  44119. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  44120. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  44121. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  44122. // WebGL 2 does not support wrapping for depth 2D array textures
  44123. if ( ! texture.isArrayTexture ) {
  44124. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  44125. }
  44126. }
  44127. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  44128. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  44129. // follow WebGPU backend mapping for texture filtering
  44130. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  44131. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  44132. if ( texture.compareFunction ) {
  44133. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  44134. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  44135. }
  44136. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44137. if ( texture.magFilter === NearestFilter ) return;
  44138. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  44139. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  44140. if ( texture.anisotropy > 1 ) {
  44141. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44142. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  44143. }
  44144. }
  44145. }
  44146. /**
  44147. * Creates a default texture for the given texture that can be used
  44148. * as a placeholder until the actual texture is ready for usage.
  44149. *
  44150. * @param {Texture} texture - The texture to create a default texture for.
  44151. */
  44152. createDefaultTexture( texture ) {
  44153. const { gl, backend, defaultTextures } = this;
  44154. const glTextureType = this.getGLTextureType( texture );
  44155. let textureGPU = defaultTextures[ glTextureType ];
  44156. if ( textureGPU === undefined ) {
  44157. textureGPU = gl.createTexture();
  44158. backend.state.bindTexture( glTextureType, textureGPU );
  44159. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  44160. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  44161. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  44162. defaultTextures[ glTextureType ] = textureGPU;
  44163. }
  44164. backend.set( texture, {
  44165. textureGPU,
  44166. glTextureType,
  44167. isDefault: true
  44168. } );
  44169. }
  44170. /**
  44171. * Defines a texture on the GPU for the given texture object.
  44172. *
  44173. * @param {Texture} texture - The texture.
  44174. * @param {Object} [options={}] - Optional configuration parameter.
  44175. * @return {undefined}
  44176. */
  44177. createTexture( texture, options ) {
  44178. const { gl, backend } = this;
  44179. const { levels, width, height, depth } = options;
  44180. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  44181. const glType = backend.utils.convert( texture.type );
  44182. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  44183. const textureGPU = gl.createTexture();
  44184. const glTextureType = this.getGLTextureType( texture );
  44185. backend.state.bindTexture( glTextureType, textureGPU );
  44186. this.setTextureParameters( glTextureType, texture );
  44187. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  44188. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  44189. } else if ( texture.isData3DTexture ) {
  44190. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  44191. } else if ( ! texture.isVideoTexture ) {
  44192. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  44193. }
  44194. backend.set( texture, {
  44195. textureGPU,
  44196. glTextureType,
  44197. glFormat,
  44198. glType,
  44199. glInternalFormat
  44200. } );
  44201. }
  44202. /**
  44203. * Uploads texture buffer data to the GPU memory.
  44204. *
  44205. * @param {WebGLBuffer} buffer - The buffer data.
  44206. * @param {Texture} texture - The texture,
  44207. */
  44208. copyBufferToTexture( buffer, texture ) {
  44209. const { gl, backend } = this;
  44210. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  44211. const { width, height } = texture.source.data;
  44212. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  44213. backend.state.bindTexture( glTextureType, textureGPU );
  44214. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  44215. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  44216. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  44217. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  44218. backend.state.unbindTexture();
  44219. // debug
  44220. // const framebuffer = gl.createFramebuffer();
  44221. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  44222. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  44223. // const readout = new Float32Array( width * height * 4 );
  44224. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  44225. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  44226. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  44227. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  44228. // console.log( readout );
  44229. }
  44230. /**
  44231. * Uploads the updated texture data to the GPU.
  44232. *
  44233. * @param {Texture} texture - The texture.
  44234. * @param {Object} [options={}] - Optional configuration parameter.
  44235. */
  44236. updateTexture( texture, options ) {
  44237. const { gl } = this;
  44238. const { width, height } = options;
  44239. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  44240. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  44241. return;
  44242. this.backend.state.bindTexture( glTextureType, textureGPU );
  44243. this.setTextureParameters( glTextureType, texture );
  44244. if ( texture.isCompressedTexture ) {
  44245. const mipmaps = texture.mipmaps;
  44246. const image = options.image;
  44247. for ( let i = 0; i < mipmaps.length; i ++ ) {
  44248. const mipmap = mipmaps[ i ];
  44249. if ( texture.isCompressedArrayTexture ) {
  44250. if ( texture.format !== gl.RGBA ) {
  44251. if ( glFormat !== null ) {
  44252. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  44253. } else {
  44254. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  44255. }
  44256. } else {
  44257. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  44258. }
  44259. } else {
  44260. if ( glFormat !== null ) {
  44261. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  44262. } else {
  44263. console.warn( 'Unsupported compressed texture format' );
  44264. }
  44265. }
  44266. }
  44267. } else if ( texture.isCubeTexture ) {
  44268. const images = options.images;
  44269. const mipmaps = texture.mipmaps;
  44270. for ( let i = 0; i < 6; i ++ ) {
  44271. const image = getImage( images[ i ] );
  44272. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  44273. for ( let j = 0; j < mipmaps.length; j ++ ) {
  44274. const mipmap = mipmaps[ j ];
  44275. const image = getImage( mipmap.images[ i ] );
  44276. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  44277. }
  44278. }
  44279. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  44280. const image = options.image;
  44281. if ( texture.layerUpdates.size > 0 ) {
  44282. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  44283. for ( const layerIndex of texture.layerUpdates ) {
  44284. const layerData = image.data.subarray(
  44285. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  44286. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  44287. );
  44288. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  44289. }
  44290. texture.clearLayerUpdates();
  44291. } else {
  44292. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  44293. }
  44294. } else if ( texture.isData3DTexture ) {
  44295. const image = options.image;
  44296. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  44297. } else if ( texture.isVideoTexture ) {
  44298. texture.update();
  44299. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  44300. } else {
  44301. const mipmaps = texture.mipmaps;
  44302. if ( mipmaps.length > 0 ) {
  44303. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  44304. const mipmap = mipmaps[ i ];
  44305. const image = getImage( mipmap );
  44306. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  44307. }
  44308. } else {
  44309. const image = getImage( options.image );
  44310. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  44311. }
  44312. }
  44313. }
  44314. /**
  44315. * Generates mipmaps for the given texture.
  44316. *
  44317. * @param {Texture} texture - The texture.
  44318. */
  44319. generateMipmaps( texture ) {
  44320. const { gl, backend } = this;
  44321. const { textureGPU, glTextureType } = backend.get( texture );
  44322. backend.state.bindTexture( glTextureType, textureGPU );
  44323. gl.generateMipmap( glTextureType );
  44324. }
  44325. /**
  44326. * Deallocates the render buffers of the given render target.
  44327. *
  44328. * @param {RenderTarget} renderTarget - The render target.
  44329. */
  44330. deallocateRenderBuffers( renderTarget ) {
  44331. const { gl, backend } = this;
  44332. // remove framebuffer reference
  44333. if ( renderTarget ) {
  44334. const renderContextData = backend.get( renderTarget );
  44335. renderContextData.renderBufferStorageSetup = undefined;
  44336. if ( renderContextData.framebuffers ) {
  44337. for ( const cacheKey in renderContextData.framebuffers ) {
  44338. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  44339. }
  44340. delete renderContextData.framebuffers;
  44341. }
  44342. if ( renderContextData.depthRenderbuffer ) {
  44343. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  44344. delete renderContextData.depthRenderbuffer;
  44345. }
  44346. if ( renderContextData.stencilRenderbuffer ) {
  44347. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  44348. delete renderContextData.stencilRenderbuffer;
  44349. }
  44350. if ( renderContextData.msaaFrameBuffer ) {
  44351. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  44352. delete renderContextData.msaaFrameBuffer;
  44353. }
  44354. if ( renderContextData.msaaRenderbuffers ) {
  44355. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  44356. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  44357. }
  44358. delete renderContextData.msaaRenderbuffers;
  44359. }
  44360. }
  44361. }
  44362. /**
  44363. * Destroys the GPU data for the given texture object.
  44364. *
  44365. * @param {Texture} texture - The texture.
  44366. */
  44367. destroyTexture( texture ) {
  44368. const { gl, backend } = this;
  44369. const { textureGPU, renderTarget } = backend.get( texture );
  44370. this.deallocateRenderBuffers( renderTarget );
  44371. gl.deleteTexture( textureGPU );
  44372. backend.delete( texture );
  44373. }
  44374. /**
  44375. * Copies data of the given source texture to the given destination texture.
  44376. *
  44377. * @param {Texture} srcTexture - The source texture.
  44378. * @param {Texture} dstTexture - The destination texture.
  44379. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44380. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44381. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44382. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44383. */
  44384. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44385. const { gl, backend } = this;
  44386. const { state } = this.backend;
  44387. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  44388. state.bindTexture( glTextureType, dstTextureGPU );
  44389. // gather the necessary dimensions to copy
  44390. let width, height, depth, minX, minY, minZ;
  44391. let dstX, dstY, dstZ;
  44392. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  44393. if ( srcRegion !== null ) {
  44394. width = srcRegion.max.x - srcRegion.min.x;
  44395. height = srcRegion.max.y - srcRegion.min.y;
  44396. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  44397. minX = srcRegion.min.x;
  44398. minY = srcRegion.min.y;
  44399. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  44400. } else {
  44401. const levelScale = Math.pow( 2, - srcLevel );
  44402. width = Math.floor( image.width * levelScale );
  44403. height = Math.floor( image.height * levelScale );
  44404. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  44405. depth = image.depth;
  44406. } else if ( srcTexture.isData3DTexture ) {
  44407. depth = Math.floor( image.depth * levelScale );
  44408. } else {
  44409. depth = 1;
  44410. }
  44411. minX = 0;
  44412. minY = 0;
  44413. minZ = 0;
  44414. }
  44415. if ( dstPosition !== null ) {
  44416. dstX = dstPosition.x;
  44417. dstY = dstPosition.y;
  44418. dstZ = dstPosition.z;
  44419. } else {
  44420. dstX = 0;
  44421. dstY = 0;
  44422. dstZ = 0;
  44423. }
  44424. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  44425. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  44426. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  44427. // used for copying data from cpu
  44428. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  44429. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  44430. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  44431. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  44432. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  44433. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  44434. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  44435. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  44436. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  44437. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  44438. // set up the src texture
  44439. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  44440. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  44441. const srcTextureData = backend.get( srcTexture );
  44442. const dstTextureData = backend.get( dstTexture );
  44443. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  44444. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  44445. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  44446. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  44447. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  44448. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  44449. let mask = gl.COLOR_BUFFER_BIT;
  44450. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  44451. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  44452. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  44453. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  44454. } else {
  44455. if ( isDst3D ) {
  44456. // copy data into the 3d texture
  44457. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  44458. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  44459. } else if ( dstTexture.isCompressedArrayTexture ) {
  44460. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  44461. } else {
  44462. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  44463. }
  44464. } else {
  44465. // copy data into the 2d texture
  44466. if ( srcTexture.isDataTexture ) {
  44467. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  44468. } else if ( srcTexture.isCompressedTexture ) {
  44469. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  44470. } else {
  44471. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  44472. }
  44473. }
  44474. }
  44475. // reset values
  44476. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  44477. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  44478. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  44479. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  44480. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  44481. // Generate mipmaps only when copying level 0
  44482. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  44483. gl.generateMipmap( glTextureType );
  44484. }
  44485. state.unbindTexture();
  44486. }
  44487. /**
  44488. * Copies the current bound framebuffer to the given texture.
  44489. *
  44490. * @param {Texture} texture - The destination texture.
  44491. * @param {RenderContext} renderContext - The render context.
  44492. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44493. */
  44494. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  44495. const { gl } = this;
  44496. const { state } = this.backend;
  44497. const { textureGPU } = this.backend.get( texture );
  44498. const { x, y, z: width, w: height } = rectangle;
  44499. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  44500. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  44501. if ( requireDrawFrameBuffer ) {
  44502. const partial = ( x !== 0 || y !== 0 );
  44503. let mask;
  44504. let attachment;
  44505. if ( texture.isDepthTexture === true ) {
  44506. mask = gl.DEPTH_BUFFER_BIT;
  44507. attachment = gl.DEPTH_ATTACHMENT;
  44508. if ( renderContext.stencil ) {
  44509. mask |= gl.STENCIL_BUFFER_BIT;
  44510. }
  44511. } else {
  44512. mask = gl.COLOR_BUFFER_BIT;
  44513. attachment = gl.COLOR_ATTACHMENT0;
  44514. }
  44515. if ( partial ) {
  44516. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  44517. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  44518. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44519. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44520. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  44521. const flippedY = srcHeight - y - height;
  44522. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  44523. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  44524. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  44525. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  44526. state.unbindTexture();
  44527. } else {
  44528. const fb = gl.createFramebuffer();
  44529. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44530. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  44531. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  44532. gl.deleteFramebuffer( fb );
  44533. }
  44534. } else {
  44535. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  44536. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  44537. state.unbindTexture();
  44538. }
  44539. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  44540. this.backend._setFramebuffer( renderContext );
  44541. }
  44542. /**
  44543. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  44544. *
  44545. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  44546. * @param {RenderContext} renderContext - The render context.
  44547. * @param {number} samples - The MSAA sample count.
  44548. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  44549. */
  44550. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  44551. const { gl } = this;
  44552. const renderTarget = renderContext.renderTarget;
  44553. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  44554. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44555. if ( depthBuffer && ! stencilBuffer ) {
  44556. let glInternalFormat = gl.DEPTH_COMPONENT24;
  44557. if ( useMultisampledRTT === true ) {
  44558. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44559. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  44560. } else if ( samples > 0 ) {
  44561. if ( depthTexture && depthTexture.isDepthTexture ) {
  44562. if ( depthTexture.type === gl.FLOAT ) {
  44563. glInternalFormat = gl.DEPTH_COMPONENT32F;
  44564. }
  44565. }
  44566. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  44567. } else {
  44568. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  44569. }
  44570. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  44571. } else if ( depthBuffer && stencilBuffer ) {
  44572. if ( samples > 0 ) {
  44573. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  44574. } else {
  44575. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  44576. }
  44577. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  44578. }
  44579. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  44580. }
  44581. /**
  44582. * Returns texture data as a typed array.
  44583. *
  44584. * @async
  44585. * @param {Texture} texture - The texture to copy.
  44586. * @param {number} x - The x coordinate of the copy origin.
  44587. * @param {number} y - The y coordinate of the copy origin.
  44588. * @param {number} width - The width of the copy.
  44589. * @param {number} height - The height of the copy.
  44590. * @param {number} faceIndex - The face index.
  44591. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44592. */
  44593. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44594. const { backend, gl } = this;
  44595. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  44596. const fb = gl.createFramebuffer();
  44597. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  44598. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  44599. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  44600. const typedArrayType = this._getTypedArrayType( glType );
  44601. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  44602. const elementCount = width * height;
  44603. const byteLength = elementCount * bytesPerTexel;
  44604. const buffer = gl.createBuffer();
  44605. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  44606. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  44607. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  44608. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  44609. await backend.utils._clientWaitAsync();
  44610. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  44611. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  44612. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  44613. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  44614. gl.deleteFramebuffer( fb );
  44615. return dstBuffer;
  44616. }
  44617. /**
  44618. * Returns the corresponding typed array type for the given WebGL data type.
  44619. *
  44620. * @private
  44621. * @param {GLenum} glType - The WebGL data type.
  44622. * @return {TypedArray.constructor} The typed array type.
  44623. */
  44624. _getTypedArrayType( glType ) {
  44625. const { gl } = this;
  44626. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  44627. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  44628. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  44629. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  44630. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  44631. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  44632. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  44633. if ( glType === gl.FLOAT ) return Float32Array;
  44634. throw new Error( `Unsupported WebGL type: ${glType}` );
  44635. }
  44636. /**
  44637. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  44638. *
  44639. * @private
  44640. * @param {GLenum} glType - The WebGL data type.
  44641. * @param {GLenum} glFormat - The WebGL texture format.
  44642. * @return {number} The bytes-per-texel.
  44643. */
  44644. _getBytesPerTexel( glType, glFormat ) {
  44645. const { gl } = this;
  44646. let bytesPerComponent = 0;
  44647. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  44648. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  44649. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  44650. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  44651. glType === gl.UNSIGNED_SHORT ||
  44652. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  44653. if ( glType === gl.UNSIGNED_INT ||
  44654. glType === gl.FLOAT ) bytesPerComponent = 4;
  44655. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  44656. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  44657. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  44658. }
  44659. }
  44660. function getImage( source ) {
  44661. if ( source.isDataTexture ) {
  44662. return source.image.data;
  44663. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  44664. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  44665. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  44666. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  44667. return source;
  44668. }
  44669. return source.data;
  44670. }
  44671. /**
  44672. * A WebGL 2 backend utility module for managing extensions.
  44673. *
  44674. * @private
  44675. */
  44676. class WebGLExtensions {
  44677. /**
  44678. * Constructs a new utility object.
  44679. *
  44680. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44681. */
  44682. constructor( backend ) {
  44683. /**
  44684. * A reference to the WebGL 2 backend.
  44685. *
  44686. * @type {WebGLBackend}
  44687. */
  44688. this.backend = backend;
  44689. /**
  44690. * A reference to the rendering context.
  44691. *
  44692. * @type {WebGL2RenderingContext}
  44693. */
  44694. this.gl = this.backend.gl;
  44695. /**
  44696. * A list with all the supported WebGL extensions.
  44697. *
  44698. * @type {Array<string>}
  44699. */
  44700. this.availableExtensions = this.gl.getSupportedExtensions();
  44701. /**
  44702. * A dictionary with requested WebGL extensions.
  44703. * The key is the name of the extension, the value
  44704. * the requested extension object.
  44705. *
  44706. * @type {Object<string,Object>}
  44707. */
  44708. this.extensions = {};
  44709. }
  44710. /**
  44711. * Returns the extension object for the given extension name.
  44712. *
  44713. * @param {string} name - The extension name.
  44714. * @return {Object} The extension object.
  44715. */
  44716. get( name ) {
  44717. let extension = this.extensions[ name ];
  44718. if ( extension === undefined ) {
  44719. extension = this.gl.getExtension( name );
  44720. this.extensions[ name ] = extension;
  44721. }
  44722. return extension;
  44723. }
  44724. /**
  44725. * Returns `true` if the requested extension is available.
  44726. *
  44727. * @param {string} name - The extension name.
  44728. * @return {boolean} Whether the given extension is available or not.
  44729. */
  44730. has( name ) {
  44731. return this.availableExtensions.includes( name );
  44732. }
  44733. }
  44734. /**
  44735. * A WebGL 2 backend utility module for managing the device's capabilities.
  44736. *
  44737. * @private
  44738. */
  44739. class WebGLCapabilities {
  44740. /**
  44741. * Constructs a new utility object.
  44742. *
  44743. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44744. */
  44745. constructor( backend ) {
  44746. /**
  44747. * A reference to the WebGL 2 backend.
  44748. *
  44749. * @type {WebGLBackend}
  44750. */
  44751. this.backend = backend;
  44752. /**
  44753. * This value holds the cached max anisotropy value.
  44754. *
  44755. * @type {?number}
  44756. * @default null
  44757. */
  44758. this.maxAnisotropy = null;
  44759. }
  44760. /**
  44761. * Returns the maximum anisotropy texture filtering value. This value
  44762. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  44763. * WebGL extension.
  44764. *
  44765. * @return {number} The maximum anisotropy texture filtering value.
  44766. */
  44767. getMaxAnisotropy() {
  44768. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  44769. const gl = this.backend.gl;
  44770. const extensions = this.backend.extensions;
  44771. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44772. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44773. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44774. } else {
  44775. this.maxAnisotropy = 0;
  44776. }
  44777. return this.maxAnisotropy;
  44778. }
  44779. }
  44780. const GLFeatureName = {
  44781. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  44782. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  44783. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  44784. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  44785. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  44786. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  44787. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  44788. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  44789. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  44790. 'OVR_multiview2': 'OVR_multiview2'
  44791. };
  44792. class WebGLBufferRenderer {
  44793. constructor( backend ) {
  44794. this.gl = backend.gl;
  44795. this.extensions = backend.extensions;
  44796. this.info = backend.renderer.info;
  44797. this.mode = null;
  44798. this.index = 0;
  44799. this.type = null;
  44800. this.object = null;
  44801. }
  44802. render( start, count ) {
  44803. const { gl, mode, object, type, info, index } = this;
  44804. if ( index !== 0 ) {
  44805. gl.drawElements( mode, count, type, start );
  44806. } else {
  44807. gl.drawArrays( mode, start, count );
  44808. }
  44809. info.update( object, count, 1 );
  44810. }
  44811. renderInstances( start, count, primcount ) {
  44812. const { gl, mode, type, index, object, info } = this;
  44813. if ( primcount === 0 ) return;
  44814. if ( index !== 0 ) {
  44815. gl.drawElementsInstanced( mode, count, type, start, primcount );
  44816. } else {
  44817. gl.drawArraysInstanced( mode, start, count, primcount );
  44818. }
  44819. info.update( object, count, primcount );
  44820. }
  44821. renderMultiDraw( starts, counts, drawCount ) {
  44822. const { extensions, mode, object, info } = this;
  44823. if ( drawCount === 0 ) return;
  44824. const extension = extensions.get( 'WEBGL_multi_draw' );
  44825. if ( extension === null ) {
  44826. for ( let i = 0; i < drawCount; i ++ ) {
  44827. this.render( starts[ i ], counts[ i ] );
  44828. }
  44829. } else {
  44830. if ( this.index !== 0 ) {
  44831. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  44832. } else {
  44833. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44834. }
  44835. let elementCount = 0;
  44836. for ( let i = 0; i < drawCount; i ++ ) {
  44837. elementCount += counts[ i ];
  44838. }
  44839. info.update( object, elementCount, 1 );
  44840. }
  44841. }
  44842. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44843. const { extensions, mode, object, info } = this;
  44844. if ( drawCount === 0 ) return;
  44845. const extension = extensions.get( 'WEBGL_multi_draw' );
  44846. if ( extension === null ) {
  44847. for ( let i = 0; i < drawCount; i ++ ) {
  44848. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44849. }
  44850. } else {
  44851. if ( this.index !== 0 ) {
  44852. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  44853. } else {
  44854. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44855. }
  44856. let elementCount = 0;
  44857. for ( let i = 0; i < drawCount; i ++ ) {
  44858. elementCount += counts[ i ] * primcount[ i ];
  44859. }
  44860. info.update( object, elementCount, 1 );
  44861. }
  44862. }
  44863. //
  44864. }
  44865. /**
  44866. * Abstract base class of a timestamp query pool.
  44867. *
  44868. * @abstract
  44869. */
  44870. class TimestampQueryPool {
  44871. /**
  44872. * Creates a new timestamp query pool.
  44873. *
  44874. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  44875. */
  44876. constructor( maxQueries = 256 ) {
  44877. /**
  44878. * Whether to track timestamps or not.
  44879. *
  44880. * @type {boolean}
  44881. * @default true
  44882. */
  44883. this.trackTimestamp = true;
  44884. /**
  44885. * Maximum number of queries this pool can hold.
  44886. *
  44887. * @type {number}
  44888. * @default 256
  44889. */
  44890. this.maxQueries = maxQueries;
  44891. /**
  44892. * How many queries allocated so far.
  44893. *
  44894. * @type {number}
  44895. * @default 0
  44896. */
  44897. this.currentQueryIndex = 0;
  44898. /**
  44899. * Tracks offsets for different contexts.
  44900. *
  44901. * @type {Map<string, number>}
  44902. */
  44903. this.queryOffsets = new Map();
  44904. /**
  44905. * Whether the pool has been disposed or not.
  44906. *
  44907. * @type {boolean}
  44908. * @default false
  44909. */
  44910. this.isDisposed = false;
  44911. /**
  44912. * TODO
  44913. *
  44914. * @type {number}
  44915. * @default 0
  44916. */
  44917. this.lastValue = 0;
  44918. /**
  44919. * TODO
  44920. *
  44921. * @type {boolean}
  44922. * @default false
  44923. */
  44924. this.pendingResolve = false;
  44925. }
  44926. /**
  44927. * Allocate queries for a specific renderContext.
  44928. *
  44929. * @abstract
  44930. * @param {Object} renderContext - The render context to allocate queries for.
  44931. * @returns {?number}
  44932. */
  44933. allocateQueriesForContext( /* renderContext */ ) {}
  44934. /**
  44935. * Resolve all timestamps and return data (or process them).
  44936. *
  44937. * @abstract
  44938. * @async
  44939. * @returns {Promise<number>|number} The resolved timestamp value.
  44940. */
  44941. async resolveQueriesAsync() {}
  44942. /**
  44943. * Dispose of the query pool.
  44944. *
  44945. * @abstract
  44946. */
  44947. dispose() {}
  44948. }
  44949. /**
  44950. * Manages a pool of WebGL timestamp queries for performance measurement.
  44951. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  44952. *
  44953. * @augments TimestampQueryPool
  44954. */
  44955. class WebGLTimestampQueryPool extends TimestampQueryPool {
  44956. /**
  44957. * Creates a new WebGL timestamp query pool.
  44958. *
  44959. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  44960. * @param {string} type - The type identifier for this query pool.
  44961. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  44962. */
  44963. constructor( gl, type, maxQueries = 2048 ) {
  44964. super( maxQueries );
  44965. this.gl = gl;
  44966. this.type = type;
  44967. // Check for timer query extensions
  44968. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  44969. gl.getExtension( 'EXT_disjoint_timer_query' );
  44970. if ( ! this.ext ) {
  44971. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  44972. this.trackTimestamp = false;
  44973. return;
  44974. }
  44975. // Create query objects
  44976. this.queries = [];
  44977. for ( let i = 0; i < this.maxQueries; i ++ ) {
  44978. this.queries.push( gl.createQuery() );
  44979. }
  44980. this.activeQuery = null;
  44981. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  44982. }
  44983. /**
  44984. * Allocates a pair of queries for a given render context.
  44985. *
  44986. * @param {Object} renderContext - The render context to allocate queries for.
  44987. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  44988. */
  44989. allocateQueriesForContext( renderContext ) {
  44990. if ( ! this.trackTimestamp ) return null;
  44991. // Check if we have enough space for a new query pair
  44992. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  44993. 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() } ).` );
  44994. return null;
  44995. }
  44996. const baseOffset = this.currentQueryIndex;
  44997. this.currentQueryIndex += 2;
  44998. // Initialize query states
  44999. this.queryStates.set( baseOffset, 'inactive' );
  45000. this.queryOffsets.set( renderContext.id, baseOffset );
  45001. return baseOffset;
  45002. }
  45003. /**
  45004. * Begins a timestamp query for the specified render context.
  45005. *
  45006. * @param {Object} renderContext - The render context to begin timing for.
  45007. */
  45008. beginQuery( renderContext ) {
  45009. if ( ! this.trackTimestamp || this.isDisposed ) {
  45010. return;
  45011. }
  45012. const baseOffset = this.queryOffsets.get( renderContext.id );
  45013. if ( baseOffset == null ) {
  45014. return;
  45015. }
  45016. // Don't start a new query if there's an active one
  45017. if ( this.activeQuery !== null ) {
  45018. return;
  45019. }
  45020. const query = this.queries[ baseOffset ];
  45021. if ( ! query ) {
  45022. return;
  45023. }
  45024. try {
  45025. // Only begin if query is inactive
  45026. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  45027. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  45028. this.activeQuery = baseOffset;
  45029. this.queryStates.set( baseOffset, 'started' );
  45030. }
  45031. } catch ( error ) {
  45032. console.error( 'Error in beginQuery:', error );
  45033. this.activeQuery = null;
  45034. this.queryStates.set( baseOffset, 'inactive' );
  45035. }
  45036. }
  45037. /**
  45038. * Ends the active timestamp query for the specified render context.
  45039. *
  45040. * @param {Object} renderContext - The render context to end timing for.
  45041. * @param {string} renderContext.id - Unique identifier for the render context.
  45042. */
  45043. endQuery( renderContext ) {
  45044. if ( ! this.trackTimestamp || this.isDisposed ) {
  45045. return;
  45046. }
  45047. const baseOffset = this.queryOffsets.get( renderContext.id );
  45048. if ( baseOffset == null ) {
  45049. return;
  45050. }
  45051. // Only end if this is the active query
  45052. if ( this.activeQuery !== baseOffset ) {
  45053. return;
  45054. }
  45055. try {
  45056. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  45057. this.queryStates.set( baseOffset, 'ended' );
  45058. this.activeQuery = null;
  45059. } catch ( error ) {
  45060. console.error( 'Error in endQuery:', error );
  45061. // Reset state on error
  45062. this.queryStates.set( baseOffset, 'inactive' );
  45063. this.activeQuery = null;
  45064. }
  45065. }
  45066. /**
  45067. * Asynchronously resolves all completed queries and returns the total duration.
  45068. *
  45069. * @async
  45070. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  45071. */
  45072. async resolveQueriesAsync() {
  45073. if ( ! this.trackTimestamp || this.pendingResolve ) {
  45074. return this.lastValue;
  45075. }
  45076. this.pendingResolve = true;
  45077. try {
  45078. // Wait for all ended queries to complete
  45079. const resolvePromises = [];
  45080. for ( const [ baseOffset, state ] of this.queryStates ) {
  45081. if ( state === 'ended' ) {
  45082. const query = this.queries[ baseOffset ];
  45083. resolvePromises.push( this.resolveQuery( query ) );
  45084. }
  45085. }
  45086. if ( resolvePromises.length === 0 ) {
  45087. return this.lastValue;
  45088. }
  45089. const results = await Promise.all( resolvePromises );
  45090. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  45091. // Store the last valid result
  45092. this.lastValue = totalDuration;
  45093. // Reset states
  45094. this.currentQueryIndex = 0;
  45095. this.queryOffsets.clear();
  45096. this.queryStates.clear();
  45097. this.activeQuery = null;
  45098. return totalDuration;
  45099. } catch ( error ) {
  45100. console.error( 'Error resolving queries:', error );
  45101. return this.lastValue;
  45102. } finally {
  45103. this.pendingResolve = false;
  45104. }
  45105. }
  45106. /**
  45107. * Resolves a single query, checking for completion and disjoint operation.
  45108. *
  45109. * @async
  45110. * @param {WebGLQuery} query - The query object to resolve.
  45111. * @returns {Promise<number>} The elapsed time in milliseconds.
  45112. */
  45113. async resolveQuery( query ) {
  45114. return new Promise( ( resolve ) => {
  45115. if ( this.isDisposed ) {
  45116. resolve( this.lastValue );
  45117. return;
  45118. }
  45119. let timeoutId;
  45120. let isResolved = false;
  45121. const cleanup = () => {
  45122. if ( timeoutId ) {
  45123. clearTimeout( timeoutId );
  45124. timeoutId = null;
  45125. }
  45126. };
  45127. const finalizeResolution = ( value ) => {
  45128. if ( ! isResolved ) {
  45129. isResolved = true;
  45130. cleanup();
  45131. resolve( value );
  45132. }
  45133. };
  45134. const checkQuery = () => {
  45135. if ( this.isDisposed ) {
  45136. finalizeResolution( this.lastValue );
  45137. return;
  45138. }
  45139. try {
  45140. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  45141. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  45142. if ( disjoint ) {
  45143. finalizeResolution( this.lastValue );
  45144. return;
  45145. }
  45146. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  45147. if ( ! available ) {
  45148. timeoutId = setTimeout( checkQuery, 1 );
  45149. return;
  45150. }
  45151. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  45152. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  45153. } catch ( error ) {
  45154. console.error( 'Error checking query:', error );
  45155. resolve( this.lastValue );
  45156. }
  45157. };
  45158. checkQuery();
  45159. } );
  45160. }
  45161. /**
  45162. * Releases all resources held by this query pool.
  45163. * This includes deleting all query objects and clearing internal state.
  45164. */
  45165. dispose() {
  45166. if ( this.isDisposed ) {
  45167. return;
  45168. }
  45169. this.isDisposed = true;
  45170. if ( ! this.trackTimestamp ) return;
  45171. for ( const query of this.queries ) {
  45172. this.gl.deleteQuery( query );
  45173. }
  45174. this.queries = [];
  45175. this.queryStates.clear();
  45176. this.queryOffsets.clear();
  45177. this.lastValue = 0;
  45178. this.activeQuery = null;
  45179. }
  45180. }
  45181. /**
  45182. * A backend implementation targeting WebGL 2.
  45183. *
  45184. * @private
  45185. * @augments Backend
  45186. */
  45187. class WebGLBackend extends Backend {
  45188. /**
  45189. * WebGLBackend options.
  45190. *
  45191. * @typedef {Object} WebGLBackend~Options
  45192. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  45193. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  45194. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  45195. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  45196. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  45197. * @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.
  45198. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  45199. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  45200. */
  45201. /**
  45202. * Constructs a new WebGPU backend.
  45203. *
  45204. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  45205. */
  45206. constructor( parameters = {} ) {
  45207. super( parameters );
  45208. /**
  45209. * This flag can be used for type testing.
  45210. *
  45211. * @type {boolean}
  45212. * @readonly
  45213. * @default true
  45214. */
  45215. this.isWebGLBackend = true;
  45216. /**
  45217. * A reference to a backend module holding shader attribute-related
  45218. * utility functions.
  45219. *
  45220. * @type {?WebGLAttributeUtils}
  45221. * @default null
  45222. */
  45223. this.attributeUtils = null;
  45224. /**
  45225. * A reference to a backend module holding extension-related
  45226. * utility functions.
  45227. *
  45228. * @type {?WebGLExtensions}
  45229. * @default null
  45230. */
  45231. this.extensions = null;
  45232. /**
  45233. * A reference to a backend module holding capability-related
  45234. * utility functions.
  45235. *
  45236. * @type {?WebGLCapabilities}
  45237. * @default null
  45238. */
  45239. this.capabilities = null;
  45240. /**
  45241. * A reference to a backend module holding texture-related
  45242. * utility functions.
  45243. *
  45244. * @type {?WebGLTextureUtils}
  45245. * @default null
  45246. */
  45247. this.textureUtils = null;
  45248. /**
  45249. * A reference to a backend module holding renderer-related
  45250. * utility functions.
  45251. *
  45252. * @type {?WebGLBufferRenderer}
  45253. * @default null
  45254. */
  45255. this.bufferRenderer = null;
  45256. /**
  45257. * A reference to the rendering context.
  45258. *
  45259. * @type {?WebGL2RenderingContext}
  45260. * @default null
  45261. */
  45262. this.gl = null;
  45263. /**
  45264. * A reference to a backend module holding state-related
  45265. * utility functions.
  45266. *
  45267. * @type {?WebGLState}
  45268. * @default null
  45269. */
  45270. this.state = null;
  45271. /**
  45272. * A reference to a backend module holding common
  45273. * utility functions.
  45274. *
  45275. * @type {?WebGLUtils}
  45276. * @default null
  45277. */
  45278. this.utils = null;
  45279. /**
  45280. * Dictionary for caching VAOs.
  45281. *
  45282. * @type {Object<string,WebGLVertexArrayObject>}
  45283. */
  45284. this.vaoCache = {};
  45285. /**
  45286. * Dictionary for caching transform feedback objects.
  45287. *
  45288. * @type {Object<string,WebGLTransformFeedback>}
  45289. */
  45290. this.transformFeedbackCache = {};
  45291. /**
  45292. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  45293. * Only relevant when using compute shaders.
  45294. *
  45295. * @type {boolean}
  45296. * @default false
  45297. */
  45298. this.discard = false;
  45299. /**
  45300. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  45301. * device does not support the extension.
  45302. *
  45303. * @type {?EXTDisjointTimerQueryWebGL2}
  45304. * @default null
  45305. */
  45306. this.disjoint = null;
  45307. /**
  45308. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  45309. * device does not support the extension.
  45310. *
  45311. * @type {?KHRParallelShaderCompile}
  45312. * @default null
  45313. */
  45314. this.parallel = null;
  45315. /**
  45316. * A reference to the current render context.
  45317. *
  45318. * @private
  45319. * @type {RenderContext}
  45320. * @default null
  45321. */
  45322. this._currentContext = null;
  45323. /**
  45324. * A unique collection of bindings.
  45325. *
  45326. * @private
  45327. * @type {WeakSet<Array<BindGroup>>}
  45328. */
  45329. this._knownBindings = new WeakSet();
  45330. /**
  45331. * Whether the device supports framebuffers invalidation or not.
  45332. *
  45333. * @private
  45334. * @type {boolean}
  45335. */
  45336. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  45337. /**
  45338. * The target framebuffer when rendering with
  45339. * the WebXR device API.
  45340. *
  45341. * @private
  45342. * @type {WebGLFramebuffer}
  45343. * @default null
  45344. */
  45345. this._xrFramebuffer = null;
  45346. }
  45347. /**
  45348. * Initializes the backend so it is ready for usage.
  45349. *
  45350. * @param {Renderer} renderer - The renderer.
  45351. */
  45352. init( renderer ) {
  45353. super.init( renderer );
  45354. //
  45355. const parameters = this.parameters;
  45356. const contextAttributes = {
  45357. antialias: renderer.samples > 0,
  45358. alpha: true, // always true for performance reasons
  45359. depth: renderer.depth,
  45360. stencil: renderer.stencil
  45361. };
  45362. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  45363. function onContextLost( event ) {
  45364. event.preventDefault();
  45365. const contextLossInfo = {
  45366. api: 'WebGL',
  45367. message: event.statusMessage || 'Unknown reason',
  45368. reason: null,
  45369. originalEvent: event
  45370. };
  45371. renderer.onDeviceLost( contextLossInfo );
  45372. }
  45373. this._onContextLost = onContextLost;
  45374. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  45375. this.gl = glContext;
  45376. this.extensions = new WebGLExtensions( this );
  45377. this.capabilities = new WebGLCapabilities( this );
  45378. this.attributeUtils = new WebGLAttributeUtils( this );
  45379. this.textureUtils = new WebGLTextureUtils( this );
  45380. this.bufferRenderer = new WebGLBufferRenderer( this );
  45381. this.state = new WebGLState( this );
  45382. this.utils = new WebGLUtils( this );
  45383. this.extensions.get( 'EXT_color_buffer_float' );
  45384. this.extensions.get( 'WEBGL_clip_cull_distance' );
  45385. this.extensions.get( 'OES_texture_float_linear' );
  45386. this.extensions.get( 'EXT_color_buffer_half_float' );
  45387. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  45388. this.extensions.get( 'WEBGL_render_shared_exponent' );
  45389. this.extensions.get( 'WEBGL_multi_draw' );
  45390. this.extensions.get( 'OVR_multiview2' );
  45391. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  45392. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  45393. }
  45394. /**
  45395. * The coordinate system of the backend.
  45396. *
  45397. * @type {number}
  45398. * @readonly
  45399. */
  45400. get coordinateSystem() {
  45401. return WebGLCoordinateSystem;
  45402. }
  45403. /**
  45404. * This method performs a readback operation by moving buffer data from
  45405. * a storage buffer attribute from the GPU to the CPU.
  45406. *
  45407. * @async
  45408. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45409. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45410. */
  45411. async getArrayBufferAsync( attribute ) {
  45412. return await this.attributeUtils.getArrayBufferAsync( attribute );
  45413. }
  45414. /**
  45415. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  45416. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  45417. *
  45418. * @async
  45419. * @return {Promise} A Promise that resolves when synchronization has been finished.
  45420. */
  45421. async waitForGPU() {
  45422. await this.utils._clientWaitAsync();
  45423. }
  45424. /**
  45425. * Ensures the backend is XR compatible.
  45426. *
  45427. * @async
  45428. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  45429. */
  45430. async makeXRCompatible() {
  45431. const attributes = this.gl.getContextAttributes();
  45432. if ( attributes.xrCompatible !== true ) {
  45433. await this.gl.makeXRCompatible();
  45434. }
  45435. }
  45436. /**
  45437. * Sets the XR rendering destination.
  45438. *
  45439. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  45440. */
  45441. setXRTarget( xrFramebuffer ) {
  45442. this._xrFramebuffer = xrFramebuffer;
  45443. }
  45444. /**
  45445. * Configures the given XR render target with external textures.
  45446. *
  45447. * This method is only relevant when using the WebXR Layers API.
  45448. *
  45449. * @param {XRRenderTarget} renderTarget - The XR render target.
  45450. * @param {WebGLTexture} colorTexture - A native color texture.
  45451. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  45452. */
  45453. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  45454. const gl = this.gl;
  45455. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  45456. if ( depthTexture !== null ) {
  45457. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  45458. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  45459. // The multisample_render_to_texture extension doesn't work properly if there
  45460. // are midframe flushes and an external depth texture.
  45461. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  45462. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  45463. }
  45464. renderTarget._autoAllocateDepthBuffer = false;
  45465. }
  45466. }
  45467. /**
  45468. * Inits a time stamp query for the given render context.
  45469. *
  45470. * @param {RenderContext} renderContext - The render context.
  45471. */
  45472. initTimestampQuery( renderContext ) {
  45473. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  45474. const type = renderContext.isComputeNode ? 'compute' : 'render';
  45475. if ( ! this.timestampQueryPool[ type ] ) {
  45476. // TODO: Variable maxQueries?
  45477. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  45478. }
  45479. const timestampQueryPool = this.timestampQueryPool[ type ];
  45480. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  45481. if ( baseOffset !== null ) {
  45482. timestampQueryPool.beginQuery( renderContext );
  45483. }
  45484. }
  45485. // timestamp utils
  45486. /**
  45487. * Prepares the timestamp buffer.
  45488. *
  45489. * @param {RenderContext} renderContext - The render context.
  45490. */
  45491. prepareTimestampBuffer( renderContext ) {
  45492. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  45493. const type = renderContext.isComputeNode ? 'compute' : 'render';
  45494. const timestampQueryPool = this.timestampQueryPool[ type ];
  45495. timestampQueryPool.endQuery( renderContext );
  45496. }
  45497. /**
  45498. * Returns the backend's rendering context.
  45499. *
  45500. * @return {WebGL2RenderingContext} The rendering context.
  45501. */
  45502. getContext() {
  45503. return this.gl;
  45504. }
  45505. /**
  45506. * This method is executed at the beginning of a render call and prepares
  45507. * the WebGL state for upcoming render calls
  45508. *
  45509. * @param {RenderContext} renderContext - The render context.
  45510. */
  45511. beginRender( renderContext ) {
  45512. const { state } = this;
  45513. const renderContextData = this.get( renderContext );
  45514. //
  45515. if ( renderContext.viewport ) {
  45516. this.updateViewport( renderContext );
  45517. } else {
  45518. const { width, height } = this.getDrawingBufferSize();
  45519. state.viewport( 0, 0, width, height );
  45520. }
  45521. if ( renderContext.scissor ) {
  45522. const { x, y, width, height } = renderContext.scissorValue;
  45523. state.scissor( x, renderContext.height - height - y, width, height );
  45524. }
  45525. //
  45526. this.initTimestampQuery( renderContext );
  45527. renderContextData.previousContext = this._currentContext;
  45528. this._currentContext = renderContext;
  45529. this._setFramebuffer( renderContext );
  45530. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  45531. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45532. if ( occlusionQueryCount > 0 ) {
  45533. // Get a reference to the array of objects with queries. The renderContextData property
  45534. // can be changed by another render pass before the async reading of all previous queries complete
  45535. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  45536. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  45537. renderContextData.lastOcclusionObject = null;
  45538. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  45539. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  45540. renderContextData.occlusionQueryIndex = 0;
  45541. }
  45542. }
  45543. /**
  45544. * This method is executed at the end of a render call and finalizes work
  45545. * after draw calls.
  45546. *
  45547. * @param {RenderContext} renderContext - The render context.
  45548. */
  45549. finishRender( renderContext ) {
  45550. const { gl, state } = this;
  45551. const renderContextData = this.get( renderContext );
  45552. const previousContext = renderContextData.previousContext;
  45553. state.resetVertexState();
  45554. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45555. if ( occlusionQueryCount > 0 ) {
  45556. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  45557. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  45558. }
  45559. this.resolveOccludedAsync( renderContext );
  45560. }
  45561. const textures = renderContext.textures;
  45562. if ( textures !== null ) {
  45563. for ( let i = 0; i < textures.length; i ++ ) {
  45564. const texture = textures[ i ];
  45565. if ( texture.generateMipmaps ) {
  45566. this.generateMipmaps( texture );
  45567. }
  45568. }
  45569. }
  45570. this._currentContext = previousContext;
  45571. const renderTarget = renderContext.renderTarget;
  45572. if ( renderContext.textures !== null && renderTarget ) {
  45573. const renderTargetContextData = this.get( renderTarget );
  45574. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  45575. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  45576. let mask = gl.COLOR_BUFFER_BIT;
  45577. if ( renderTarget.resolveDepthBuffer ) {
  45578. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  45579. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  45580. }
  45581. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  45582. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  45583. const textures = renderContext.textures;
  45584. const isMRT = textures.length > 1;
  45585. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  45586. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  45587. if ( isMRT ) {
  45588. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  45589. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  45590. for ( let i = 0; i < textures.length; i ++ ) {
  45591. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  45592. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  45593. }
  45594. }
  45595. for ( let i = 0; i < textures.length; i ++ ) {
  45596. if ( isMRT ) {
  45597. // configure attachment for resolve
  45598. const { textureGPU } = this.get( textures[ i ] );
  45599. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45600. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  45601. }
  45602. if ( renderContext.scissor ) {
  45603. const { x, y, width, height } = renderContext.scissorValue;
  45604. const viewY = renderContext.height - height - y;
  45605. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  45606. } else {
  45607. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  45608. }
  45609. }
  45610. if ( isMRT ) {
  45611. // restore attachments
  45612. for ( let i = 0; i < textures.length; i ++ ) {
  45613. const { textureGPU } = this.get( textures[ i ] );
  45614. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45615. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  45616. }
  45617. }
  45618. if ( this._supportsInvalidateFramebuffer === true ) {
  45619. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  45620. }
  45621. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  45622. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  45623. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  45624. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  45625. }
  45626. }
  45627. if ( previousContext !== null ) {
  45628. this._setFramebuffer( previousContext );
  45629. if ( previousContext.viewport ) {
  45630. this.updateViewport( previousContext );
  45631. } else {
  45632. const { width, height } = this.getDrawingBufferSize();
  45633. state.viewport( 0, 0, width, height );
  45634. }
  45635. }
  45636. this.prepareTimestampBuffer( renderContext );
  45637. }
  45638. /**
  45639. * This method processes the result of occlusion queries and writes it
  45640. * into render context data.
  45641. *
  45642. * @async
  45643. * @param {RenderContext} renderContext - The render context.
  45644. */
  45645. resolveOccludedAsync( renderContext ) {
  45646. const renderContextData = this.get( renderContext );
  45647. // handle occlusion query results
  45648. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  45649. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  45650. const occluded = new WeakSet();
  45651. const { gl } = this;
  45652. renderContextData.currentOcclusionQueryObjects = null;
  45653. renderContextData.currentOcclusionQueries = null;
  45654. const check = () => {
  45655. let completed = 0;
  45656. // check all queries and requeue as appropriate
  45657. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  45658. const query = currentOcclusionQueries[ i ];
  45659. if ( query === null ) continue;
  45660. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  45661. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  45662. currentOcclusionQueries[ i ] = null;
  45663. gl.deleteQuery( query );
  45664. completed ++;
  45665. }
  45666. }
  45667. if ( completed < currentOcclusionQueries.length ) {
  45668. requestAnimationFrame( check );
  45669. } else {
  45670. renderContextData.occluded = occluded;
  45671. }
  45672. };
  45673. check();
  45674. }
  45675. }
  45676. /**
  45677. * Returns `true` if the given 3D object is fully occluded by other
  45678. * 3D objects in the scene.
  45679. *
  45680. * @param {RenderContext} renderContext - The render context.
  45681. * @param {Object3D} object - The 3D object to test.
  45682. * @return {boolean} Whether the 3D object is fully occluded or not.
  45683. */
  45684. isOccluded( renderContext, object ) {
  45685. const renderContextData = this.get( renderContext );
  45686. return renderContextData.occluded && renderContextData.occluded.has( object );
  45687. }
  45688. /**
  45689. * Updates the viewport with the values from the given render context.
  45690. *
  45691. * @param {RenderContext} renderContext - The render context.
  45692. */
  45693. updateViewport( renderContext ) {
  45694. const { state } = this;
  45695. const { x, y, width, height } = renderContext.viewportValue;
  45696. state.viewport( x, renderContext.height - height - y, width, height );
  45697. }
  45698. /**
  45699. * Defines the scissor test.
  45700. *
  45701. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45702. */
  45703. setScissorTest( boolean ) {
  45704. const state = this.state;
  45705. state.setScissorTest( boolean );
  45706. }
  45707. /**
  45708. * Returns the clear color and alpha into a single
  45709. * color object.
  45710. *
  45711. * @return {Color4} The clear color.
  45712. */
  45713. getClearColor() {
  45714. const clearColor = super.getClearColor();
  45715. // Since the canvas is always created with alpha: true,
  45716. // WebGL must always premultiply the clear color.
  45717. clearColor.r *= clearColor.a;
  45718. clearColor.g *= clearColor.a;
  45719. clearColor.b *= clearColor.a;
  45720. return clearColor;
  45721. }
  45722. /**
  45723. * Performs a clear operation.
  45724. *
  45725. * @param {boolean} color - Whether the color buffer should be cleared or not.
  45726. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  45727. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  45728. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  45729. * @param {boolean} [setFrameBuffer=true] - TODO.
  45730. */
  45731. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  45732. const { gl, renderer } = this;
  45733. if ( descriptor === null ) {
  45734. const clearColor = this.getClearColor();
  45735. descriptor = {
  45736. textures: null,
  45737. clearColorValue: clearColor
  45738. };
  45739. }
  45740. //
  45741. let clear = 0;
  45742. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  45743. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  45744. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  45745. if ( clear !== 0 ) {
  45746. let clearColor;
  45747. if ( descriptor.clearColorValue ) {
  45748. clearColor = descriptor.clearColorValue;
  45749. } else {
  45750. clearColor = this.getClearColor();
  45751. }
  45752. const clearDepth = renderer.getClearDepth();
  45753. const clearStencil = renderer.getClearStencil();
  45754. if ( depth ) this.state.setDepthMask( true );
  45755. if ( descriptor.textures === null ) {
  45756. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  45757. gl.clear( clear );
  45758. } else {
  45759. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  45760. if ( color ) {
  45761. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  45762. if ( i === 0 ) {
  45763. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  45764. } else {
  45765. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  45766. }
  45767. }
  45768. }
  45769. if ( depth && stencil ) {
  45770. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  45771. } else if ( depth ) {
  45772. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  45773. } else if ( stencil ) {
  45774. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  45775. }
  45776. }
  45777. }
  45778. }
  45779. /**
  45780. * This method is executed at the beginning of a compute call and
  45781. * prepares the state for upcoming compute tasks.
  45782. *
  45783. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45784. */
  45785. beginCompute( computeGroup ) {
  45786. const { state, gl } = this;
  45787. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  45788. this.initTimestampQuery( computeGroup );
  45789. }
  45790. /**
  45791. * Executes a compute command for the given compute node.
  45792. *
  45793. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45794. * @param {Node} computeNode - The compute node.
  45795. * @param {Array<BindGroup>} bindings - The bindings.
  45796. * @param {ComputePipeline} pipeline - The compute pipeline.
  45797. * @param {number|null} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  45798. */
  45799. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  45800. const { state, gl } = this;
  45801. if ( this.discard === false ) {
  45802. // required here to handle async behaviour of render.compute()
  45803. gl.enable( gl.RASTERIZER_DISCARD );
  45804. this.discard = true;
  45805. }
  45806. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  45807. const vaoKey = this._getVaoKey( attributes );
  45808. const vaoGPU = this.vaoCache[ vaoKey ];
  45809. if ( vaoGPU === undefined ) {
  45810. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  45811. } else {
  45812. state.setVertexState( vaoGPU );
  45813. }
  45814. state.useProgram( programGPU );
  45815. this._bindUniforms( bindings );
  45816. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  45817. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  45818. gl.beginTransformFeedback( gl.POINTS );
  45819. count = ( count !== null ) ? count : computeNode.count;
  45820. if ( Array.isArray( count ) ) {
  45821. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  45822. count = count[ 0 ];
  45823. }
  45824. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  45825. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  45826. } else {
  45827. gl.drawArrays( gl.POINTS, 0, count );
  45828. }
  45829. gl.endTransformFeedback();
  45830. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  45831. // switch active buffers
  45832. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45833. const dualAttributeData = transformBuffers[ i ];
  45834. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  45835. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  45836. }
  45837. dualAttributeData.switchBuffers();
  45838. }
  45839. }
  45840. /**
  45841. * This method is executed at the end of a compute call and
  45842. * finalizes work after compute tasks.
  45843. *
  45844. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45845. */
  45846. finishCompute( computeGroup ) {
  45847. const gl = this.gl;
  45848. this.discard = false;
  45849. gl.disable( gl.RASTERIZER_DISCARD );
  45850. this.prepareTimestampBuffer( computeGroup );
  45851. if ( this._currentContext ) {
  45852. this._setFramebuffer( this._currentContext );
  45853. }
  45854. }
  45855. /**
  45856. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  45857. *
  45858. * @param {RenderContext} renderContext - The render context.
  45859. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  45860. *
  45861. * @private
  45862. */
  45863. _isRenderCameraDepthArray( renderContext ) {
  45864. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  45865. }
  45866. /**
  45867. * Executes a draw command for the given render object.
  45868. *
  45869. * @param {RenderObject} renderObject - The render object to draw.
  45870. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45871. */
  45872. draw( renderObject/*, info*/ ) {
  45873. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  45874. const { programGPU } = this.get( pipeline );
  45875. const { gl, state } = this;
  45876. const contextData = this.get( context );
  45877. const drawParams = renderObject.getDrawParameters();
  45878. if ( drawParams === null ) return;
  45879. //
  45880. this._bindUniforms( renderObject.getBindings() );
  45881. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  45882. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  45883. state.useProgram( programGPU );
  45884. // vertex state
  45885. const attributes = renderObject.getAttributes();
  45886. const attributesData = this.get( attributes );
  45887. let vaoGPU = attributesData.vaoGPU;
  45888. if ( vaoGPU === undefined ) {
  45889. const vaoKey = this._getVaoKey( attributes );
  45890. vaoGPU = this.vaoCache[ vaoKey ];
  45891. if ( vaoGPU === undefined ) {
  45892. vaoGPU = this._createVao( attributes );
  45893. this.vaoCache[ vaoKey ] = vaoGPU;
  45894. attributesData.vaoGPU = vaoGPU;
  45895. }
  45896. }
  45897. const index = renderObject.getIndex();
  45898. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  45899. state.setVertexState( vaoGPU, indexGPU );
  45900. //
  45901. const lastObject = contextData.lastOcclusionObject;
  45902. if ( lastObject !== object && lastObject !== undefined ) {
  45903. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45904. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  45905. contextData.occlusionQueryIndex ++;
  45906. }
  45907. if ( object.occlusionTest === true ) {
  45908. const query = gl.createQuery();
  45909. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  45910. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  45911. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  45912. }
  45913. contextData.lastOcclusionObject = object;
  45914. }
  45915. //
  45916. const renderer = this.bufferRenderer;
  45917. if ( object.isPoints ) renderer.mode = gl.POINTS;
  45918. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  45919. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  45920. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  45921. else {
  45922. if ( material.wireframe === true ) {
  45923. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  45924. renderer.mode = gl.LINES;
  45925. } else {
  45926. renderer.mode = gl.TRIANGLES;
  45927. }
  45928. }
  45929. //
  45930. const { vertexCount, instanceCount } = drawParams;
  45931. let { firstVertex } = drawParams;
  45932. renderer.object = object;
  45933. if ( index !== null ) {
  45934. firstVertex *= index.array.BYTES_PER_ELEMENT;
  45935. const indexData = this.get( index );
  45936. renderer.index = index.count;
  45937. renderer.type = indexData.type;
  45938. } else {
  45939. renderer.index = 0;
  45940. }
  45941. const draw = () => {
  45942. if ( object.isBatchedMesh ) {
  45943. if ( object._multiDrawInstances !== null ) {
  45944. // @deprecated, r174
  45945. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  45946. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  45947. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  45948. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  45949. } else {
  45950. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  45951. }
  45952. } else if ( instanceCount > 1 ) {
  45953. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  45954. } else {
  45955. renderer.render( firstVertex, vertexCount );
  45956. }
  45957. };
  45958. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  45959. const cameraData = this.get( renderObject.camera );
  45960. const cameras = renderObject.camera.cameras;
  45961. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  45962. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  45963. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  45964. const indexesGPU = [];
  45965. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45966. const bufferGPU = gl.createBuffer();
  45967. data[ 0 ] = i;
  45968. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45969. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  45970. indexesGPU.push( bufferGPU );
  45971. }
  45972. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  45973. }
  45974. const cameraIndexData = this.get( cameraIndex );
  45975. const pixelRatio = this.renderer.getPixelRatio();
  45976. const renderTarget = this._currentContext.renderTarget;
  45977. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  45978. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  45979. if ( isRenderCameraDepthArray ) {
  45980. // Clear the depth texture
  45981. const textureData = this.get( renderTarget.depthTexture );
  45982. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  45983. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  45984. const { stencilBuffer } = renderTarget;
  45985. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45986. this.renderer._activeCubeFace = i;
  45987. this._currentContext.activeCubeFace = i;
  45988. this._setFramebuffer( this._currentContext );
  45989. this.clear( false, true, stencilBuffer, this._currentContext, false );
  45990. }
  45991. this.renderer._activeCubeFace = prevActiveCubeFace;
  45992. this._currentContext.activeCubeFace = prevActiveCubeFace;
  45993. }
  45994. }
  45995. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45996. const subCamera = cameras[ i ];
  45997. if ( object.layers.test( subCamera.layers ) ) {
  45998. if ( isRenderCameraDepthArray ) {
  45999. // Update the active layer
  46000. this.renderer._activeCubeFace = i;
  46001. this._currentContext.activeCubeFace = i;
  46002. this._setFramebuffer( this._currentContext );
  46003. }
  46004. const vp = subCamera.viewport;
  46005. if ( vp !== undefined ) {
  46006. const x = vp.x * pixelRatio;
  46007. const y = vp.y * pixelRatio;
  46008. const width = vp.width * pixelRatio;
  46009. const height = vp.height * pixelRatio;
  46010. state.viewport(
  46011. Math.floor( x ),
  46012. Math.floor( renderObject.context.height - height - y ),
  46013. Math.floor( width ),
  46014. Math.floor( height )
  46015. );
  46016. }
  46017. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  46018. draw();
  46019. }
  46020. this._currentContext.activeCubeFace = prevActiveCubeFace;
  46021. this.renderer._activeCubeFace = prevActiveCubeFace;
  46022. }
  46023. } else {
  46024. draw();
  46025. }
  46026. }
  46027. /**
  46028. * Explain why always null is returned.
  46029. *
  46030. * @param {RenderObject} renderObject - The render object.
  46031. * @return {boolean} Whether the render pipeline requires an update or not.
  46032. */
  46033. needsRenderUpdate( /*renderObject*/ ) {
  46034. return false;
  46035. }
  46036. /**
  46037. * Explain why no cache key is computed.
  46038. *
  46039. * @param {RenderObject} renderObject - The render object.
  46040. * @return {string} The cache key.
  46041. */
  46042. getRenderCacheKey( /*renderObject*/ ) {
  46043. return '';
  46044. }
  46045. // textures
  46046. /**
  46047. * Creates a default texture for the given texture that can be used
  46048. * as a placeholder until the actual texture is ready for usage.
  46049. *
  46050. * @param {Texture} texture - The texture to create a default texture for.
  46051. */
  46052. createDefaultTexture( texture ) {
  46053. this.textureUtils.createDefaultTexture( texture );
  46054. }
  46055. /**
  46056. * Defines a texture on the GPU for the given texture object.
  46057. *
  46058. * @param {Texture} texture - The texture.
  46059. * @param {Object} [options={}] - Optional configuration parameter.
  46060. */
  46061. createTexture( texture, options ) {
  46062. this.textureUtils.createTexture( texture, options );
  46063. }
  46064. /**
  46065. * Uploads the updated texture data to the GPU.
  46066. *
  46067. * @param {Texture} texture - The texture.
  46068. * @param {Object} [options={}] - Optional configuration parameter.
  46069. */
  46070. updateTexture( texture, options ) {
  46071. this.textureUtils.updateTexture( texture, options );
  46072. }
  46073. /**
  46074. * Generates mipmaps for the given texture.
  46075. *
  46076. * @param {Texture} texture - The texture.
  46077. */
  46078. generateMipmaps( texture ) {
  46079. this.textureUtils.generateMipmaps( texture );
  46080. }
  46081. /**
  46082. * Destroys the GPU data for the given texture object.
  46083. *
  46084. * @param {Texture} texture - The texture.
  46085. */
  46086. destroyTexture( texture ) {
  46087. this.textureUtils.destroyTexture( texture );
  46088. }
  46089. /**
  46090. * Returns texture data as a typed array.
  46091. *
  46092. * @async
  46093. * @param {Texture} texture - The texture to copy.
  46094. * @param {number} x - The x coordinate of the copy origin.
  46095. * @param {number} y - The y coordinate of the copy origin.
  46096. * @param {number} width - The width of the copy.
  46097. * @param {number} height - The height of the copy.
  46098. * @param {number} faceIndex - The face index.
  46099. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46100. */
  46101. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46102. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  46103. }
  46104. /**
  46105. * This method does nothing since WebGL 2 has no concept of samplers.
  46106. *
  46107. * @param {Texture} texture - The texture to create the sampler for.
  46108. */
  46109. createSampler( /*texture*/ ) {
  46110. //console.warn( 'Abstract class.' );
  46111. }
  46112. /**
  46113. * This method does nothing since WebGL 2 has no concept of samplers.
  46114. *
  46115. * @param {Texture} texture - The texture to destroy the sampler for.
  46116. */
  46117. destroySampler( /*texture*/ ) {}
  46118. // node builder
  46119. /**
  46120. * Returns a node builder for the given render object.
  46121. *
  46122. * @param {RenderObject} object - The render object.
  46123. * @param {Renderer} renderer - The renderer.
  46124. * @return {GLSLNodeBuilder} The node builder.
  46125. */
  46126. createNodeBuilder( object, renderer ) {
  46127. return new GLSLNodeBuilder( object, renderer );
  46128. }
  46129. // program
  46130. /**
  46131. * Creates a shader program from the given programmable stage.
  46132. *
  46133. * @param {ProgrammableStage} program - The programmable stage.
  46134. */
  46135. createProgram( program ) {
  46136. const gl = this.gl;
  46137. const { stage, code } = program;
  46138. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  46139. gl.shaderSource( shader, code );
  46140. gl.compileShader( shader );
  46141. this.set( program, {
  46142. shaderGPU: shader
  46143. } );
  46144. }
  46145. /**
  46146. * Destroys the shader program of the given programmable stage.
  46147. *
  46148. * @param {ProgrammableStage} program - The programmable stage.
  46149. */
  46150. destroyProgram( program ) {
  46151. this.delete( program );
  46152. }
  46153. /**
  46154. * Creates a render pipeline for the given render object.
  46155. *
  46156. * @param {RenderObject} renderObject - The render object.
  46157. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46158. */
  46159. createRenderPipeline( renderObject, promises ) {
  46160. const gl = this.gl;
  46161. const pipeline = renderObject.pipeline;
  46162. // Program
  46163. const { fragmentProgram, vertexProgram } = pipeline;
  46164. const programGPU = gl.createProgram();
  46165. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  46166. const vertexShader = this.get( vertexProgram ).shaderGPU;
  46167. gl.attachShader( programGPU, fragmentShader );
  46168. gl.attachShader( programGPU, vertexShader );
  46169. gl.linkProgram( programGPU );
  46170. this.set( pipeline, {
  46171. programGPU,
  46172. fragmentShader,
  46173. vertexShader
  46174. } );
  46175. if ( promises !== null && this.parallel ) {
  46176. const p = new Promise( ( resolve /*, reject*/ ) => {
  46177. const parallel = this.parallel;
  46178. const checkStatus = () => {
  46179. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  46180. this._completeCompile( renderObject, pipeline );
  46181. resolve();
  46182. } else {
  46183. requestAnimationFrame( checkStatus );
  46184. }
  46185. };
  46186. checkStatus();
  46187. } );
  46188. promises.push( p );
  46189. return;
  46190. }
  46191. this._completeCompile( renderObject, pipeline );
  46192. }
  46193. /**
  46194. * Formats the source code of error messages.
  46195. *
  46196. * @private
  46197. * @param {string} string - The code.
  46198. * @param {number} errorLine - The error line.
  46199. * @return {string} The formatted code.
  46200. */
  46201. _handleSource( string, errorLine ) {
  46202. const lines = string.split( '\n' );
  46203. const lines2 = [];
  46204. const from = Math.max( errorLine - 6, 0 );
  46205. const to = Math.min( errorLine + 6, lines.length );
  46206. for ( let i = from; i < to; i ++ ) {
  46207. const line = i + 1;
  46208. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46209. }
  46210. return lines2.join( '\n' );
  46211. }
  46212. /**
  46213. * Gets the shader compilation errors from the info log.
  46214. *
  46215. * @private
  46216. * @param {WebGL2RenderingContext} gl - The rendering context.
  46217. * @param {WebGLShader} shader - The WebGL shader object.
  46218. * @param {string} type - The shader type.
  46219. * @return {string} The shader errors.
  46220. */
  46221. _getShaderErrors( gl, shader, type ) {
  46222. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46223. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46224. const errors = shaderInfoLog.trim();
  46225. if ( status && errors === '' ) return '';
  46226. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46227. if ( errorMatches ) {
  46228. const errorLine = parseInt( errorMatches[ 1 ] );
  46229. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  46230. } else {
  46231. return errors;
  46232. }
  46233. }
  46234. /**
  46235. * Logs shader compilation errors.
  46236. *
  46237. * @private
  46238. * @param {WebGLProgram} programGPU - The WebGL program.
  46239. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  46240. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  46241. */
  46242. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  46243. if ( this.renderer.debug.checkShaderErrors ) {
  46244. const gl = this.gl;
  46245. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  46246. const programLog = programInfoLog.trim();
  46247. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46248. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  46249. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  46250. } else {
  46251. // default error reporting
  46252. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  46253. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  46254. console.error(
  46255. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46256. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  46257. 'Program Info Log: ' + programLog + '\n' +
  46258. vertexErrors + '\n' +
  46259. fragmentErrors
  46260. );
  46261. }
  46262. } else if ( programLog !== '' ) {
  46263. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  46264. }
  46265. }
  46266. }
  46267. /**
  46268. * Completes the shader program setup for the given render object.
  46269. *
  46270. * @private
  46271. * @param {RenderObject} renderObject - The render object.
  46272. * @param {RenderPipeline} pipeline - The render pipeline.
  46273. */
  46274. _completeCompile( renderObject, pipeline ) {
  46275. const { state, gl } = this;
  46276. const pipelineData = this.get( pipeline );
  46277. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  46278. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46279. this._logProgramError( programGPU, fragmentShader, vertexShader );
  46280. }
  46281. state.useProgram( programGPU );
  46282. // Bindings
  46283. const bindings = renderObject.getBindings();
  46284. this._setupBindings( bindings, programGPU );
  46285. //
  46286. this.set( pipeline, {
  46287. programGPU
  46288. } );
  46289. }
  46290. /**
  46291. * Creates a compute pipeline for the given compute node.
  46292. *
  46293. * @param {ComputePipeline} computePipeline - The compute pipeline.
  46294. * @param {Array<BindGroup>} bindings - The bindings.
  46295. */
  46296. createComputePipeline( computePipeline, bindings ) {
  46297. const { state, gl } = this;
  46298. // Program
  46299. const fragmentProgram = {
  46300. stage: 'fragment',
  46301. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  46302. };
  46303. this.createProgram( fragmentProgram );
  46304. const { computeProgram } = computePipeline;
  46305. const programGPU = gl.createProgram();
  46306. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  46307. const vertexShader = this.get( computeProgram ).shaderGPU;
  46308. const transforms = computeProgram.transforms;
  46309. const transformVaryingNames = [];
  46310. const transformAttributeNodes = [];
  46311. for ( let i = 0; i < transforms.length; i ++ ) {
  46312. const transform = transforms[ i ];
  46313. transformVaryingNames.push( transform.varyingName );
  46314. transformAttributeNodes.push( transform.attributeNode );
  46315. }
  46316. gl.attachShader( programGPU, fragmentShader );
  46317. gl.attachShader( programGPU, vertexShader );
  46318. gl.transformFeedbackVaryings(
  46319. programGPU,
  46320. transformVaryingNames,
  46321. gl.SEPARATE_ATTRIBS
  46322. );
  46323. gl.linkProgram( programGPU );
  46324. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46325. this._logProgramError( programGPU, fragmentShader, vertexShader );
  46326. }
  46327. state.useProgram( programGPU );
  46328. // Bindings
  46329. this._setupBindings( bindings, programGPU );
  46330. const attributeNodes = computeProgram.attributes;
  46331. const attributes = [];
  46332. const transformBuffers = [];
  46333. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  46334. const attribute = attributeNodes[ i ].node.attribute;
  46335. attributes.push( attribute );
  46336. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46337. }
  46338. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  46339. const attribute = transformAttributeNodes[ i ].attribute;
  46340. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46341. const attributeData = this.get( attribute );
  46342. transformBuffers.push( attributeData );
  46343. }
  46344. //
  46345. this.set( computePipeline, {
  46346. programGPU,
  46347. transformBuffers,
  46348. attributes
  46349. } );
  46350. }
  46351. /**
  46352. * Creates bindings from the given bind group definition.
  46353. *
  46354. * @param {BindGroup} bindGroup - The bind group.
  46355. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46356. * @param {number} cacheIndex - The cache index.
  46357. * @param {number} version - The version.
  46358. */
  46359. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  46360. if ( this._knownBindings.has( bindings ) === false ) {
  46361. this._knownBindings.add( bindings );
  46362. let uniformBuffers = 0;
  46363. let textures = 0;
  46364. for ( const bindGroup of bindings ) {
  46365. this.set( bindGroup, {
  46366. textures: textures,
  46367. uniformBuffers: uniformBuffers
  46368. } );
  46369. for ( const binding of bindGroup.bindings ) {
  46370. if ( binding.isUniformBuffer ) uniformBuffers ++;
  46371. if ( binding.isSampledTexture ) textures ++;
  46372. }
  46373. }
  46374. }
  46375. this.updateBindings( bindGroup, bindings );
  46376. }
  46377. /**
  46378. * Updates the given bind group definition.
  46379. *
  46380. * @param {BindGroup} bindGroup - The bind group.
  46381. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46382. * @param {number} cacheIndex - The cache index.
  46383. * @param {number} version - The version.
  46384. */
  46385. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  46386. const { gl } = this;
  46387. const bindGroupData = this.get( bindGroup );
  46388. let i = bindGroupData.uniformBuffers;
  46389. let t = bindGroupData.textures;
  46390. for ( const binding of bindGroup.bindings ) {
  46391. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46392. const data = binding.buffer;
  46393. const bufferGPU = gl.createBuffer();
  46394. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46395. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  46396. this.set( binding, {
  46397. index: i ++,
  46398. bufferGPU
  46399. } );
  46400. } else if ( binding.isSampledTexture ) {
  46401. const { textureGPU, glTextureType } = this.get( binding.texture );
  46402. this.set( binding, {
  46403. index: t ++,
  46404. textureGPU,
  46405. glTextureType
  46406. } );
  46407. }
  46408. }
  46409. }
  46410. /**
  46411. * Updates a buffer binding.
  46412. *
  46413. * @param {Buffer} binding - The buffer binding to update.
  46414. */
  46415. updateBinding( binding ) {
  46416. const gl = this.gl;
  46417. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46418. const bindingData = this.get( binding );
  46419. const bufferGPU = bindingData.bufferGPU;
  46420. const data = binding.buffer;
  46421. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46422. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  46423. }
  46424. }
  46425. // attributes
  46426. /**
  46427. * Creates the GPU buffer of an indexed shader attribute.
  46428. *
  46429. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  46430. */
  46431. createIndexAttribute( attribute ) {
  46432. const gl = this.gl;
  46433. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  46434. }
  46435. /**
  46436. * Creates the GPU buffer of a shader attribute.
  46437. *
  46438. * @param {BufferAttribute} attribute - The buffer attribute.
  46439. */
  46440. createAttribute( attribute ) {
  46441. if ( this.has( attribute ) ) return;
  46442. const gl = this.gl;
  46443. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46444. }
  46445. /**
  46446. * Creates the GPU buffer of a storage attribute.
  46447. *
  46448. * @param {BufferAttribute} attribute - The buffer attribute.
  46449. */
  46450. createStorageAttribute( attribute ) {
  46451. if ( this.has( attribute ) ) return;
  46452. const gl = this.gl;
  46453. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46454. }
  46455. /**
  46456. * Updates the GPU buffer of a shader attribute.
  46457. *
  46458. * @param {BufferAttribute} attribute - The buffer attribute to update.
  46459. */
  46460. updateAttribute( attribute ) {
  46461. this.attributeUtils.updateAttribute( attribute );
  46462. }
  46463. /**
  46464. * Destroys the GPU buffer of a shader attribute.
  46465. *
  46466. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  46467. */
  46468. destroyAttribute( attribute ) {
  46469. this.attributeUtils.destroyAttribute( attribute );
  46470. }
  46471. /**
  46472. * Checks if the given feature is supported by the backend.
  46473. *
  46474. * @param {string} name - The feature's name.
  46475. * @return {boolean} Whether the feature is supported or not.
  46476. */
  46477. hasFeature( name ) {
  46478. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  46479. const extensions = this.extensions;
  46480. for ( let i = 0; i < keysMatching.length; i ++ ) {
  46481. if ( extensions.has( keysMatching[ i ] ) ) return true;
  46482. }
  46483. return false;
  46484. }
  46485. /**
  46486. * Returns the maximum anisotropy texture filtering value.
  46487. *
  46488. * @return {number} The maximum anisotropy texture filtering value.
  46489. */
  46490. getMaxAnisotropy() {
  46491. return this.capabilities.getMaxAnisotropy();
  46492. }
  46493. /**
  46494. * Copies data of the given source texture to the given destination texture.
  46495. *
  46496. * @param {Texture} srcTexture - The source texture.
  46497. * @param {Texture} dstTexture - The destination texture.
  46498. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  46499. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  46500. * @param {number} [srcLevel=0] - The source mip level to copy from.
  46501. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  46502. */
  46503. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  46504. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  46505. }
  46506. /**
  46507. * Copies the current bound framebuffer to the given texture.
  46508. *
  46509. * @param {Texture} texture - The destination texture.
  46510. * @param {RenderContext} renderContext - The render context.
  46511. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46512. */
  46513. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46514. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  46515. }
  46516. /**
  46517. * Configures the active framebuffer from the given render context.
  46518. *
  46519. * @private
  46520. * @param {RenderContext} descriptor - The render context.
  46521. */
  46522. _setFramebuffer( descriptor ) {
  46523. const { gl, state } = this;
  46524. let currentFrameBuffer = null;
  46525. if ( descriptor.textures !== null ) {
  46526. const renderTarget = descriptor.renderTarget;
  46527. const renderTargetContextData = this.get( renderTarget );
  46528. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  46529. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  46530. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  46531. const isRenderTargetArray = renderTarget.depth > 1;
  46532. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  46533. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  46534. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  46535. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  46536. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46537. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  46538. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  46539. const cacheKey = getCacheKey( descriptor );
  46540. let fb;
  46541. if ( isCube ) {
  46542. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  46543. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  46544. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  46545. fb = this._xrFramebuffer;
  46546. } else {
  46547. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  46548. fb = renderTargetContextData.framebuffers[ cacheKey ];
  46549. }
  46550. if ( fb === undefined ) {
  46551. fb = gl.createFramebuffer();
  46552. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  46553. const textures = descriptor.textures;
  46554. const depthInvalidationArray = [];
  46555. if ( isCube ) {
  46556. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  46557. const { textureGPU } = this.get( textures[ 0 ] );
  46558. const cubeFace = this.renderer._activeCubeFace;
  46559. const mipLevel = this.renderer._activeMipmapLevel;
  46560. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  46561. } else {
  46562. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  46563. for ( let i = 0; i < textures.length; i ++ ) {
  46564. const texture = textures[ i ];
  46565. const textureData = this.get( texture );
  46566. textureData.renderTarget = descriptor.renderTarget;
  46567. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  46568. const attachment = gl.COLOR_ATTACHMENT0 + i;
  46569. if ( renderTarget.multiview ) {
  46570. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  46571. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  46572. const layer = this.renderer._activeCubeFace;
  46573. const mipLevel = this.renderer._activeMipmapLevel;
  46574. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  46575. } else {
  46576. if ( useMultisampledRTT ) {
  46577. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46578. } else {
  46579. const mipLevel = this.renderer._activeMipmapLevel;
  46580. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  46581. }
  46582. }
  46583. }
  46584. }
  46585. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46586. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  46587. const renderbuffer = gl.createRenderbuffer();
  46588. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  46589. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  46590. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  46591. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46592. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  46593. } else {
  46594. if ( descriptor.depthTexture !== null ) {
  46595. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  46596. const textureData = this.get( descriptor.depthTexture );
  46597. textureData.renderTarget = descriptor.renderTarget;
  46598. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  46599. if ( renderTarget.multiview ) {
  46600. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  46601. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  46602. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46603. } else {
  46604. if ( descriptor.depthTexture.isArrayTexture ) {
  46605. const layer = this.renderer._activeCubeFace;
  46606. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  46607. } else {
  46608. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  46609. }
  46610. }
  46611. }
  46612. }
  46613. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  46614. } else {
  46615. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  46616. if ( isRenderCameraDepthArray ) {
  46617. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  46618. const layer = this.renderer._activeCubeFace;
  46619. const depthData = this.get( descriptor.depthTexture );
  46620. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46621. gl.framebufferTextureLayer(
  46622. gl.FRAMEBUFFER,
  46623. depthStyle,
  46624. depthData.textureGPU,
  46625. 0,
  46626. layer
  46627. );
  46628. }
  46629. // rebind external XR textures
  46630. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  46631. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  46632. // rebind color
  46633. const textureData = this.get( descriptor.textures[ 0 ] );
  46634. if ( renderTarget.multiview ) {
  46635. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  46636. } else if ( useMultisampledRTT ) {
  46637. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46638. } else {
  46639. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  46640. }
  46641. // rebind depth
  46642. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46643. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  46644. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  46645. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46646. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  46647. } else {
  46648. const textureData = this.get( descriptor.depthTexture );
  46649. if ( renderTarget.multiview ) {
  46650. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  46651. } else if ( useMultisampledRTT ) {
  46652. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46653. } else {
  46654. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  46655. }
  46656. }
  46657. }
  46658. }
  46659. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  46660. if ( msaaFb === undefined ) {
  46661. const invalidationArray = [];
  46662. msaaFb = gl.createFramebuffer();
  46663. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  46664. const msaaRenderbuffers = [];
  46665. const textures = descriptor.textures;
  46666. for ( let i = 0; i < textures.length; i ++ ) {
  46667. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  46668. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  46669. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  46670. const texture = descriptor.textures[ i ];
  46671. const textureData = this.get( texture );
  46672. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  46673. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  46674. }
  46675. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  46676. renderTargetContextData.msaaFrameBuffer = msaaFb;
  46677. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  46678. if ( depthBuffer && depthRenderbuffer === undefined ) {
  46679. depthRenderbuffer = gl.createRenderbuffer();
  46680. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  46681. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  46682. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46683. invalidationArray.push( depthStyle );
  46684. }
  46685. renderTargetContextData.invalidationArray = invalidationArray;
  46686. }
  46687. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  46688. } else {
  46689. currentFrameBuffer = fb;
  46690. }
  46691. state.drawBuffers( descriptor, fb );
  46692. }
  46693. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  46694. }
  46695. /**
  46696. * Computes the VAO key for the given index and attributes.
  46697. *
  46698. * @private
  46699. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  46700. * @return {string} The VAO key.
  46701. */
  46702. _getVaoKey( attributes ) {
  46703. let key = '';
  46704. for ( let i = 0; i < attributes.length; i ++ ) {
  46705. const attributeData = this.get( attributes[ i ] );
  46706. key += ':' + attributeData.id;
  46707. }
  46708. return key;
  46709. }
  46710. /**
  46711. * Creates a VAO from the index and attributes.
  46712. *
  46713. * @private
  46714. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  46715. * @return {Object} The VAO data.
  46716. */
  46717. _createVao( attributes ) {
  46718. const { gl } = this;
  46719. const vaoGPU = gl.createVertexArray();
  46720. gl.bindVertexArray( vaoGPU );
  46721. for ( let i = 0; i < attributes.length; i ++ ) {
  46722. const attribute = attributes[ i ];
  46723. const attributeData = this.get( attribute );
  46724. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  46725. gl.enableVertexAttribArray( i );
  46726. let stride, offset;
  46727. if ( attribute.isInterleavedBufferAttribute === true ) {
  46728. stride = attribute.data.stride * attributeData.bytesPerElement;
  46729. offset = attribute.offset * attributeData.bytesPerElement;
  46730. } else {
  46731. stride = 0;
  46732. offset = 0;
  46733. }
  46734. if ( attributeData.isInteger ) {
  46735. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  46736. } else {
  46737. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  46738. }
  46739. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  46740. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  46741. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  46742. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  46743. }
  46744. }
  46745. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  46746. return vaoGPU;
  46747. }
  46748. /**
  46749. * Creates a transform feedback from the given transform buffers.
  46750. *
  46751. * @private
  46752. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  46753. * @return {WebGLTransformFeedback} The transform feedback.
  46754. */
  46755. _getTransformFeedback( transformBuffers ) {
  46756. let key = '';
  46757. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46758. key += ':' + transformBuffers[ i ].id;
  46759. }
  46760. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  46761. if ( transformFeedbackGPU !== undefined ) {
  46762. return transformFeedbackGPU;
  46763. }
  46764. const { gl } = this;
  46765. transformFeedbackGPU = gl.createTransformFeedback();
  46766. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  46767. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46768. const attributeData = transformBuffers[ i ];
  46769. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  46770. }
  46771. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  46772. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  46773. return transformFeedbackGPU;
  46774. }
  46775. /**
  46776. * Setups the given bindings.
  46777. *
  46778. * @private
  46779. * @param {Array<BindGroup>} bindings - The bindings.
  46780. * @param {WebGLProgram} programGPU - The WebGL program.
  46781. */
  46782. _setupBindings( bindings, programGPU ) {
  46783. const gl = this.gl;
  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. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  46790. gl.uniformBlockBinding( programGPU, location, index );
  46791. } else if ( binding.isSampledTexture ) {
  46792. const location = gl.getUniformLocation( programGPU, binding.name );
  46793. gl.uniform1i( location, index );
  46794. }
  46795. }
  46796. }
  46797. }
  46798. /**
  46799. * Binds the given uniforms.
  46800. *
  46801. * @private
  46802. * @param {Array<BindGroup>} bindings - The bindings.
  46803. */
  46804. _bindUniforms( bindings ) {
  46805. const { gl, state } = this;
  46806. for ( const bindGroup of bindings ) {
  46807. for ( const binding of bindGroup.bindings ) {
  46808. const bindingData = this.get( binding );
  46809. const index = bindingData.index;
  46810. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46811. // TODO USE bindBufferRange to group multiple uniform buffers
  46812. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  46813. } else if ( binding.isSampledTexture ) {
  46814. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  46815. }
  46816. }
  46817. }
  46818. }
  46819. /**
  46820. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  46821. * should be used when MSAA is enabled.
  46822. *
  46823. * @private
  46824. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  46825. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  46826. */
  46827. _useMultisampledExtension( renderTarget ) {
  46828. if ( renderTarget.multiview === true ) {
  46829. return true;
  46830. }
  46831. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  46832. }
  46833. /**
  46834. * Frees internal resources.
  46835. */
  46836. dispose() {
  46837. const extension = this.extensions.get( 'WEBGL_lose_context' );
  46838. if ( extension ) extension.loseContext();
  46839. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  46840. }
  46841. }
  46842. const GPUPrimitiveTopology = {
  46843. PointList: 'point-list',
  46844. LineList: 'line-list',
  46845. LineStrip: 'line-strip',
  46846. TriangleList: 'triangle-list',
  46847. TriangleStrip: 'triangle-strip',
  46848. };
  46849. const GPUCompareFunction = {
  46850. Never: 'never',
  46851. Less: 'less',
  46852. Equal: 'equal',
  46853. LessEqual: 'less-equal',
  46854. Greater: 'greater',
  46855. NotEqual: 'not-equal',
  46856. GreaterEqual: 'greater-equal',
  46857. Always: 'always'
  46858. };
  46859. const GPUStoreOp = {
  46860. Store: 'store'};
  46861. const GPULoadOp = {
  46862. Load: 'load',
  46863. Clear: 'clear'
  46864. };
  46865. const GPUFrontFace = {
  46866. CCW: 'ccw'};
  46867. const GPUCullMode = {
  46868. None: 'none',
  46869. Front: 'front',
  46870. Back: 'back'
  46871. };
  46872. const GPUIndexFormat = {
  46873. Uint16: 'uint16',
  46874. Uint32: 'uint32'
  46875. };
  46876. const GPUTextureFormat = {
  46877. // 8-bit formats
  46878. R8Unorm: 'r8unorm',
  46879. R8Snorm: 'r8snorm',
  46880. R8Uint: 'r8uint',
  46881. R8Sint: 'r8sint',
  46882. // 16-bit formats
  46883. R16Uint: 'r16uint',
  46884. R16Sint: 'r16sint',
  46885. R16Float: 'r16float',
  46886. RG8Unorm: 'rg8unorm',
  46887. RG8Snorm: 'rg8snorm',
  46888. RG8Uint: 'rg8uint',
  46889. RG8Sint: 'rg8sint',
  46890. // 32-bit formats
  46891. R32Uint: 'r32uint',
  46892. R32Sint: 'r32sint',
  46893. R32Float: 'r32float',
  46894. RG16Uint: 'rg16uint',
  46895. RG16Sint: 'rg16sint',
  46896. RG16Float: 'rg16float',
  46897. RGBA8Unorm: 'rgba8unorm',
  46898. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  46899. RGBA8Snorm: 'rgba8snorm',
  46900. RGBA8Uint: 'rgba8uint',
  46901. RGBA8Sint: 'rgba8sint',
  46902. BGRA8Unorm: 'bgra8unorm',
  46903. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  46904. // Packed 32-bit formats
  46905. RGB9E5UFloat: 'rgb9e5ufloat',
  46906. RGB10A2Unorm: 'rgb10a2unorm',
  46907. RG11B10UFloat: 'rgb10a2unorm',
  46908. // 64-bit formats
  46909. RG32Uint: 'rg32uint',
  46910. RG32Sint: 'rg32sint',
  46911. RG32Float: 'rg32float',
  46912. RGBA16Uint: 'rgba16uint',
  46913. RGBA16Sint: 'rgba16sint',
  46914. RGBA16Float: 'rgba16float',
  46915. // 128-bit formats
  46916. RGBA32Uint: 'rgba32uint',
  46917. RGBA32Sint: 'rgba32sint',
  46918. RGBA32Float: 'rgba32float',
  46919. Depth16Unorm: 'depth16unorm',
  46920. Depth24Plus: 'depth24plus',
  46921. Depth24PlusStencil8: 'depth24plus-stencil8',
  46922. Depth32Float: 'depth32float',
  46923. // 'depth32float-stencil8' extension
  46924. Depth32FloatStencil8: 'depth32float-stencil8',
  46925. // BC compressed formats usable if 'texture-compression-bc' is both
  46926. // supported by the device/user agent and enabled in requestDevice.
  46927. BC1RGBAUnorm: 'bc1-rgba-unorm',
  46928. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  46929. BC2RGBAUnorm: 'bc2-rgba-unorm',
  46930. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  46931. BC3RGBAUnorm: 'bc3-rgba-unorm',
  46932. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  46933. BC4RUnorm: 'bc4-r-unorm',
  46934. BC4RSnorm: 'bc4-r-snorm',
  46935. BC5RGUnorm: 'bc5-rg-unorm',
  46936. BC5RGSnorm: 'bc5-rg-snorm',
  46937. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  46938. BC6HRGBFloat: 'bc6h-rgb-float',
  46939. BC7RGBAUnorm: 'bc7-rgba-unorm',
  46940. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  46941. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  46942. // supported by the device/user agent and enabled in requestDevice.
  46943. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  46944. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  46945. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  46946. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  46947. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  46948. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  46949. EACR11Unorm: 'eac-r11unorm',
  46950. EACR11Snorm: 'eac-r11snorm',
  46951. EACRG11Unorm: 'eac-rg11unorm',
  46952. EACRG11Snorm: 'eac-rg11snorm',
  46953. // ASTC compressed formats usable if 'texture-compression-astc' is both
  46954. // supported by the device/user agent and enabled in requestDevice.
  46955. ASTC4x4Unorm: 'astc-4x4-unorm',
  46956. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  46957. ASTC5x4Unorm: 'astc-5x4-unorm',
  46958. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  46959. ASTC5x5Unorm: 'astc-5x5-unorm',
  46960. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  46961. ASTC6x5Unorm: 'astc-6x5-unorm',
  46962. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  46963. ASTC6x6Unorm: 'astc-6x6-unorm',
  46964. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  46965. ASTC8x5Unorm: 'astc-8x5-unorm',
  46966. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  46967. ASTC8x6Unorm: 'astc-8x6-unorm',
  46968. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  46969. ASTC8x8Unorm: 'astc-8x8-unorm',
  46970. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  46971. ASTC10x5Unorm: 'astc-10x5-unorm',
  46972. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  46973. ASTC10x6Unorm: 'astc-10x6-unorm',
  46974. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  46975. ASTC10x8Unorm: 'astc-10x8-unorm',
  46976. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  46977. ASTC10x10Unorm: 'astc-10x10-unorm',
  46978. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  46979. ASTC12x10Unorm: 'astc-12x10-unorm',
  46980. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  46981. ASTC12x12Unorm: 'astc-12x12-unorm',
  46982. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  46983. };
  46984. const GPUAddressMode = {
  46985. ClampToEdge: 'clamp-to-edge',
  46986. Repeat: 'repeat',
  46987. MirrorRepeat: 'mirror-repeat'
  46988. };
  46989. const GPUFilterMode = {
  46990. Linear: 'linear',
  46991. Nearest: 'nearest'
  46992. };
  46993. const GPUBlendFactor = {
  46994. Zero: 'zero',
  46995. One: 'one',
  46996. Src: 'src',
  46997. OneMinusSrc: 'one-minus-src',
  46998. SrcAlpha: 'src-alpha',
  46999. OneMinusSrcAlpha: 'one-minus-src-alpha',
  47000. Dst: 'dst',
  47001. OneMinusDst: 'one-minus-dst',
  47002. DstAlpha: 'dst-alpha',
  47003. OneMinusDstAlpha: 'one-minus-dst-alpha',
  47004. SrcAlphaSaturated: 'src-alpha-saturated',
  47005. Constant: 'constant',
  47006. OneMinusConstant: 'one-minus-constant'
  47007. };
  47008. const GPUBlendOperation = {
  47009. Add: 'add',
  47010. Subtract: 'subtract',
  47011. ReverseSubtract: 'reverse-subtract',
  47012. Min: 'min',
  47013. Max: 'max'
  47014. };
  47015. const GPUColorWriteFlags = {
  47016. None: 0,
  47017. All: 0xF
  47018. };
  47019. const GPUStencilOperation = {
  47020. Keep: 'keep',
  47021. Zero: 'zero',
  47022. Replace: 'replace',
  47023. Invert: 'invert',
  47024. IncrementClamp: 'increment-clamp',
  47025. DecrementClamp: 'decrement-clamp',
  47026. IncrementWrap: 'increment-wrap',
  47027. DecrementWrap: 'decrement-wrap'
  47028. };
  47029. const GPUBufferBindingType = {
  47030. Storage: 'storage',
  47031. ReadOnlyStorage: 'read-only-storage'
  47032. };
  47033. const GPUStorageTextureAccess = {
  47034. WriteOnly: 'write-only',
  47035. ReadOnly: 'read-only',
  47036. ReadWrite: 'read-write',
  47037. };
  47038. const GPUSamplerBindingType = {
  47039. NonFiltering: 'non-filtering',
  47040. Comparison: 'comparison'
  47041. };
  47042. const GPUTextureSampleType = {
  47043. Float: 'float',
  47044. UnfilterableFloat: 'unfilterable-float',
  47045. Depth: 'depth',
  47046. SInt: 'sint',
  47047. UInt: 'uint'
  47048. };
  47049. const GPUTextureDimension = {
  47050. TwoD: '2d',
  47051. ThreeD: '3d'
  47052. };
  47053. const GPUTextureViewDimension = {
  47054. TwoD: '2d',
  47055. TwoDArray: '2d-array',
  47056. Cube: 'cube',
  47057. ThreeD: '3d'
  47058. };
  47059. const GPUTextureAspect = {
  47060. All: 'all'};
  47061. const GPUInputStepMode = {
  47062. Vertex: 'vertex',
  47063. Instance: 'instance'
  47064. };
  47065. const GPUFeatureName = {
  47066. CoreFeaturesAndLimits: 'core-features-and-limits',
  47067. DepthClipControl: 'depth-clip-control',
  47068. Depth32FloatStencil8: 'depth32float-stencil8',
  47069. TextureCompressionBC: 'texture-compression-bc',
  47070. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  47071. TextureCompressionETC2: 'texture-compression-etc2',
  47072. TextureCompressionASTC: 'texture-compression-astc',
  47073. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  47074. TimestampQuery: 'timestamp-query',
  47075. IndirectFirstInstance: 'indirect-first-instance',
  47076. ShaderF16: 'shader-f16',
  47077. RG11B10UFloat: 'rg11b10ufloat-renderable',
  47078. BGRA8UNormStorage: 'bgra8unorm-storage',
  47079. Float32Filterable: 'float32-filterable',
  47080. Float32Blendable: 'float32-blendable',
  47081. ClipDistances: 'clip-distances',
  47082. DualSourceBlending: 'dual-source-blending',
  47083. Subgroups: 'subgroups',
  47084. TextureFormatsTier1: 'texture-formats-tier1',
  47085. TextureFormatsTier2: 'texture-formats-tier2'
  47086. };
  47087. /**
  47088. * A special form of sampler binding type.
  47089. * It's texture value is managed by a node object.
  47090. *
  47091. * @private
  47092. * @augments Sampler
  47093. */
  47094. class NodeSampler extends Sampler {
  47095. /**
  47096. * Constructs a new node-based sampler.
  47097. *
  47098. * @param {string} name - The samplers's name.
  47099. * @param {TextureNode} textureNode - The texture node.
  47100. * @param {UniformGroupNode} groupNode - The uniform group node.
  47101. */
  47102. constructor( name, textureNode, groupNode ) {
  47103. super( name, textureNode ? textureNode.value : null );
  47104. /**
  47105. * The texture node.
  47106. *
  47107. * @type {TextureNode}
  47108. */
  47109. this.textureNode = textureNode;
  47110. /**
  47111. * The uniform group node.
  47112. *
  47113. * @type {UniformGroupNode}
  47114. */
  47115. this.groupNode = groupNode;
  47116. }
  47117. /**
  47118. * Updates the texture value of this sampler.
  47119. */
  47120. update() {
  47121. this.texture = this.textureNode.value;
  47122. }
  47123. }
  47124. /**
  47125. * Represents a storage buffer binding type.
  47126. *
  47127. * @private
  47128. * @augments Buffer
  47129. */
  47130. class StorageBuffer extends Buffer {
  47131. /**
  47132. * Constructs a new uniform buffer.
  47133. *
  47134. * @param {string} name - The buffer's name.
  47135. * @param {BufferAttribute} attribute - The buffer attribute.
  47136. */
  47137. constructor( name, attribute ) {
  47138. super( name, attribute ? attribute.array : null );
  47139. /**
  47140. * This flag can be used for type testing.
  47141. *
  47142. * @type {BufferAttribute}
  47143. */
  47144. this.attribute = attribute;
  47145. /**
  47146. * This flag can be used for type testing.
  47147. *
  47148. * @type {boolean}
  47149. * @readonly
  47150. * @default true
  47151. */
  47152. this.isStorageBuffer = true;
  47153. }
  47154. }
  47155. let _id = 0;
  47156. /**
  47157. * A special form of storage buffer binding type.
  47158. * It's buffer value is managed by a node object.
  47159. *
  47160. * @private
  47161. * @augments StorageBuffer
  47162. */
  47163. class NodeStorageBuffer extends StorageBuffer {
  47164. /**
  47165. * Constructs a new node-based storage buffer.
  47166. *
  47167. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  47168. * @param {UniformGroupNode} groupNode - The uniform group node.
  47169. */
  47170. constructor( nodeUniform, groupNode ) {
  47171. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  47172. /**
  47173. * The node uniform.
  47174. *
  47175. * @type {StorageBufferNode}
  47176. */
  47177. this.nodeUniform = nodeUniform;
  47178. /**
  47179. * The access type.
  47180. *
  47181. * @type {string}
  47182. */
  47183. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  47184. /**
  47185. * The uniform group node.
  47186. *
  47187. * @type {UniformGroupNode}
  47188. */
  47189. this.groupNode = groupNode;
  47190. }
  47191. /**
  47192. * The storage buffer.
  47193. *
  47194. * @type {BufferAttribute}
  47195. */
  47196. get buffer() {
  47197. return this.nodeUniform.value;
  47198. }
  47199. }
  47200. /**
  47201. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  47202. *
  47203. * @private
  47204. */
  47205. class WebGPUTexturePassUtils extends DataMap {
  47206. /**
  47207. * Constructs a new utility object.
  47208. *
  47209. * @param {GPUDevice} device - The WebGPU device.
  47210. */
  47211. constructor( device ) {
  47212. super();
  47213. /**
  47214. * The WebGPU device.
  47215. *
  47216. * @type {GPUDevice}
  47217. */
  47218. this.device = device;
  47219. const mipmapVertexSource = `
  47220. struct VarysStruct {
  47221. @builtin( position ) Position: vec4<f32>,
  47222. @location( 0 ) vTex : vec2<f32>
  47223. };
  47224. @vertex
  47225. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  47226. var Varys : VarysStruct;
  47227. var pos = array< vec2<f32>, 4 >(
  47228. vec2<f32>( -1.0, 1.0 ),
  47229. vec2<f32>( 1.0, 1.0 ),
  47230. vec2<f32>( -1.0, -1.0 ),
  47231. vec2<f32>( 1.0, -1.0 )
  47232. );
  47233. var tex = array< vec2<f32>, 4 >(
  47234. vec2<f32>( 0.0, 0.0 ),
  47235. vec2<f32>( 1.0, 0.0 ),
  47236. vec2<f32>( 0.0, 1.0 ),
  47237. vec2<f32>( 1.0, 1.0 )
  47238. );
  47239. Varys.vTex = tex[ vertexIndex ];
  47240. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  47241. return Varys;
  47242. }
  47243. `;
  47244. const mipmapFragmentSource = `
  47245. @group( 0 ) @binding( 0 )
  47246. var imgSampler : sampler;
  47247. @group( 0 ) @binding( 1 )
  47248. var img : texture_2d<f32>;
  47249. @fragment
  47250. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  47251. return textureSample( img, imgSampler, vTex );
  47252. }
  47253. `;
  47254. const flipYFragmentSource = `
  47255. @group( 0 ) @binding( 0 )
  47256. var imgSampler : sampler;
  47257. @group( 0 ) @binding( 1 )
  47258. var img : texture_2d<f32>;
  47259. @fragment
  47260. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  47261. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  47262. }
  47263. `;
  47264. /**
  47265. * The mipmap GPU sampler.
  47266. *
  47267. * @type {GPUSampler}
  47268. */
  47269. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  47270. /**
  47271. * The flipY GPU sampler.
  47272. *
  47273. * @type {GPUSampler}
  47274. */
  47275. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  47276. /**
  47277. * A cache for GPU render pipelines used for copy/transfer passes.
  47278. * Every texture format requires a unique pipeline.
  47279. *
  47280. * @type {Object<string,GPURenderPipeline>}
  47281. */
  47282. this.transferPipelines = {};
  47283. /**
  47284. * A cache for GPU render pipelines used for flipY passes.
  47285. * Every texture format requires a unique pipeline.
  47286. *
  47287. * @type {Object<string,GPURenderPipeline>}
  47288. */
  47289. this.flipYPipelines = {};
  47290. /**
  47291. * The mipmap vertex shader module.
  47292. *
  47293. * @type {GPUShaderModule}
  47294. */
  47295. this.mipmapVertexShaderModule = device.createShaderModule( {
  47296. label: 'mipmapVertex',
  47297. code: mipmapVertexSource
  47298. } );
  47299. /**
  47300. * The mipmap fragment shader module.
  47301. *
  47302. * @type {GPUShaderModule}
  47303. */
  47304. this.mipmapFragmentShaderModule = device.createShaderModule( {
  47305. label: 'mipmapFragment',
  47306. code: mipmapFragmentSource
  47307. } );
  47308. /**
  47309. * The flipY fragment shader module.
  47310. *
  47311. * @type {GPUShaderModule}
  47312. */
  47313. this.flipYFragmentShaderModule = device.createShaderModule( {
  47314. label: 'flipYFragment',
  47315. code: flipYFragmentSource
  47316. } );
  47317. }
  47318. /**
  47319. * Returns a render pipeline for the internal copy render pass. The pass
  47320. * requires a unique render pipeline for each texture format.
  47321. *
  47322. * @param {string} format - The GPU texture format
  47323. * @return {GPURenderPipeline} The GPU render pipeline.
  47324. */
  47325. getTransferPipeline( format ) {
  47326. let pipeline = this.transferPipelines[ format ];
  47327. if ( pipeline === undefined ) {
  47328. pipeline = this.device.createRenderPipeline( {
  47329. label: `mipmap-${ format }`,
  47330. vertex: {
  47331. module: this.mipmapVertexShaderModule,
  47332. entryPoint: 'main'
  47333. },
  47334. fragment: {
  47335. module: this.mipmapFragmentShaderModule,
  47336. entryPoint: 'main',
  47337. targets: [ { format } ]
  47338. },
  47339. primitive: {
  47340. topology: GPUPrimitiveTopology.TriangleStrip,
  47341. stripIndexFormat: GPUIndexFormat.Uint32
  47342. },
  47343. layout: 'auto'
  47344. } );
  47345. this.transferPipelines[ format ] = pipeline;
  47346. }
  47347. return pipeline;
  47348. }
  47349. /**
  47350. * Returns a render pipeline for the flipY render pass. The pass
  47351. * requires a unique render pipeline for each texture format.
  47352. *
  47353. * @param {string} format - The GPU texture format
  47354. * @return {GPURenderPipeline} The GPU render pipeline.
  47355. */
  47356. getFlipYPipeline( format ) {
  47357. let pipeline = this.flipYPipelines[ format ];
  47358. if ( pipeline === undefined ) {
  47359. pipeline = this.device.createRenderPipeline( {
  47360. label: `flipY-${ format }`,
  47361. vertex: {
  47362. module: this.mipmapVertexShaderModule,
  47363. entryPoint: 'main'
  47364. },
  47365. fragment: {
  47366. module: this.flipYFragmentShaderModule,
  47367. entryPoint: 'main',
  47368. targets: [ { format } ]
  47369. },
  47370. primitive: {
  47371. topology: GPUPrimitiveTopology.TriangleStrip,
  47372. stripIndexFormat: GPUIndexFormat.Uint32
  47373. },
  47374. layout: 'auto'
  47375. } );
  47376. this.flipYPipelines[ format ] = pipeline;
  47377. }
  47378. return pipeline;
  47379. }
  47380. /**
  47381. * Flip the contents of the given GPU texture along its vertical axis.
  47382. *
  47383. * @param {GPUTexture} textureGPU - The GPU texture object.
  47384. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47385. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  47386. */
  47387. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  47388. const format = textureGPUDescriptor.format;
  47389. const { width, height } = textureGPUDescriptor.size;
  47390. const transferPipeline = this.getTransferPipeline( format );
  47391. const flipYPipeline = this.getFlipYPipeline( format );
  47392. const tempTexture = this.device.createTexture( {
  47393. size: { width, height, depthOrArrayLayers: 1 },
  47394. format,
  47395. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  47396. } );
  47397. const srcView = textureGPU.createView( {
  47398. baseMipLevel: 0,
  47399. mipLevelCount: 1,
  47400. dimension: GPUTextureViewDimension.TwoD,
  47401. baseArrayLayer
  47402. } );
  47403. const dstView = tempTexture.createView( {
  47404. baseMipLevel: 0,
  47405. mipLevelCount: 1,
  47406. dimension: GPUTextureViewDimension.TwoD,
  47407. baseArrayLayer: 0
  47408. } );
  47409. const commandEncoder = this.device.createCommandEncoder( {} );
  47410. const pass = ( pipeline, sourceView, destinationView ) => {
  47411. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  47412. const bindGroup = this.device.createBindGroup( {
  47413. layout: bindGroupLayout,
  47414. entries: [ {
  47415. binding: 0,
  47416. resource: this.flipYSampler
  47417. }, {
  47418. binding: 1,
  47419. resource: sourceView
  47420. } ]
  47421. } );
  47422. const passEncoder = commandEncoder.beginRenderPass( {
  47423. colorAttachments: [ {
  47424. view: destinationView,
  47425. loadOp: GPULoadOp.Clear,
  47426. storeOp: GPUStoreOp.Store,
  47427. clearValue: [ 0, 0, 0, 0 ]
  47428. } ]
  47429. } );
  47430. passEncoder.setPipeline( pipeline );
  47431. passEncoder.setBindGroup( 0, bindGroup );
  47432. passEncoder.draw( 4, 1, 0, 0 );
  47433. passEncoder.end();
  47434. };
  47435. pass( transferPipeline, srcView, dstView );
  47436. pass( flipYPipeline, dstView, srcView );
  47437. this.device.queue.submit( [ commandEncoder.finish() ] );
  47438. tempTexture.destroy();
  47439. }
  47440. /**
  47441. * Generates mipmaps for the given GPU texture.
  47442. *
  47443. * @param {GPUTexture} textureGPU - The GPU texture object.
  47444. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47445. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  47446. */
  47447. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  47448. const textureData = this.get( textureGPU );
  47449. if ( textureData.useCount === undefined ) {
  47450. textureData.useCount = 0;
  47451. textureData.layers = [];
  47452. }
  47453. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  47454. const commandEncoder = this.device.createCommandEncoder( {} );
  47455. this._mipmapRunBundles( commandEncoder, passes );
  47456. this.device.queue.submit( [ commandEncoder.finish() ] );
  47457. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  47458. textureData.useCount ++;
  47459. }
  47460. /**
  47461. * Since multiple copy render passes are required to generate mipmaps, the passes
  47462. * are managed as render bundles to improve performance.
  47463. *
  47464. * @param {GPUTexture} textureGPU - The GPU texture object.
  47465. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47466. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  47467. * @return {Array<Object>} An array of render bundles.
  47468. */
  47469. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  47470. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  47471. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  47472. let srcView = textureGPU.createView( {
  47473. baseMipLevel: 0,
  47474. mipLevelCount: 1,
  47475. dimension: GPUTextureViewDimension.TwoD,
  47476. baseArrayLayer
  47477. } );
  47478. const passes = [];
  47479. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  47480. const bindGroup = this.device.createBindGroup( {
  47481. layout: bindGroupLayout,
  47482. entries: [ {
  47483. binding: 0,
  47484. resource: this.mipmapSampler
  47485. }, {
  47486. binding: 1,
  47487. resource: srcView
  47488. } ]
  47489. } );
  47490. const dstView = textureGPU.createView( {
  47491. baseMipLevel: i,
  47492. mipLevelCount: 1,
  47493. dimension: GPUTextureViewDimension.TwoD,
  47494. baseArrayLayer
  47495. } );
  47496. const passDescriptor = {
  47497. colorAttachments: [ {
  47498. view: dstView,
  47499. loadOp: GPULoadOp.Clear,
  47500. storeOp: GPUStoreOp.Store,
  47501. clearValue: [ 0, 0, 0, 0 ]
  47502. } ]
  47503. };
  47504. const passEncoder = this.device.createRenderBundleEncoder( {
  47505. colorFormats: [ textureGPUDescriptor.format ]
  47506. } );
  47507. passEncoder.setPipeline( pipeline );
  47508. passEncoder.setBindGroup( 0, bindGroup );
  47509. passEncoder.draw( 4, 1, 0, 0 );
  47510. passes.push( {
  47511. renderBundles: [ passEncoder.finish() ],
  47512. passDescriptor
  47513. } );
  47514. srcView = dstView;
  47515. }
  47516. return passes;
  47517. }
  47518. /**
  47519. * Executes the render bundles.
  47520. *
  47521. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  47522. * @param {Array<Object>} passes - An array of render bundles.
  47523. */
  47524. _mipmapRunBundles( commandEncoder, passes ) {
  47525. const levels = passes.length;
  47526. for ( let i = 0; i < levels; i ++ ) {
  47527. const pass = passes[ i ];
  47528. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  47529. passEncoder.executeBundles( pass.renderBundles );
  47530. passEncoder.end();
  47531. }
  47532. }
  47533. }
  47534. const _compareToWebGPU = {
  47535. [ NeverCompare ]: 'never',
  47536. [ LessCompare ]: 'less',
  47537. [ EqualCompare ]: 'equal',
  47538. [ LessEqualCompare ]: 'less-equal',
  47539. [ GreaterCompare ]: 'greater',
  47540. [ GreaterEqualCompare ]: 'greater-equal',
  47541. [ AlwaysCompare ]: 'always',
  47542. [ NotEqualCompare ]: 'not-equal'
  47543. };
  47544. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  47545. /**
  47546. * A WebGPU backend utility module for managing textures.
  47547. *
  47548. * @private
  47549. */
  47550. class WebGPUTextureUtils {
  47551. /**
  47552. * Constructs a new utility object.
  47553. *
  47554. * @param {WebGPUBackend} backend - The WebGPU backend.
  47555. */
  47556. constructor( backend ) {
  47557. /**
  47558. * A reference to the WebGPU backend.
  47559. *
  47560. * @type {WebGPUBackend}
  47561. */
  47562. this.backend = backend;
  47563. /**
  47564. * A reference to the pass utils.
  47565. *
  47566. * @type {?WebGPUTexturePassUtils}
  47567. * @default null
  47568. */
  47569. this._passUtils = null;
  47570. /**
  47571. * A dictionary for managing default textures. The key
  47572. * is the texture format, the value the texture object.
  47573. *
  47574. * @type {Object<string,Texture>}
  47575. */
  47576. this.defaultTexture = {};
  47577. /**
  47578. * A dictionary for managing default cube textures. The key
  47579. * is the texture format, the value the texture object.
  47580. *
  47581. * @type {Object<string,CubeTexture>}
  47582. */
  47583. this.defaultCubeTexture = {};
  47584. /**
  47585. * A default video frame.
  47586. *
  47587. * @type {?VideoFrame}
  47588. * @default null
  47589. */
  47590. this.defaultVideoFrame = null;
  47591. /**
  47592. * Represents the color attachment of the default framebuffer.
  47593. *
  47594. * @type {?GPUTexture}
  47595. * @default null
  47596. */
  47597. this.colorBuffer = null;
  47598. /**
  47599. * Represents the depth attachment of the default framebuffer.
  47600. *
  47601. * @type {DepthTexture}
  47602. */
  47603. this.depthTexture = new DepthTexture();
  47604. this.depthTexture.name = 'depthBuffer';
  47605. }
  47606. /**
  47607. * Creates a GPU sampler for the given texture.
  47608. *
  47609. * @param {Texture} texture - The texture to create the sampler for.
  47610. */
  47611. createSampler( texture ) {
  47612. const backend = this.backend;
  47613. const device = backend.device;
  47614. const textureGPU = backend.get( texture );
  47615. const samplerDescriptorGPU = {
  47616. addressModeU: this._convertAddressMode( texture.wrapS ),
  47617. addressModeV: this._convertAddressMode( texture.wrapT ),
  47618. addressModeW: this._convertAddressMode( texture.wrapR ),
  47619. magFilter: this._convertFilterMode( texture.magFilter ),
  47620. minFilter: this._convertFilterMode( texture.minFilter ),
  47621. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  47622. maxAnisotropy: 1
  47623. };
  47624. // anisotropy can only be used when all filter modes are set to linear.
  47625. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  47626. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  47627. }
  47628. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  47629. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  47630. }
  47631. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  47632. }
  47633. /**
  47634. * Creates a default texture for the given texture that can be used
  47635. * as a placeholder until the actual texture is ready for usage.
  47636. *
  47637. * @param {Texture} texture - The texture to create a default texture for.
  47638. */
  47639. createDefaultTexture( texture ) {
  47640. let textureGPU;
  47641. const format = getFormat( texture );
  47642. if ( texture.isCubeTexture ) {
  47643. textureGPU = this._getDefaultCubeTextureGPU( format );
  47644. } else {
  47645. textureGPU = this._getDefaultTextureGPU( format );
  47646. }
  47647. this.backend.get( texture ).texture = textureGPU;
  47648. }
  47649. /**
  47650. * Defines a texture on the GPU for the given texture object.
  47651. *
  47652. * @param {Texture} texture - The texture.
  47653. * @param {Object} [options={}] - Optional configuration parameter.
  47654. */
  47655. createTexture( texture, options = {} ) {
  47656. const backend = this.backend;
  47657. const textureData = backend.get( texture );
  47658. if ( textureData.initialized ) {
  47659. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  47660. }
  47661. if ( texture.isExternalTexture ) {
  47662. textureData.texture = texture.sourceTexture;
  47663. textureData.initialized = true;
  47664. return;
  47665. }
  47666. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  47667. if ( options.levels === undefined ) options.levels = 1;
  47668. if ( options.depth === undefined ) options.depth = 1;
  47669. const { width, height, depth, levels } = options;
  47670. if ( texture.isFramebufferTexture ) {
  47671. if ( options.renderTarget ) {
  47672. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  47673. } else {
  47674. options.format = this.backend.utils.getPreferredCanvasFormat();
  47675. }
  47676. }
  47677. const dimension = this._getDimension( texture );
  47678. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  47679. textureData.format = format;
  47680. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  47681. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  47682. if ( texture.isStorageTexture === true ) {
  47683. usage |= GPUTextureUsage.STORAGE_BINDING;
  47684. }
  47685. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  47686. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  47687. }
  47688. const textureDescriptorGPU = {
  47689. label: texture.name,
  47690. size: {
  47691. width: width,
  47692. height: height,
  47693. depthOrArrayLayers: depth,
  47694. },
  47695. mipLevelCount: levels,
  47696. sampleCount: primarySamples,
  47697. dimension: dimension,
  47698. format: format,
  47699. usage: usage
  47700. };
  47701. // texture creation
  47702. if ( format === undefined ) {
  47703. console.warn( 'WebGPURenderer: Texture format not supported.' );
  47704. this.createDefaultTexture( texture );
  47705. return;
  47706. }
  47707. if ( texture.isCubeTexture ) {
  47708. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  47709. }
  47710. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  47711. if ( isMSAA ) {
  47712. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  47713. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  47714. msaaTextureDescriptorGPU.sampleCount = samples;
  47715. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  47716. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  47717. }
  47718. textureData.initialized = true;
  47719. textureData.textureDescriptorGPU = textureDescriptorGPU;
  47720. }
  47721. /**
  47722. * Destroys the GPU data for the given texture object.
  47723. *
  47724. * @param {Texture} texture - The texture.
  47725. */
  47726. destroyTexture( texture ) {
  47727. const backend = this.backend;
  47728. const textureData = backend.get( texture );
  47729. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  47730. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  47731. backend.delete( texture );
  47732. }
  47733. /**
  47734. * Destroys the GPU sampler for the given texture.
  47735. *
  47736. * @param {Texture} texture - The texture to destroy the sampler for.
  47737. */
  47738. destroySampler( texture ) {
  47739. const backend = this.backend;
  47740. const textureData = backend.get( texture );
  47741. delete textureData.sampler;
  47742. }
  47743. /**
  47744. * Generates mipmaps for the given texture.
  47745. *
  47746. * @param {Texture} texture - The texture.
  47747. */
  47748. generateMipmaps( texture ) {
  47749. const textureData = this.backend.get( texture );
  47750. if ( texture.isCubeTexture ) {
  47751. for ( let i = 0; i < 6; i ++ ) {
  47752. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  47753. }
  47754. } else {
  47755. const depth = texture.image.depth || 1;
  47756. for ( let i = 0; i < depth; i ++ ) {
  47757. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  47758. }
  47759. }
  47760. }
  47761. /**
  47762. * Returns the color buffer representing the color
  47763. * attachment of the default framebuffer.
  47764. *
  47765. * @return {GPUTexture} The color buffer.
  47766. */
  47767. getColorBuffer() {
  47768. if ( this.colorBuffer ) this.colorBuffer.destroy();
  47769. const backend = this.backend;
  47770. const { width, height } = backend.getDrawingBufferSize();
  47771. this.colorBuffer = backend.device.createTexture( {
  47772. label: 'colorBuffer',
  47773. size: {
  47774. width: width,
  47775. height: height,
  47776. depthOrArrayLayers: 1
  47777. },
  47778. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  47779. format: backend.utils.getPreferredCanvasFormat(),
  47780. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  47781. } );
  47782. return this.colorBuffer;
  47783. }
  47784. /**
  47785. * Returns the depth buffer representing the depth
  47786. * attachment of the default framebuffer.
  47787. *
  47788. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  47789. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  47790. * @return {GPUTexture} The depth buffer.
  47791. */
  47792. getDepthBuffer( depth = true, stencil = false ) {
  47793. const backend = this.backend;
  47794. const { width, height } = backend.getDrawingBufferSize();
  47795. const depthTexture = this.depthTexture;
  47796. const depthTextureGPU = backend.get( depthTexture ).texture;
  47797. let format, type;
  47798. if ( stencil ) {
  47799. format = DepthStencilFormat;
  47800. type = UnsignedInt248Type;
  47801. } else if ( depth ) {
  47802. format = DepthFormat;
  47803. type = UnsignedIntType;
  47804. }
  47805. if ( depthTextureGPU !== undefined ) {
  47806. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  47807. return depthTextureGPU;
  47808. }
  47809. this.destroyTexture( depthTexture );
  47810. }
  47811. depthTexture.name = 'depthBuffer';
  47812. depthTexture.format = format;
  47813. depthTexture.type = type;
  47814. depthTexture.image.width = width;
  47815. depthTexture.image.height = height;
  47816. this.createTexture( depthTexture, { width, height } );
  47817. return backend.get( depthTexture ).texture;
  47818. }
  47819. /**
  47820. * Uploads the updated texture data to the GPU.
  47821. *
  47822. * @param {Texture} texture - The texture.
  47823. * @param {Object} [options={}] - Optional configuration parameter.
  47824. */
  47825. updateTexture( texture, options ) {
  47826. const textureData = this.backend.get( texture );
  47827. const mipmaps = texture.mipmaps;
  47828. const { textureDescriptorGPU } = textureData;
  47829. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  47830. return;
  47831. // transfer texture data
  47832. if ( texture.isDataTexture ) {
  47833. if ( mipmaps.length > 0 ) {
  47834. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47835. const mipmap = mipmaps[ i ];
  47836. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  47837. }
  47838. } else {
  47839. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  47840. }
  47841. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  47842. for ( let i = 0; i < options.image.depth; i ++ ) {
  47843. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  47844. }
  47845. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  47846. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  47847. } else if ( texture.isCubeTexture ) {
  47848. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  47849. } else {
  47850. if ( mipmaps.length > 0 ) {
  47851. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47852. const mipmap = mipmaps[ i ];
  47853. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  47854. }
  47855. } else {
  47856. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  47857. }
  47858. }
  47859. //
  47860. textureData.version = texture.version;
  47861. if ( texture.onUpdate ) texture.onUpdate( texture );
  47862. }
  47863. /**
  47864. * Returns texture data as a typed array.
  47865. *
  47866. * @async
  47867. * @param {Texture} texture - The texture to copy.
  47868. * @param {number} x - The x coordinate of the copy origin.
  47869. * @param {number} y - The y coordinate of the copy origin.
  47870. * @param {number} width - The width of the copy.
  47871. * @param {number} height - The height of the copy.
  47872. * @param {number} faceIndex - The face index.
  47873. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47874. */
  47875. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47876. const device = this.backend.device;
  47877. const textureData = this.backend.get( texture );
  47878. const textureGPU = textureData.texture;
  47879. const format = textureData.textureDescriptorGPU.format;
  47880. const bytesPerTexel = this._getBytesPerTexel( format );
  47881. let bytesPerRow = width * bytesPerTexel;
  47882. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  47883. const readBuffer = device.createBuffer(
  47884. {
  47885. size: width * height * bytesPerTexel,
  47886. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47887. }
  47888. );
  47889. const encoder = device.createCommandEncoder();
  47890. encoder.copyTextureToBuffer(
  47891. {
  47892. texture: textureGPU,
  47893. origin: { x, y, z: faceIndex },
  47894. },
  47895. {
  47896. buffer: readBuffer,
  47897. bytesPerRow: bytesPerRow
  47898. },
  47899. {
  47900. width: width,
  47901. height: height
  47902. }
  47903. );
  47904. const typedArrayType = this._getTypedArrayType( format );
  47905. device.queue.submit( [ encoder.finish() ] );
  47906. await readBuffer.mapAsync( GPUMapMode.READ );
  47907. const buffer = readBuffer.getMappedRange();
  47908. return new typedArrayType( buffer );
  47909. }
  47910. /**
  47911. * Returns the default GPU texture for the given format.
  47912. *
  47913. * @private
  47914. * @param {string} format - The GPU format.
  47915. * @return {GPUTexture} The GPU texture.
  47916. */
  47917. _getDefaultTextureGPU( format ) {
  47918. let defaultTexture = this.defaultTexture[ format ];
  47919. if ( defaultTexture === undefined ) {
  47920. const texture = new Texture();
  47921. texture.minFilter = NearestFilter;
  47922. texture.magFilter = NearestFilter;
  47923. this.createTexture( texture, { width: 1, height: 1, format } );
  47924. this.defaultTexture[ format ] = defaultTexture = texture;
  47925. }
  47926. return this.backend.get( defaultTexture ).texture;
  47927. }
  47928. /**
  47929. * Returns the default GPU cube texture for the given format.
  47930. *
  47931. * @private
  47932. * @param {string} format - The GPU format.
  47933. * @return {GPUTexture} The GPU texture.
  47934. */
  47935. _getDefaultCubeTextureGPU( format ) {
  47936. let defaultCubeTexture = this.defaultTexture[ format ];
  47937. if ( defaultCubeTexture === undefined ) {
  47938. const texture = new CubeTexture();
  47939. texture.minFilter = NearestFilter;
  47940. texture.magFilter = NearestFilter;
  47941. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  47942. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  47943. }
  47944. return this.backend.get( defaultCubeTexture ).texture;
  47945. }
  47946. /**
  47947. * Uploads cube texture image data to the GPU memory.
  47948. *
  47949. * @private
  47950. * @param {CubeTexture} texture - The cube texture.
  47951. * @param {GPUTexture} textureGPU - The GPU texture.
  47952. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47953. */
  47954. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  47955. const images = texture.images;
  47956. const mipmaps = texture.mipmaps;
  47957. for ( let i = 0; i < 6; i ++ ) {
  47958. const image = images[ i ];
  47959. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  47960. if ( image.isDataTexture ) {
  47961. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  47962. } else {
  47963. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  47964. }
  47965. for ( let j = 0; j < mipmaps.length; j ++ ) {
  47966. const mipmap = mipmaps[ j ];
  47967. const image = mipmap.images[ i ];
  47968. if ( image.isDataTexture ) {
  47969. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  47970. } else {
  47971. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  47972. }
  47973. }
  47974. }
  47975. }
  47976. /**
  47977. * Uploads texture image data to the GPU memory.
  47978. *
  47979. * @private
  47980. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  47981. * @param {GPUTexture} textureGPU - The GPU texture.
  47982. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47983. * @param {number} originDepth - The origin depth.
  47984. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  47985. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  47986. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  47987. */
  47988. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  47989. const device = this.backend.device;
  47990. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  47991. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  47992. device.queue.copyExternalImageToTexture(
  47993. {
  47994. source: image,
  47995. flipY: flipY
  47996. }, {
  47997. texture: textureGPU,
  47998. mipLevel: mipLevel,
  47999. origin: { x: 0, y: 0, z: originDepth },
  48000. premultipliedAlpha: premultiplyAlpha
  48001. }, {
  48002. width: width,
  48003. height: height,
  48004. depthOrArrayLayers: 1
  48005. }
  48006. );
  48007. }
  48008. /**
  48009. * Returns the pass utils singleton.
  48010. *
  48011. * @private
  48012. * @return {WebGPUTexturePassUtils} The utils instance.
  48013. */
  48014. _getPassUtils() {
  48015. let passUtils = this._passUtils;
  48016. if ( passUtils === null ) {
  48017. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  48018. }
  48019. return passUtils;
  48020. }
  48021. /**
  48022. * Generates mipmaps for the given GPU texture.
  48023. *
  48024. * @private
  48025. * @param {GPUTexture} textureGPU - The GPU texture object.
  48026. * @param {Object} textureDescriptorGPU - The texture descriptor.
  48027. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  48028. */
  48029. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  48030. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  48031. }
  48032. /**
  48033. * Flip the contents of the given GPU texture along its vertical axis.
  48034. *
  48035. * @private
  48036. * @param {GPUTexture} textureGPU - The GPU texture object.
  48037. * @param {Object} textureDescriptorGPU - The texture descriptor.
  48038. * @param {number} [originDepth=0] - The origin depth.
  48039. */
  48040. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  48041. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  48042. }
  48043. /**
  48044. * Uploads texture buffer data to the GPU memory.
  48045. *
  48046. * @private
  48047. * @param {Object} image - An object defining the image buffer data.
  48048. * @param {GPUTexture} textureGPU - The GPU texture.
  48049. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48050. * @param {number} originDepth - The origin depth.
  48051. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  48052. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  48053. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  48054. */
  48055. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  48056. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  48057. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  48058. const device = this.backend.device;
  48059. const data = image.data;
  48060. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  48061. const bytesPerRow = image.width * bytesPerTexel;
  48062. device.queue.writeTexture(
  48063. {
  48064. texture: textureGPU,
  48065. mipLevel: mipLevel,
  48066. origin: { x: 0, y: 0, z: originDepth }
  48067. },
  48068. data,
  48069. {
  48070. offset: image.width * image.height * bytesPerTexel * depth,
  48071. bytesPerRow
  48072. },
  48073. {
  48074. width: image.width,
  48075. height: image.height,
  48076. depthOrArrayLayers: 1
  48077. } );
  48078. if ( flipY === true ) {
  48079. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  48080. }
  48081. }
  48082. /**
  48083. * Uploads compressed texture data to the GPU memory.
  48084. *
  48085. * @private
  48086. * @param {Array<Object>} mipmaps - An array with mipmap data.
  48087. * @param {GPUTexture} textureGPU - The GPU texture.
  48088. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48089. */
  48090. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  48091. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  48092. const device = this.backend.device;
  48093. const blockData = this._getBlockData( textureDescriptorGPU.format );
  48094. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  48095. for ( let i = 0; i < mipmaps.length; i ++ ) {
  48096. const mipmap = mipmaps[ i ];
  48097. const width = mipmap.width;
  48098. const height = mipmap.height;
  48099. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  48100. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  48101. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  48102. for ( let j = 0; j < depth; j ++ ) {
  48103. device.queue.writeTexture(
  48104. {
  48105. texture: textureGPU,
  48106. mipLevel: i,
  48107. origin: { x: 0, y: 0, z: j }
  48108. },
  48109. mipmap.data,
  48110. {
  48111. offset: j * bytesPerImage,
  48112. bytesPerRow,
  48113. rowsPerImage: Math.ceil( height / blockData.height )
  48114. },
  48115. {
  48116. width: Math.ceil( width / blockData.width ) * blockData.width,
  48117. height: Math.ceil( height / blockData.height ) * blockData.height,
  48118. depthOrArrayLayers: 1
  48119. }
  48120. );
  48121. }
  48122. }
  48123. }
  48124. /**
  48125. * This method is only relevant for compressed texture formats. It returns a block
  48126. * data descriptor for the given GPU compressed texture format.
  48127. *
  48128. * @private
  48129. * @param {string} format - The GPU compressed texture format.
  48130. * @return {Object} The block data descriptor.
  48131. */
  48132. _getBlockData( format ) {
  48133. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  48134. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  48135. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  48136. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  48137. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  48138. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  48139. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  48140. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  48141. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  48142. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  48143. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  48144. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  48145. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  48146. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  48147. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  48148. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  48149. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  48150. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  48151. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  48152. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  48153. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  48154. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  48155. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  48156. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  48157. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  48158. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  48159. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  48160. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  48161. }
  48162. /**
  48163. * Converts the three.js uv wrapping constants to GPU address mode constants.
  48164. *
  48165. * @private
  48166. * @param {number} value - The three.js constant defining a uv wrapping mode.
  48167. * @return {string} The GPU address mode.
  48168. */
  48169. _convertAddressMode( value ) {
  48170. let addressMode = GPUAddressMode.ClampToEdge;
  48171. if ( value === RepeatWrapping ) {
  48172. addressMode = GPUAddressMode.Repeat;
  48173. } else if ( value === MirroredRepeatWrapping ) {
  48174. addressMode = GPUAddressMode.MirrorRepeat;
  48175. }
  48176. return addressMode;
  48177. }
  48178. /**
  48179. * Converts the three.js filter constants to GPU filter constants.
  48180. *
  48181. * @private
  48182. * @param {number} value - The three.js constant defining a filter mode.
  48183. * @return {string} The GPU filter mode.
  48184. */
  48185. _convertFilterMode( value ) {
  48186. let filterMode = GPUFilterMode.Linear;
  48187. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  48188. filterMode = GPUFilterMode.Nearest;
  48189. }
  48190. return filterMode;
  48191. }
  48192. /**
  48193. * Returns the bytes-per-texel value for the given GPU texture format.
  48194. *
  48195. * @private
  48196. * @param {string} format - The GPU texture format.
  48197. * @return {number} The bytes-per-texel.
  48198. */
  48199. _getBytesPerTexel( format ) {
  48200. // 8-bit formats
  48201. if ( format === GPUTextureFormat.R8Unorm ||
  48202. format === GPUTextureFormat.R8Snorm ||
  48203. format === GPUTextureFormat.R8Uint ||
  48204. format === GPUTextureFormat.R8Sint ) return 1;
  48205. // 16-bit formats
  48206. if ( format === GPUTextureFormat.R16Uint ||
  48207. format === GPUTextureFormat.R16Sint ||
  48208. format === GPUTextureFormat.R16Float ||
  48209. format === GPUTextureFormat.RG8Unorm ||
  48210. format === GPUTextureFormat.RG8Snorm ||
  48211. format === GPUTextureFormat.RG8Uint ||
  48212. format === GPUTextureFormat.RG8Sint ) return 2;
  48213. // 32-bit formats
  48214. if ( format === GPUTextureFormat.R32Uint ||
  48215. format === GPUTextureFormat.R32Sint ||
  48216. format === GPUTextureFormat.R32Float ||
  48217. format === GPUTextureFormat.RG16Uint ||
  48218. format === GPUTextureFormat.RG16Sint ||
  48219. format === GPUTextureFormat.RG16Float ||
  48220. format === GPUTextureFormat.RGBA8Unorm ||
  48221. format === GPUTextureFormat.RGBA8UnormSRGB ||
  48222. format === GPUTextureFormat.RGBA8Snorm ||
  48223. format === GPUTextureFormat.RGBA8Uint ||
  48224. format === GPUTextureFormat.RGBA8Sint ||
  48225. format === GPUTextureFormat.BGRA8Unorm ||
  48226. format === GPUTextureFormat.BGRA8UnormSRGB ||
  48227. // Packed 32-bit formats
  48228. format === GPUTextureFormat.RGB9E5UFloat ||
  48229. format === GPUTextureFormat.RGB10A2Unorm ||
  48230. format === GPUTextureFormat.RG11B10UFloat ||
  48231. format === GPUTextureFormat.Depth32Float ||
  48232. format === GPUTextureFormat.Depth24Plus ||
  48233. format === GPUTextureFormat.Depth24PlusStencil8 ||
  48234. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  48235. // 64-bit formats
  48236. if ( format === GPUTextureFormat.RG32Uint ||
  48237. format === GPUTextureFormat.RG32Sint ||
  48238. format === GPUTextureFormat.RG32Float ||
  48239. format === GPUTextureFormat.RGBA16Uint ||
  48240. format === GPUTextureFormat.RGBA16Sint ||
  48241. format === GPUTextureFormat.RGBA16Float ) return 8;
  48242. // 128-bit formats
  48243. if ( format === GPUTextureFormat.RGBA32Uint ||
  48244. format === GPUTextureFormat.RGBA32Sint ||
  48245. format === GPUTextureFormat.RGBA32Float ) return 16;
  48246. }
  48247. /**
  48248. * Returns the corresponding typed array type for the given GPU texture format.
  48249. *
  48250. * @private
  48251. * @param {string} format - The GPU texture format.
  48252. * @return {TypedArray.constructor} The typed array type.
  48253. */
  48254. _getTypedArrayType( format ) {
  48255. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  48256. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  48257. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  48258. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  48259. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  48260. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  48261. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  48262. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  48263. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  48264. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  48265. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  48266. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  48267. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  48268. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  48269. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  48270. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  48271. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  48272. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  48273. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  48274. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  48275. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  48276. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  48277. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  48278. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  48279. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  48280. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  48281. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  48282. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  48283. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  48284. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  48285. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  48286. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  48287. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  48288. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  48289. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  48290. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  48291. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  48292. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  48293. }
  48294. /**
  48295. * Returns the GPU dimensions for the given texture.
  48296. *
  48297. * @private
  48298. * @param {Texture} texture - The texture.
  48299. * @return {string} The GPU dimension.
  48300. */
  48301. _getDimension( texture ) {
  48302. let dimension;
  48303. if ( texture.is3DTexture || texture.isData3DTexture ) {
  48304. dimension = GPUTextureDimension.ThreeD;
  48305. } else {
  48306. dimension = GPUTextureDimension.TwoD;
  48307. }
  48308. return dimension;
  48309. }
  48310. }
  48311. /**
  48312. * Returns the GPU format for the given texture.
  48313. *
  48314. * @param {Texture} texture - The texture.
  48315. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  48316. * It is not necessary to apply the device for most formats.
  48317. * @return {string} The GPU format.
  48318. */
  48319. function getFormat( texture, device = null ) {
  48320. const format = texture.format;
  48321. const type = texture.type;
  48322. const colorSpace = texture.colorSpace;
  48323. const transfer = ColorManagement.getTransfer( colorSpace );
  48324. let formatGPU;
  48325. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  48326. switch ( format ) {
  48327. case RGBA_S3TC_DXT1_Format:
  48328. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  48329. break;
  48330. case RGBA_S3TC_DXT3_Format:
  48331. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  48332. break;
  48333. case RGBA_S3TC_DXT5_Format:
  48334. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  48335. break;
  48336. case RGB_ETC2_Format:
  48337. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  48338. break;
  48339. case RGBA_ETC2_EAC_Format:
  48340. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  48341. break;
  48342. case RGBA_ASTC_4x4_Format:
  48343. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  48344. break;
  48345. case RGBA_ASTC_5x4_Format:
  48346. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  48347. break;
  48348. case RGBA_ASTC_5x5_Format:
  48349. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  48350. break;
  48351. case RGBA_ASTC_6x5_Format:
  48352. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  48353. break;
  48354. case RGBA_ASTC_6x6_Format:
  48355. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  48356. break;
  48357. case RGBA_ASTC_8x5_Format:
  48358. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  48359. break;
  48360. case RGBA_ASTC_8x6_Format:
  48361. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  48362. break;
  48363. case RGBA_ASTC_8x8_Format:
  48364. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  48365. break;
  48366. case RGBA_ASTC_10x5_Format:
  48367. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  48368. break;
  48369. case RGBA_ASTC_10x6_Format:
  48370. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  48371. break;
  48372. case RGBA_ASTC_10x8_Format:
  48373. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  48374. break;
  48375. case RGBA_ASTC_10x10_Format:
  48376. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  48377. break;
  48378. case RGBA_ASTC_12x10_Format:
  48379. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  48380. break;
  48381. case RGBA_ASTC_12x12_Format:
  48382. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  48383. break;
  48384. case RGBAFormat:
  48385. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  48386. break;
  48387. default:
  48388. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  48389. }
  48390. } else {
  48391. switch ( format ) {
  48392. case RGBAFormat:
  48393. switch ( type ) {
  48394. case ByteType:
  48395. formatGPU = GPUTextureFormat.RGBA8Snorm;
  48396. break;
  48397. case ShortType:
  48398. formatGPU = GPUTextureFormat.RGBA16Sint;
  48399. break;
  48400. case UnsignedShortType:
  48401. formatGPU = GPUTextureFormat.RGBA16Uint;
  48402. break;
  48403. case UnsignedIntType:
  48404. formatGPU = GPUTextureFormat.RGBA32Uint;
  48405. break;
  48406. case IntType:
  48407. formatGPU = GPUTextureFormat.RGBA32Sint;
  48408. break;
  48409. case UnsignedByteType:
  48410. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  48411. break;
  48412. case HalfFloatType:
  48413. formatGPU = GPUTextureFormat.RGBA16Float;
  48414. break;
  48415. case FloatType:
  48416. formatGPU = GPUTextureFormat.RGBA32Float;
  48417. break;
  48418. default:
  48419. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  48420. }
  48421. break;
  48422. case RGBFormat:
  48423. switch ( type ) {
  48424. case UnsignedInt5999Type:
  48425. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  48426. break;
  48427. case UnsignedInt101111Type:
  48428. formatGPU = GPUTextureFormat.RG11B10UFloat;
  48429. break;
  48430. default:
  48431. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  48432. }
  48433. break;
  48434. case RedFormat:
  48435. switch ( type ) {
  48436. case ByteType:
  48437. formatGPU = GPUTextureFormat.R8Snorm;
  48438. break;
  48439. case ShortType:
  48440. formatGPU = GPUTextureFormat.R16Sint;
  48441. break;
  48442. case UnsignedShortType:
  48443. formatGPU = GPUTextureFormat.R16Uint;
  48444. break;
  48445. case UnsignedIntType:
  48446. formatGPU = GPUTextureFormat.R32Uint;
  48447. break;
  48448. case IntType:
  48449. formatGPU = GPUTextureFormat.R32Sint;
  48450. break;
  48451. case UnsignedByteType:
  48452. formatGPU = GPUTextureFormat.R8Unorm;
  48453. break;
  48454. case HalfFloatType:
  48455. formatGPU = GPUTextureFormat.R16Float;
  48456. break;
  48457. case FloatType:
  48458. formatGPU = GPUTextureFormat.R32Float;
  48459. break;
  48460. default:
  48461. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  48462. }
  48463. break;
  48464. case RGFormat:
  48465. switch ( type ) {
  48466. case ByteType:
  48467. formatGPU = GPUTextureFormat.RG8Snorm;
  48468. break;
  48469. case ShortType:
  48470. formatGPU = GPUTextureFormat.RG16Sint;
  48471. break;
  48472. case UnsignedShortType:
  48473. formatGPU = GPUTextureFormat.RG16Uint;
  48474. break;
  48475. case UnsignedIntType:
  48476. formatGPU = GPUTextureFormat.RG32Uint;
  48477. break;
  48478. case IntType:
  48479. formatGPU = GPUTextureFormat.RG32Sint;
  48480. break;
  48481. case UnsignedByteType:
  48482. formatGPU = GPUTextureFormat.RG8Unorm;
  48483. break;
  48484. case HalfFloatType:
  48485. formatGPU = GPUTextureFormat.RG16Float;
  48486. break;
  48487. case FloatType:
  48488. formatGPU = GPUTextureFormat.RG32Float;
  48489. break;
  48490. default:
  48491. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  48492. }
  48493. break;
  48494. case DepthFormat:
  48495. switch ( type ) {
  48496. case UnsignedShortType:
  48497. formatGPU = GPUTextureFormat.Depth16Unorm;
  48498. break;
  48499. case UnsignedIntType:
  48500. formatGPU = GPUTextureFormat.Depth24Plus;
  48501. break;
  48502. case FloatType:
  48503. formatGPU = GPUTextureFormat.Depth32Float;
  48504. break;
  48505. default:
  48506. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  48507. }
  48508. break;
  48509. case DepthStencilFormat:
  48510. switch ( type ) {
  48511. case UnsignedInt248Type:
  48512. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  48513. break;
  48514. case FloatType:
  48515. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  48516. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  48517. }
  48518. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  48519. break;
  48520. default:
  48521. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  48522. }
  48523. break;
  48524. case RedIntegerFormat:
  48525. switch ( type ) {
  48526. case IntType:
  48527. formatGPU = GPUTextureFormat.R32Sint;
  48528. break;
  48529. case UnsignedIntType:
  48530. formatGPU = GPUTextureFormat.R32Uint;
  48531. break;
  48532. default:
  48533. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  48534. }
  48535. break;
  48536. case RGIntegerFormat:
  48537. switch ( type ) {
  48538. case IntType:
  48539. formatGPU = GPUTextureFormat.RG32Sint;
  48540. break;
  48541. case UnsignedIntType:
  48542. formatGPU = GPUTextureFormat.RG32Uint;
  48543. break;
  48544. default:
  48545. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  48546. }
  48547. break;
  48548. case RGBAIntegerFormat:
  48549. switch ( type ) {
  48550. case IntType:
  48551. formatGPU = GPUTextureFormat.RGBA32Sint;
  48552. break;
  48553. case UnsignedIntType:
  48554. formatGPU = GPUTextureFormat.RGBA32Uint;
  48555. break;
  48556. default:
  48557. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  48558. }
  48559. break;
  48560. default:
  48561. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  48562. }
  48563. }
  48564. return formatGPU;
  48565. }
  48566. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  48567. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  48568. const wgslTypeLib$1 = {
  48569. 'f32': 'float',
  48570. 'i32': 'int',
  48571. 'u32': 'uint',
  48572. 'bool': 'bool',
  48573. 'vec2<f32>': 'vec2',
  48574. 'vec2<i32>': 'ivec2',
  48575. 'vec2<u32>': 'uvec2',
  48576. 'vec2<bool>': 'bvec2',
  48577. 'vec2f': 'vec2',
  48578. 'vec2i': 'ivec2',
  48579. 'vec2u': 'uvec2',
  48580. 'vec2b': 'bvec2',
  48581. 'vec3<f32>': 'vec3',
  48582. 'vec3<i32>': 'ivec3',
  48583. 'vec3<u32>': 'uvec3',
  48584. 'vec3<bool>': 'bvec3',
  48585. 'vec3f': 'vec3',
  48586. 'vec3i': 'ivec3',
  48587. 'vec3u': 'uvec3',
  48588. 'vec3b': 'bvec3',
  48589. 'vec4<f32>': 'vec4',
  48590. 'vec4<i32>': 'ivec4',
  48591. 'vec4<u32>': 'uvec4',
  48592. 'vec4<bool>': 'bvec4',
  48593. 'vec4f': 'vec4',
  48594. 'vec4i': 'ivec4',
  48595. 'vec4u': 'uvec4',
  48596. 'vec4b': 'bvec4',
  48597. 'mat2x2<f32>': 'mat2',
  48598. 'mat2x2f': 'mat2',
  48599. 'mat3x3<f32>': 'mat3',
  48600. 'mat3x3f': 'mat3',
  48601. 'mat4x4<f32>': 'mat4',
  48602. 'mat4x4f': 'mat4',
  48603. 'sampler': 'sampler',
  48604. 'texture_1d': 'texture',
  48605. 'texture_2d': 'texture',
  48606. 'texture_2d_array': 'texture',
  48607. 'texture_multisampled_2d': 'cubeTexture',
  48608. 'texture_depth_2d': 'depthTexture',
  48609. 'texture_depth_2d_array': 'depthTexture',
  48610. 'texture_depth_multisampled_2d': 'depthTexture',
  48611. 'texture_depth_cube': 'depthTexture',
  48612. 'texture_depth_cube_array': 'depthTexture',
  48613. 'texture_3d': 'texture3D',
  48614. 'texture_cube': 'cubeTexture',
  48615. 'texture_cube_array': 'cubeTexture',
  48616. 'texture_storage_1d': 'storageTexture',
  48617. 'texture_storage_2d': 'storageTexture',
  48618. 'texture_storage_2d_array': 'storageTexture',
  48619. 'texture_storage_3d': 'storageTexture'
  48620. };
  48621. const parse = ( source ) => {
  48622. source = source.trim();
  48623. const declaration = source.match( declarationRegexp );
  48624. if ( declaration !== null && declaration.length === 4 ) {
  48625. const inputsCode = declaration[ 2 ];
  48626. const propsMatches = [];
  48627. let match = null;
  48628. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  48629. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  48630. }
  48631. // Process matches to correctly pair names and types
  48632. const inputs = [];
  48633. for ( let i = 0; i < propsMatches.length; i ++ ) {
  48634. const { name, type } = propsMatches[ i ];
  48635. let resolvedType = type;
  48636. if ( resolvedType.startsWith( 'ptr' ) ) {
  48637. resolvedType = 'pointer';
  48638. } else {
  48639. if ( resolvedType.startsWith( 'texture' ) ) {
  48640. resolvedType = type.split( '<' )[ 0 ];
  48641. }
  48642. resolvedType = wgslTypeLib$1[ resolvedType ];
  48643. }
  48644. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  48645. }
  48646. const blockCode = source.substring( declaration[ 0 ].length );
  48647. const outputType = declaration[ 3 ] || 'void';
  48648. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  48649. const type = wgslTypeLib$1[ outputType ] || outputType;
  48650. return {
  48651. type,
  48652. inputs,
  48653. name,
  48654. inputsCode,
  48655. blockCode,
  48656. outputType
  48657. };
  48658. } else {
  48659. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  48660. }
  48661. };
  48662. /**
  48663. * This class represents a WSL node function.
  48664. *
  48665. * @augments NodeFunction
  48666. */
  48667. class WGSLNodeFunction extends NodeFunction {
  48668. /**
  48669. * Constructs a new WGSL node function.
  48670. *
  48671. * @param {string} source - The WGSL source.
  48672. */
  48673. constructor( source ) {
  48674. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  48675. super( type, inputs, name );
  48676. this.inputsCode = inputsCode;
  48677. this.blockCode = blockCode;
  48678. this.outputType = outputType;
  48679. }
  48680. /**
  48681. * This method returns the WGSL code of the node function.
  48682. *
  48683. * @param {string} [name=this.name] - The function's name.
  48684. * @return {string} The shader code.
  48685. */
  48686. getCode( name = this.name ) {
  48687. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  48688. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  48689. }
  48690. }
  48691. /**
  48692. * A WGSL node parser.
  48693. *
  48694. * @augments NodeParser
  48695. */
  48696. class WGSLNodeParser extends NodeParser {
  48697. /**
  48698. * The method parses the given WGSL code an returns a node function.
  48699. *
  48700. * @param {string} source - The WGSL code.
  48701. * @return {WGSLNodeFunction} A node function.
  48702. */
  48703. parseFunction( source ) {
  48704. return new WGSLNodeFunction( source );
  48705. }
  48706. }
  48707. // GPUShaderStage is not defined in browsers not supporting WebGPU
  48708. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  48709. const accessNames = {
  48710. [ NodeAccess.READ_ONLY ]: 'read',
  48711. [ NodeAccess.WRITE_ONLY ]: 'write',
  48712. [ NodeAccess.READ_WRITE ]: 'read_write'
  48713. };
  48714. const wrapNames = {
  48715. [ RepeatWrapping ]: 'repeat',
  48716. [ ClampToEdgeWrapping ]: 'clamp',
  48717. [ MirroredRepeatWrapping ]: 'mirror'
  48718. };
  48719. const gpuShaderStageLib = {
  48720. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  48721. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  48722. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  48723. };
  48724. const supports = {
  48725. instance: true,
  48726. swizzleAssign: false,
  48727. storageBuffer: true
  48728. };
  48729. const wgslFnOpLib = {
  48730. '^^': 'tsl_xor'
  48731. };
  48732. const wgslTypeLib = {
  48733. float: 'f32',
  48734. int: 'i32',
  48735. uint: 'u32',
  48736. bool: 'bool',
  48737. color: 'vec3<f32>',
  48738. vec2: 'vec2<f32>',
  48739. ivec2: 'vec2<i32>',
  48740. uvec2: 'vec2<u32>',
  48741. bvec2: 'vec2<bool>',
  48742. vec3: 'vec3<f32>',
  48743. ivec3: 'vec3<i32>',
  48744. uvec3: 'vec3<u32>',
  48745. bvec3: 'vec3<bool>',
  48746. vec4: 'vec4<f32>',
  48747. ivec4: 'vec4<i32>',
  48748. uvec4: 'vec4<u32>',
  48749. bvec4: 'vec4<bool>',
  48750. mat2: 'mat2x2<f32>',
  48751. mat3: 'mat3x3<f32>',
  48752. mat4: 'mat4x4<f32>'
  48753. };
  48754. const wgslCodeCache = {};
  48755. const wgslPolyfill = {
  48756. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  48757. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  48758. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  48759. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  48760. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  48761. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  48762. 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 ); }' ),
  48763. 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 ); }' ),
  48764. 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 ); }' ),
  48765. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  48766. 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 ); }' ),
  48767. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  48768. biquadraticTexture: new CodeNode( /* wgsl */`
  48769. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  48770. let res = vec2f( iRes );
  48771. let uvScaled = coord * res;
  48772. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  48773. // https://www.shadertoy.com/view/WtyXRy
  48774. let uv = uvWrapping - 0.5;
  48775. let iuv = floor( uv );
  48776. let f = fract( uv );
  48777. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  48778. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  48779. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  48780. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  48781. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  48782. }
  48783. ` )
  48784. };
  48785. const wgslMethods = {
  48786. dFdx: 'dpdx',
  48787. dFdy: '- dpdy',
  48788. mod_float: 'tsl_mod_float',
  48789. mod_vec2: 'tsl_mod_vec2',
  48790. mod_vec3: 'tsl_mod_vec3',
  48791. mod_vec4: 'tsl_mod_vec4',
  48792. equals_bool: 'tsl_equals_bool',
  48793. equals_bvec2: 'tsl_equals_bvec2',
  48794. equals_bvec3: 'tsl_equals_bvec3',
  48795. equals_bvec4: 'tsl_equals_bvec4',
  48796. inversesqrt: 'inverseSqrt',
  48797. bitcast: 'bitcast<f32>'
  48798. };
  48799. // WebGPU issue: does not support pow() with negative base on Windows
  48800. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  48801. 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 ); }' );
  48802. 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 ] );
  48803. 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 ] );
  48804. 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 ] );
  48805. wgslMethods.pow_float = 'tsl_pow_float';
  48806. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  48807. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  48808. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  48809. }
  48810. //
  48811. let diagnostics = '';
  48812. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  48813. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  48814. }
  48815. /**
  48816. * A node builder targeting WGSL.
  48817. *
  48818. * This module generates WGSL shader code from node materials and also
  48819. * generates the respective bindings and vertex buffer definitions. These
  48820. * data are later used by the renderer to create render and compute pipelines
  48821. * for render objects.
  48822. *
  48823. * @augments NodeBuilder
  48824. */
  48825. class WGSLNodeBuilder extends NodeBuilder {
  48826. /**
  48827. * Constructs a new WGSL node builder renderer.
  48828. *
  48829. * @param {Object3D} object - The 3D object.
  48830. * @param {Renderer} renderer - The renderer.
  48831. */
  48832. constructor( object, renderer ) {
  48833. super( object, renderer, new WGSLNodeParser() );
  48834. /**
  48835. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  48836. * another dictionary which manages UBOs per group ('render','frame','object').
  48837. *
  48838. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  48839. */
  48840. this.uniformGroups = {};
  48841. /**
  48842. * A dictionary that holds for each shader stage a Map of builtins.
  48843. *
  48844. * @type {Object<string,Map<string,Object>>}
  48845. */
  48846. this.builtins = {};
  48847. /**
  48848. * A dictionary that holds for each shader stage a Set of directives.
  48849. *
  48850. * @type {Object<string,Set<string>>}
  48851. */
  48852. this.directives = {};
  48853. /**
  48854. * A map for managing scope arrays. Only relevant for when using
  48855. * {@link WorkgroupInfoNode} in context of compute shaders.
  48856. *
  48857. * @type {Map<string,Object>}
  48858. */
  48859. this.scopedArrays = new Map();
  48860. }
  48861. /**
  48862. * Generates the WGSL snippet for sampled textures.
  48863. *
  48864. * @private
  48865. * @param {Texture} texture - The texture.
  48866. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48867. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48868. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48869. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48870. * @return {string} The WGSL snippet.
  48871. */
  48872. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48873. if ( shaderStage === 'fragment' ) {
  48874. if ( depthSnippet ) {
  48875. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  48876. } else {
  48877. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  48878. }
  48879. } else {
  48880. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  48881. }
  48882. }
  48883. /**
  48884. * Generates the WGSL snippet when sampling textures with explicit mip level.
  48885. *
  48886. * @private
  48887. * @param {Texture} texture - The texture.
  48888. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48889. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48890. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48891. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48892. * @return {string} The WGSL snippet.
  48893. */
  48894. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  48895. if ( this.isUnfilterable( texture ) === false ) {
  48896. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  48897. } else if ( this.isFilteredTexture( texture ) ) {
  48898. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  48899. } else {
  48900. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  48901. }
  48902. }
  48903. /**
  48904. * Generates a wrap function used in context of textures.
  48905. *
  48906. * @param {Texture} texture - The texture to generate the function for.
  48907. * @return {string} The name of the generated function.
  48908. */
  48909. generateWrapFunction( texture ) {
  48910. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  48911. let nodeCode = wgslCodeCache[ functionName ];
  48912. if ( nodeCode === undefined ) {
  48913. const includes = [];
  48914. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  48915. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  48916. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  48917. const addWrapSnippet = ( wrap, axis ) => {
  48918. if ( wrap === RepeatWrapping ) {
  48919. includes.push( wgslPolyfill.repeatWrapping_float );
  48920. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  48921. } else if ( wrap === ClampToEdgeWrapping ) {
  48922. includes.push( wgslPolyfill.clampWrapping_float );
  48923. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  48924. } else if ( wrap === MirroredRepeatWrapping ) {
  48925. includes.push( wgslPolyfill.mirrorWrapping_float );
  48926. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  48927. } else {
  48928. code += `\t\tcoord.${ axis }`;
  48929. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  48930. }
  48931. };
  48932. addWrapSnippet( texture.wrapS, 'x' );
  48933. code += ',\n';
  48934. addWrapSnippet( texture.wrapT, 'y' );
  48935. if ( texture.isData3DTexture ) {
  48936. code += ',\n';
  48937. addWrapSnippet( texture.wrapR, 'z' );
  48938. }
  48939. code += '\n\t);\n\n}\n';
  48940. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  48941. }
  48942. nodeCode.build( this );
  48943. return functionName;
  48944. }
  48945. /**
  48946. * Generates the array declaration string.
  48947. *
  48948. * @param {string} type - The type.
  48949. * @param {?number} [count] - The count.
  48950. * @return {string} The generated value as a shader string.
  48951. */
  48952. generateArrayDeclaration( type, count ) {
  48953. return `array< ${ this.getType( type ) }, ${ count } >`;
  48954. }
  48955. /**
  48956. * Generates a WGSL variable that holds the texture dimension of the given texture.
  48957. * It also returns information about the number of layers (elements) of an arrayed
  48958. * texture as well as the cube face count of cube textures.
  48959. *
  48960. * @param {Texture} texture - The texture to generate the function for.
  48961. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  48962. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48963. * @return {string} The name of the dimension variable.
  48964. */
  48965. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  48966. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  48967. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  48968. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  48969. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  48970. let textureDimensionsParams;
  48971. let dimensionType;
  48972. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  48973. const isMultisampled = primarySamples > 1;
  48974. if ( texture.isData3DTexture ) {
  48975. dimensionType = 'vec3<u32>';
  48976. } else {
  48977. // Regular 2D textures, depth textures, etc.
  48978. dimensionType = 'vec2<u32>';
  48979. }
  48980. // Build parameters string based on texture type and multisampling
  48981. if ( isMultisampled || texture.isStorageTexture ) {
  48982. textureDimensionsParams = textureProperty;
  48983. } else {
  48984. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  48985. }
  48986. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  48987. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  48988. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  48989. textureData.arrayLayerCount = new VarNode(
  48990. new ExpressionNode(
  48991. `textureNumLayers(${textureProperty})`,
  48992. 'u32'
  48993. )
  48994. );
  48995. }
  48996. // For cube textures, we know it's always 6 faces
  48997. if ( texture.isTextureCube ) {
  48998. textureData.cubeFaceCount = new VarNode(
  48999. new ExpressionNode( '6u', 'u32' )
  49000. );
  49001. }
  49002. }
  49003. return textureDimensionNode.build( this );
  49004. }
  49005. /**
  49006. * Generates the WGSL snippet for a manual filtered texture.
  49007. *
  49008. * @param {Texture} texture - The texture.
  49009. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49010. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49011. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49012. * @return {string} The WGSL snippet.
  49013. */
  49014. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  49015. this._include( 'biquadraticTexture' );
  49016. const wrapFunction = this.generateWrapFunction( texture );
  49017. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  49018. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  49019. }
  49020. /**
  49021. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  49022. * Since it's a lookup, no sampling or filtering is applied.
  49023. *
  49024. * @param {Texture} texture - The texture.
  49025. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49026. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49027. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49028. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49029. * @return {string} The WGSL snippet.
  49030. */
  49031. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  49032. const wrapFunction = this.generateWrapFunction( texture );
  49033. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  49034. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  49035. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  49036. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  49037. }
  49038. /**
  49039. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  49040. *
  49041. * @param {Texture} texture - The texture.
  49042. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49043. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49044. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49045. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49046. * @return {string} The WGSL snippet.
  49047. */
  49048. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  49049. let snippet;
  49050. if ( depthSnippet ) {
  49051. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  49052. } else {
  49053. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  49054. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  49055. snippet += '.x';
  49056. }
  49057. }
  49058. return snippet;
  49059. }
  49060. /**
  49061. * Generates the WGSL snippet that writes a single texel to a texture.
  49062. *
  49063. * @param {Texture} texture - The texture.
  49064. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49065. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49066. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49067. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  49068. * @return {string} The WGSL snippet.
  49069. */
  49070. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  49071. let snippet;
  49072. if ( depthSnippet ) {
  49073. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  49074. } else {
  49075. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  49076. }
  49077. return snippet;
  49078. }
  49079. /**
  49080. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  49081. *
  49082. * @param {Texture} texture - The texture.
  49083. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  49084. */
  49085. isSampleCompare( texture ) {
  49086. return texture.isDepthTexture === true && texture.compareFunction !== null;
  49087. }
  49088. /**
  49089. * Returns `true` if the given texture is unfilterable.
  49090. *
  49091. * @param {Texture} texture - The texture.
  49092. * @return {boolean} Whether the given texture is unfilterable or not.
  49093. */
  49094. isUnfilterable( texture ) {
  49095. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  49096. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  49097. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  49098. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  49099. }
  49100. /**
  49101. * Generates the WGSL snippet for sampling/loading the given texture.
  49102. *
  49103. * @param {Texture} texture - The texture.
  49104. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49105. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49106. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49107. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49108. * @return {string} The WGSL snippet.
  49109. */
  49110. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  49111. let snippet = null;
  49112. if ( this.isUnfilterable( texture ) ) {
  49113. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  49114. } else {
  49115. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  49116. }
  49117. return snippet;
  49118. }
  49119. /**
  49120. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  49121. *
  49122. * @param {Texture} texture - The texture.
  49123. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49124. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49125. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  49126. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49127. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49128. * @return {string} The WGSL snippet.
  49129. */
  49130. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  49131. if ( shaderStage === 'fragment' ) {
  49132. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  49133. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  49134. } else {
  49135. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  49136. }
  49137. }
  49138. /**
  49139. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  49140. * against a reference value.
  49141. *
  49142. * @param {Texture} texture - The texture.
  49143. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49144. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49145. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  49146. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49147. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49148. * @return {string} The WGSL snippet.
  49149. */
  49150. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  49151. if ( shaderStage === 'fragment' ) {
  49152. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  49153. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  49154. }
  49155. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  49156. } else {
  49157. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  49158. }
  49159. }
  49160. /**
  49161. * Generates the WGSL snippet when sampling textures with explicit mip level.
  49162. *
  49163. * @param {Texture} texture - The texture.
  49164. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49165. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49166. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49167. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49168. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49169. * @return {string} The WGSL snippet.
  49170. */
  49171. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  49172. if ( this.isUnfilterable( texture ) === false ) {
  49173. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  49174. } else if ( this.isFilteredTexture( texture ) ) {
  49175. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  49176. } else {
  49177. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  49178. }
  49179. }
  49180. /**
  49181. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  49182. *
  49183. * @param {Texture} texture - The texture.
  49184. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49185. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49186. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  49187. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49188. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49189. * @return {string} The WGSL snippet.
  49190. */
  49191. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  49192. if ( shaderStage === 'fragment' ) {
  49193. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  49194. } else {
  49195. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  49196. }
  49197. }
  49198. /**
  49199. * Returns a WGSL snippet that represents the property name of the given node.
  49200. *
  49201. * @param {Node} node - The node.
  49202. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49203. * @return {string} The property name.
  49204. */
  49205. getPropertyName( node, shaderStage = this.shaderStage ) {
  49206. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  49207. if ( shaderStage === 'vertex' ) {
  49208. return `varyings.${ node.name }`;
  49209. }
  49210. } else if ( node.isNodeUniform === true ) {
  49211. const name = node.name;
  49212. const type = node.type;
  49213. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  49214. return name;
  49215. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  49216. if ( this.isCustomStruct( node ) ) {
  49217. return name;
  49218. }
  49219. return name + '.value';
  49220. } else {
  49221. return node.groupNode.name + '.' + name;
  49222. }
  49223. }
  49224. return super.getPropertyName( node );
  49225. }
  49226. /**
  49227. * Returns the output struct name.
  49228. *
  49229. * @return {string} The name of the output struct.
  49230. */
  49231. getOutputStructName() {
  49232. return 'output';
  49233. }
  49234. /**
  49235. * Returns the native shader operator name for a given generic name.
  49236. *
  49237. * @param {string} op - The operator name to resolve.
  49238. * @return {?string} The resolved operator name.
  49239. */
  49240. getFunctionOperator( op ) {
  49241. const fnOp = wgslFnOpLib[ op ];
  49242. if ( fnOp !== undefined ) {
  49243. this._include( fnOp );
  49244. return fnOp;
  49245. }
  49246. return null;
  49247. }
  49248. /**
  49249. * Returns the node access for the given node and shader stage.
  49250. *
  49251. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  49252. * @param {string} shaderStage - The shader stage.
  49253. * @return {string} The node access.
  49254. */
  49255. getNodeAccess( node, shaderStage ) {
  49256. if ( shaderStage !== 'compute' ) {
  49257. if ( node.isAtomic === true ) {
  49258. console.warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  49259. return NodeAccess.READ_WRITE;
  49260. }
  49261. return NodeAccess.READ_ONLY;
  49262. }
  49263. return node.access;
  49264. }
  49265. /**
  49266. * Returns A WGSL snippet representing the storage access.
  49267. *
  49268. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  49269. * @param {string} shaderStage - The shader stage.
  49270. * @return {string} The WGSL snippet representing the storage access.
  49271. */
  49272. getStorageAccess( node, shaderStage ) {
  49273. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  49274. }
  49275. /**
  49276. * This method is one of the more important ones since it's responsible
  49277. * for generating a matching binding instance for the given uniform node.
  49278. *
  49279. * These bindings are later used in the renderer to create bind groups
  49280. * and layouts.
  49281. *
  49282. * @param {UniformNode} node - The uniform node.
  49283. * @param {string} type - The node data type.
  49284. * @param {string} shaderStage - The shader stage.
  49285. * @param {?string} [name=null] - An optional uniform name.
  49286. * @return {NodeUniform} The node uniform object.
  49287. */
  49288. getUniformFromNode( node, type, shaderStage, name = null ) {
  49289. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  49290. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  49291. if ( nodeData.uniformGPU === undefined ) {
  49292. let uniformGPU;
  49293. const group = node.groupNode;
  49294. const groupName = group.name;
  49295. const bindings = this.getBindGroupArray( groupName, shaderStage );
  49296. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  49297. let texture = null;
  49298. const access = this.getNodeAccess( node, shaderStage );
  49299. if ( type === 'texture' || type === 'storageTexture' ) {
  49300. if ( node.value.is3DTexture === true ) {
  49301. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  49302. } else {
  49303. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  49304. }
  49305. } else if ( type === 'cubeTexture' ) {
  49306. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  49307. } else if ( type === 'texture3D' ) {
  49308. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  49309. }
  49310. texture.store = node.isStorageTextureNode === true;
  49311. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49312. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  49313. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  49314. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49315. bindings.push( sampler, texture );
  49316. uniformGPU = [ sampler, texture ];
  49317. } else {
  49318. bindings.push( texture );
  49319. uniformGPU = [ texture ];
  49320. }
  49321. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  49322. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  49323. const buffer = new bufferClass( node, group );
  49324. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49325. bindings.push( buffer );
  49326. uniformGPU = buffer;
  49327. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  49328. } else {
  49329. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  49330. let uniformsGroup = uniformsStage[ groupName ];
  49331. if ( uniformsGroup === undefined ) {
  49332. uniformsGroup = new NodeUniformsGroup( groupName, group );
  49333. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49334. uniformsStage[ groupName ] = uniformsGroup;
  49335. bindings.push( uniformsGroup );
  49336. }
  49337. uniformGPU = this.getNodeUniform( uniformNode, type );
  49338. uniformsGroup.addUniform( uniformGPU );
  49339. }
  49340. nodeData.uniformGPU = uniformGPU;
  49341. }
  49342. return uniformNode;
  49343. }
  49344. /**
  49345. * This method should be used whenever builtins are required in nodes.
  49346. * The internal builtins data structure will make sure builtins are
  49347. * defined in the WGSL source.
  49348. *
  49349. * @param {string} name - The builtin name.
  49350. * @param {string} property - The property name.
  49351. * @param {string} type - The node data type.
  49352. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49353. * @return {string} The property name.
  49354. */
  49355. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  49356. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  49357. if ( map.has( name ) === false ) {
  49358. map.set( name, {
  49359. name,
  49360. property,
  49361. type
  49362. } );
  49363. }
  49364. return property;
  49365. }
  49366. /**
  49367. * Returns `true` if the given builtin is defined in the given shader stage.
  49368. *
  49369. * @param {string} name - The builtin name.
  49370. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49371. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  49372. */
  49373. hasBuiltin( name, shaderStage = this.shaderStage ) {
  49374. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  49375. }
  49376. /**
  49377. * Returns the vertex index builtin.
  49378. *
  49379. * @return {string} The vertex index.
  49380. */
  49381. getVertexIndex() {
  49382. if ( this.shaderStage === 'vertex' ) {
  49383. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  49384. }
  49385. return 'vertexIndex';
  49386. }
  49387. /**
  49388. * Builds the given shader node.
  49389. *
  49390. * @param {ShaderNodeInternal} shaderNode - The shader node.
  49391. * @return {string} The WGSL function code.
  49392. */
  49393. buildFunctionCode( shaderNode ) {
  49394. const layout = shaderNode.layout;
  49395. const flowData = this.flowShaderNode( shaderNode );
  49396. const parameters = [];
  49397. for ( const input of layout.inputs ) {
  49398. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  49399. }
  49400. //
  49401. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  49402. ${ flowData.vars }
  49403. ${ flowData.code }
  49404. `;
  49405. if ( flowData.result ) {
  49406. code += `\treturn ${ flowData.result };\n`;
  49407. }
  49408. code += '\n}\n';
  49409. //
  49410. return code;
  49411. }
  49412. /**
  49413. * Returns the instance index builtin.
  49414. *
  49415. * @return {string} The instance index.
  49416. */
  49417. getInstanceIndex() {
  49418. if ( this.shaderStage === 'vertex' ) {
  49419. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  49420. }
  49421. return 'instanceIndex';
  49422. }
  49423. /**
  49424. * Returns the invocation local index builtin.
  49425. *
  49426. * @return {string} The invocation local index.
  49427. */
  49428. getInvocationLocalIndex() {
  49429. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  49430. }
  49431. /**
  49432. * Returns the subgroup size builtin.
  49433. *
  49434. * @return {string} The subgroup size.
  49435. */
  49436. getSubgroupSize() {
  49437. this.enableSubGroups();
  49438. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  49439. }
  49440. /**
  49441. * Returns the invocation subgroup index builtin.
  49442. *
  49443. * @return {string} The invocation subgroup index.
  49444. */
  49445. getInvocationSubgroupIndex() {
  49446. this.enableSubGroups();
  49447. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  49448. }
  49449. /**
  49450. * Returns the subgroup index builtin.
  49451. *
  49452. * @return {string} The subgroup index.
  49453. */
  49454. getSubgroupIndex() {
  49455. this.enableSubGroups();
  49456. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  49457. }
  49458. /**
  49459. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  49460. *
  49461. * @return {null} Null.
  49462. */
  49463. getDrawIndex() {
  49464. return null;
  49465. }
  49466. /**
  49467. * Returns the front facing builtin.
  49468. *
  49469. * @return {string} The front facing builtin.
  49470. */
  49471. getFrontFacing() {
  49472. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  49473. }
  49474. /**
  49475. * Returns the frag coord builtin.
  49476. *
  49477. * @return {string} The frag coord builtin.
  49478. */
  49479. getFragCoord() {
  49480. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  49481. }
  49482. /**
  49483. * Returns the frag depth builtin.
  49484. *
  49485. * @return {string} The frag depth builtin.
  49486. */
  49487. getFragDepth() {
  49488. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  49489. }
  49490. /**
  49491. * Returns the clip distances builtin.
  49492. *
  49493. * @return {string} The clip distances builtin.
  49494. */
  49495. getClipDistance() {
  49496. return 'varyings.hw_clip_distances';
  49497. }
  49498. /**
  49499. * Whether to flip texture data along its vertical axis or not.
  49500. *
  49501. * @return {boolean} Returns always `false` in context of WGSL.
  49502. */
  49503. isFlipY() {
  49504. return false;
  49505. }
  49506. /**
  49507. * Enables the given directive for the given shader stage.
  49508. *
  49509. * @param {string} name - The directive name.
  49510. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  49511. */
  49512. enableDirective( name, shaderStage = this.shaderStage ) {
  49513. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  49514. stage.add( name );
  49515. }
  49516. /**
  49517. * Returns the directives of the given shader stage as a WGSL string.
  49518. *
  49519. * @param {string} shaderStage - The shader stage.
  49520. * @return {string} A WGSL snippet that enables the directives of the given stage.
  49521. */
  49522. getDirectives( shaderStage ) {
  49523. const snippets = [];
  49524. const directives = this.directives[ shaderStage ];
  49525. if ( directives !== undefined ) {
  49526. for ( const directive of directives ) {
  49527. snippets.push( `enable ${directive};` );
  49528. }
  49529. }
  49530. return snippets.join( '\n' );
  49531. }
  49532. /**
  49533. * Enables the 'subgroups' directive.
  49534. */
  49535. enableSubGroups() {
  49536. this.enableDirective( 'subgroups' );
  49537. }
  49538. /**
  49539. * Enables the 'subgroups-f16' directive.
  49540. */
  49541. enableSubgroupsF16() {
  49542. this.enableDirective( 'subgroups-f16' );
  49543. }
  49544. /**
  49545. * Enables the 'clip_distances' directive.
  49546. */
  49547. enableClipDistances() {
  49548. this.enableDirective( 'clip_distances' );
  49549. }
  49550. /**
  49551. * Enables the 'f16' directive.
  49552. */
  49553. enableShaderF16() {
  49554. this.enableDirective( 'f16' );
  49555. }
  49556. /**
  49557. * Enables the 'dual_source_blending' directive.
  49558. */
  49559. enableDualSourceBlending() {
  49560. this.enableDirective( 'dual_source_blending' );
  49561. }
  49562. /**
  49563. * Enables hardware clipping.
  49564. *
  49565. * @param {string} planeCount - The clipping plane count.
  49566. */
  49567. enableHardwareClipping( planeCount ) {
  49568. this.enableClipDistances();
  49569. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  49570. }
  49571. /**
  49572. * Returns the builtins of the given shader stage as a WGSL string.
  49573. *
  49574. * @param {string} shaderStage - The shader stage.
  49575. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  49576. */
  49577. getBuiltins( shaderStage ) {
  49578. const snippets = [];
  49579. const builtins = this.builtins[ shaderStage ];
  49580. if ( builtins !== undefined ) {
  49581. for ( const { name, property, type } of builtins.values() ) {
  49582. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  49583. }
  49584. }
  49585. return snippets.join( ',\n\t' );
  49586. }
  49587. /**
  49588. * This method should be used when a new scoped buffer is used in context of
  49589. * compute shaders. It adds the array to the internal data structure which is
  49590. * later used to generate the respective WGSL.
  49591. *
  49592. * @param {string} name - The array name.
  49593. * @param {string} scope - The scope.
  49594. * @param {string} bufferType - The buffer type.
  49595. * @param {string} bufferCount - The buffer count.
  49596. * @return {string} The array name.
  49597. */
  49598. getScopedArray( name, scope, bufferType, bufferCount ) {
  49599. if ( this.scopedArrays.has( name ) === false ) {
  49600. this.scopedArrays.set( name, {
  49601. name,
  49602. scope,
  49603. bufferType,
  49604. bufferCount
  49605. } );
  49606. }
  49607. return name;
  49608. }
  49609. /**
  49610. * Returns the scoped arrays of the given shader stage as a WGSL string.
  49611. *
  49612. * @param {string} shaderStage - The shader stage.
  49613. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  49614. * Returns `undefined` when used in the vertex or fragment stage.
  49615. */
  49616. getScopedArrays( shaderStage ) {
  49617. if ( shaderStage !== 'compute' ) {
  49618. return;
  49619. }
  49620. const snippets = [];
  49621. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  49622. const type = this.getType( bufferType );
  49623. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  49624. }
  49625. return snippets.join( '\n' );
  49626. }
  49627. /**
  49628. * Returns the shader attributes of the given shader stage as a WGSL string.
  49629. *
  49630. * @param {string} shaderStage - The shader stage.
  49631. * @return {string} The WGSL snippet that defines the shader attributes.
  49632. */
  49633. getAttributes( shaderStage ) {
  49634. const snippets = [];
  49635. if ( shaderStage === 'compute' ) {
  49636. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  49637. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  49638. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  49639. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  49640. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  49641. this.enableDirective( 'subgroups', shaderStage );
  49642. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  49643. }
  49644. }
  49645. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  49646. const builtins = this.getBuiltins( 'attribute' );
  49647. if ( builtins ) snippets.push( builtins );
  49648. const attributes = this.getAttributesArray();
  49649. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  49650. const attribute = attributes[ index ];
  49651. const name = attribute.name;
  49652. const type = this.getType( attribute.type );
  49653. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  49654. }
  49655. }
  49656. return snippets.join( ',\n\t' );
  49657. }
  49658. /**
  49659. * Returns the members of the given struct type node as a WGSL string.
  49660. *
  49661. * @param {StructTypeNode} struct - The struct type node.
  49662. * @return {string} The WGSL snippet that defines the struct members.
  49663. */
  49664. getStructMembers( struct ) {
  49665. const snippets = [];
  49666. for ( const member of struct.members ) {
  49667. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  49668. let type = this.getType( member.type );
  49669. if ( member.atomic ) {
  49670. type = 'atomic< ' + type + ' >';
  49671. }
  49672. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  49673. }
  49674. if ( struct.output ) {
  49675. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  49676. }
  49677. return snippets.join( ',\n' );
  49678. }
  49679. /**
  49680. * Returns the structs of the given shader stage as a WGSL string.
  49681. *
  49682. * @param {string} shaderStage - The shader stage.
  49683. * @return {string} The WGSL snippet that defines the structs.
  49684. */
  49685. getStructs( shaderStage ) {
  49686. let result = '';
  49687. const structs = this.structs[ shaderStage ];
  49688. if ( structs.length > 0 ) {
  49689. const snippets = [];
  49690. for ( const struct of structs ) {
  49691. let snippet = `struct ${ struct.name } {\n`;
  49692. snippet += this.getStructMembers( struct );
  49693. snippet += '\n};';
  49694. snippets.push( snippet );
  49695. }
  49696. result = '\n' + snippets.join( '\n\n' ) + '\n';
  49697. }
  49698. return result;
  49699. }
  49700. /**
  49701. * Returns a WGSL string representing a variable.
  49702. *
  49703. * @param {string} type - The variable's type.
  49704. * @param {string} name - The variable's name.
  49705. * @param {?number} [count=null] - The array length.
  49706. * @return {string} The WGSL snippet that defines a variable.
  49707. */
  49708. getVar( type, name, count = null ) {
  49709. let snippet = `var ${ name } : `;
  49710. if ( count !== null ) {
  49711. snippet += this.generateArrayDeclaration( type, count );
  49712. } else {
  49713. snippet += this.getType( type );
  49714. }
  49715. return snippet;
  49716. }
  49717. /**
  49718. * Returns the variables of the given shader stage as a WGSL string.
  49719. *
  49720. * @param {string} shaderStage - The shader stage.
  49721. * @return {string} The WGSL snippet that defines the variables.
  49722. */
  49723. getVars( shaderStage ) {
  49724. const snippets = [];
  49725. const vars = this.vars[ shaderStage ];
  49726. if ( vars !== undefined ) {
  49727. for ( const variable of vars ) {
  49728. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  49729. }
  49730. }
  49731. return `\n${ snippets.join( '\n' ) }\n`;
  49732. }
  49733. /**
  49734. * Returns the varyings of the given shader stage as a WGSL string.
  49735. *
  49736. * @param {string} shaderStage - The shader stage.
  49737. * @return {string} The WGSL snippet that defines the varyings.
  49738. */
  49739. getVaryings( shaderStage ) {
  49740. const snippets = [];
  49741. if ( shaderStage === 'vertex' ) {
  49742. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  49743. }
  49744. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  49745. const varyings = this.varyings;
  49746. const vars = this.vars[ shaderStage ];
  49747. for ( let index = 0; index < varyings.length; index ++ ) {
  49748. const varying = varyings[ index ];
  49749. if ( varying.needsInterpolation ) {
  49750. let attributesSnippet = `@location( ${index} )`;
  49751. if ( varying.interpolationType ) {
  49752. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  49753. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  49754. // Otherwise, optimize interpolation when sensible
  49755. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  49756. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  49757. }
  49758. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  49759. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  49760. vars.push( varying );
  49761. }
  49762. }
  49763. }
  49764. const builtins = this.getBuiltins( shaderStage );
  49765. if ( builtins ) snippets.push( builtins );
  49766. const code = snippets.join( ',\n\t' );
  49767. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  49768. }
  49769. isCustomStruct( nodeUniform ) {
  49770. const attribute = nodeUniform.value;
  49771. const bufferNode = nodeUniform.node;
  49772. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  49773. const isStructArray =
  49774. ( bufferNode.value && bufferNode.value.array ) &&
  49775. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  49776. return isAttributeStructType && ! isStructArray;
  49777. }
  49778. /**
  49779. * Returns the uniforms of the given shader stage as a WGSL string.
  49780. *
  49781. * @param {string} shaderStage - The shader stage.
  49782. * @return {string} The WGSL snippet that defines the uniforms.
  49783. */
  49784. getUniforms( shaderStage ) {
  49785. const uniforms = this.uniforms[ shaderStage ];
  49786. const bindingSnippets = [];
  49787. const bufferSnippets = [];
  49788. const structSnippets = [];
  49789. const uniformGroups = {};
  49790. for ( const uniform of uniforms ) {
  49791. const groupName = uniform.groupNode.name;
  49792. const uniformIndexes = this.bindingsIndexes[ groupName ];
  49793. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  49794. const texture = uniform.node.value;
  49795. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  49796. if ( this.isSampleCompare( texture ) ) {
  49797. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  49798. } else {
  49799. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  49800. }
  49801. }
  49802. let textureType;
  49803. let multisampled = '';
  49804. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  49805. if ( primarySamples > 1 ) {
  49806. multisampled = '_multisampled';
  49807. }
  49808. if ( texture.isCubeTexture === true ) {
  49809. textureType = 'texture_cube<f32>';
  49810. } else if ( texture.isDepthTexture === true ) {
  49811. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  49812. textureType = `texture${ multisampled }_2d<f32>`;
  49813. } else {
  49814. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  49815. }
  49816. } else if ( uniform.node.isStorageTextureNode === true ) {
  49817. const format = getFormat( texture );
  49818. const access = this.getStorageAccess( uniform.node, shaderStage );
  49819. const is3D = uniform.node.value.is3DTexture;
  49820. const isArrayTexture = uniform.node.value.isArrayTexture;
  49821. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  49822. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  49823. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  49824. textureType = 'texture_2d_array<f32>';
  49825. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  49826. textureType = 'texture_3d<f32>';
  49827. } else {
  49828. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  49829. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  49830. }
  49831. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  49832. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  49833. const bufferNode = uniform.node;
  49834. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  49835. const bufferCount = bufferNode.bufferCount;
  49836. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  49837. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  49838. if ( this.isCustomStruct( uniform ) ) {
  49839. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  49840. } else {
  49841. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  49842. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  49843. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  49844. }
  49845. } else {
  49846. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  49847. const groupName = uniform.groupNode.name;
  49848. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  49849. index: uniformIndexes.binding ++,
  49850. id: uniformIndexes.group,
  49851. snippets: []
  49852. } );
  49853. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  49854. }
  49855. }
  49856. for ( const name in uniformGroups ) {
  49857. const group = uniformGroups[ name ];
  49858. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  49859. }
  49860. let code = bindingSnippets.join( '\n' );
  49861. code += bufferSnippets.join( '\n' );
  49862. code += structSnippets.join( '\n' );
  49863. return code;
  49864. }
  49865. /**
  49866. * Controls the code build of the shader stages.
  49867. */
  49868. buildCode() {
  49869. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  49870. this.sortBindingGroups();
  49871. for ( const shaderStage in shadersData ) {
  49872. this.shaderStage = shaderStage;
  49873. const stageData = shadersData[ shaderStage ];
  49874. stageData.uniforms = this.getUniforms( shaderStage );
  49875. stageData.attributes = this.getAttributes( shaderStage );
  49876. stageData.varyings = this.getVaryings( shaderStage );
  49877. stageData.structs = this.getStructs( shaderStage );
  49878. stageData.vars = this.getVars( shaderStage );
  49879. stageData.codes = this.getCodes( shaderStage );
  49880. stageData.directives = this.getDirectives( shaderStage );
  49881. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  49882. //
  49883. let flow = '// code\n\n';
  49884. flow += this.flowCode[ shaderStage ];
  49885. const flowNodes = this.flowNodes[ shaderStage ];
  49886. const mainNode = flowNodes[ flowNodes.length - 1 ];
  49887. const outputNode = mainNode.outputNode;
  49888. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  49889. for ( const node of flowNodes ) {
  49890. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  49891. const slotName = node.name;
  49892. if ( slotName ) {
  49893. if ( flow.length > 0 ) flow += '\n';
  49894. flow += `\t// flow -> ${ slotName }\n`;
  49895. }
  49896. flow += `${ flowSlotData.code }\n\t`;
  49897. if ( node === mainNode && shaderStage !== 'compute' ) {
  49898. flow += '// result\n\n\t';
  49899. if ( shaderStage === 'vertex' ) {
  49900. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  49901. } else if ( shaderStage === 'fragment' ) {
  49902. if ( isOutputStruct ) {
  49903. stageData.returnType = outputNode.getNodeType( this );
  49904. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  49905. flow += `return ${ flowSlotData.result };`;
  49906. } else {
  49907. let structSnippet = '\t@location(0) color: vec4<f32>';
  49908. const builtins = this.getBuiltins( 'output' );
  49909. if ( builtins ) structSnippet += ',\n\t' + builtins;
  49910. stageData.returnType = 'OutputStruct';
  49911. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  49912. stageData.structs += '\nvar<private> output : OutputStruct;';
  49913. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  49914. }
  49915. }
  49916. }
  49917. }
  49918. stageData.flow = flow;
  49919. }
  49920. this.shaderStage = null;
  49921. if ( this.material !== null ) {
  49922. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  49923. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  49924. } else {
  49925. // Early strictly validated in computeNode
  49926. const workgroupSize = this.object.workgroupSize;
  49927. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  49928. }
  49929. }
  49930. /**
  49931. * Returns the native shader method name for a given generic name.
  49932. *
  49933. * @param {string} method - The method name to resolve.
  49934. * @param {?string} [output=null] - An optional output.
  49935. * @return {string} The resolved WGSL method name.
  49936. */
  49937. getMethod( method, output = null ) {
  49938. let wgslMethod;
  49939. if ( output !== null ) {
  49940. wgslMethod = this._getWGSLMethod( method + '_' + output );
  49941. }
  49942. if ( wgslMethod === undefined ) {
  49943. wgslMethod = this._getWGSLMethod( method );
  49944. }
  49945. return wgslMethod || method;
  49946. }
  49947. /**
  49948. * Returns the native snippet for a ternary operation.
  49949. *
  49950. * @param {string} condSnippet - The condition determining which expression gets resolved.
  49951. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  49952. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  49953. * @return {string} The resolved method name.
  49954. */
  49955. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  49956. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  49957. }
  49958. /**
  49959. * Returns the WGSL type of the given node data type.
  49960. *
  49961. * @param {string} type - The node data type.
  49962. * @return {string} The WGSL type.
  49963. */
  49964. getType( type ) {
  49965. return wgslTypeLib[ type ] || type;
  49966. }
  49967. /**
  49968. * Whether the requested feature is available or not.
  49969. *
  49970. * @param {string} name - The requested feature.
  49971. * @return {boolean} Whether the requested feature is supported or not.
  49972. */
  49973. isAvailable( name ) {
  49974. let result = supports[ name ];
  49975. if ( result === undefined ) {
  49976. if ( name === 'float32Filterable' ) {
  49977. result = this.renderer.hasFeature( 'float32-filterable' );
  49978. } else if ( name === 'clipDistance' ) {
  49979. result = this.renderer.hasFeature( 'clip-distances' );
  49980. }
  49981. supports[ name ] = result;
  49982. }
  49983. return result;
  49984. }
  49985. /**
  49986. * Returns the native shader method name for a given generic name.
  49987. *
  49988. * @private
  49989. * @param {string} method - The method name to resolve.
  49990. * @return {string} The resolved WGSL method name.
  49991. */
  49992. _getWGSLMethod( method ) {
  49993. if ( wgslPolyfill[ method ] !== undefined ) {
  49994. this._include( method );
  49995. }
  49996. return wgslMethods[ method ];
  49997. }
  49998. /**
  49999. * Includes the given method name into the current
  50000. * function node.
  50001. *
  50002. * @private
  50003. * @param {string} name - The method name to include.
  50004. * @return {CodeNode} The respective code node.
  50005. */
  50006. _include( name ) {
  50007. const codeNode = wgslPolyfill[ name ];
  50008. codeNode.build( this );
  50009. if ( this.currentFunctionNode !== null ) {
  50010. this.currentFunctionNode.includes.push( codeNode );
  50011. }
  50012. return codeNode;
  50013. }
  50014. /**
  50015. * Returns a WGSL vertex shader based on the given shader data.
  50016. *
  50017. * @private
  50018. * @param {Object} shaderData - The shader data.
  50019. * @return {string} The vertex shader.
  50020. */
  50021. _getWGSLVertexCode( shaderData ) {
  50022. return `${ this.getSignature() }
  50023. // directives
  50024. ${shaderData.directives}
  50025. // structs
  50026. ${shaderData.structs}
  50027. // uniforms
  50028. ${shaderData.uniforms}
  50029. // varyings
  50030. ${shaderData.varyings}
  50031. var<private> varyings : VaryingsStruct;
  50032. // codes
  50033. ${shaderData.codes}
  50034. @vertex
  50035. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  50036. // vars
  50037. ${shaderData.vars}
  50038. // flow
  50039. ${shaderData.flow}
  50040. return varyings;
  50041. }
  50042. `;
  50043. }
  50044. /**
  50045. * Returns a WGSL fragment shader based on the given shader data.
  50046. *
  50047. * @private
  50048. * @param {Object} shaderData - The shader data.
  50049. * @return {string} The vertex shader.
  50050. */
  50051. _getWGSLFragmentCode( shaderData ) {
  50052. return `${ this.getSignature() }
  50053. // global
  50054. ${ diagnostics }
  50055. // structs
  50056. ${shaderData.structs}
  50057. // uniforms
  50058. ${shaderData.uniforms}
  50059. // codes
  50060. ${shaderData.codes}
  50061. @fragment
  50062. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  50063. // vars
  50064. ${shaderData.vars}
  50065. // flow
  50066. ${shaderData.flow}
  50067. }
  50068. `;
  50069. }
  50070. /**
  50071. * Returns a WGSL compute shader based on the given shader data.
  50072. *
  50073. * @private
  50074. * @param {Object} shaderData - The shader data.
  50075. * @param {string} workgroupSize - The workgroup size.
  50076. * @return {string} The vertex shader.
  50077. */
  50078. _getWGSLComputeCode( shaderData, workgroupSize ) {
  50079. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  50080. return `${ this.getSignature() }
  50081. // directives
  50082. ${ shaderData.directives }
  50083. // system
  50084. var<private> instanceIndex : u32;
  50085. // locals
  50086. ${ shaderData.scopedArrays }
  50087. // structs
  50088. ${ shaderData.structs }
  50089. // uniforms
  50090. ${ shaderData.uniforms }
  50091. // codes
  50092. ${ shaderData.codes }
  50093. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  50094. fn main( ${ shaderData.attributes } ) {
  50095. // system
  50096. instanceIndex = globalId.x
  50097. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  50098. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  50099. // vars
  50100. ${ shaderData.vars }
  50101. // flow
  50102. ${ shaderData.flow }
  50103. }
  50104. `;
  50105. }
  50106. /**
  50107. * Returns a WGSL struct based on the given name and variables.
  50108. *
  50109. * @private
  50110. * @param {string} name - The struct name.
  50111. * @param {string} vars - The struct variables.
  50112. * @return {string} The WGSL snippet representing a struct.
  50113. */
  50114. _getWGSLStruct( name, vars ) {
  50115. return `
  50116. struct ${name} {
  50117. ${vars}
  50118. };`;
  50119. }
  50120. /**
  50121. * Returns a WGSL struct binding.
  50122. *
  50123. * @private
  50124. * @param {string} name - The struct name.
  50125. * @param {string} vars - The struct variables.
  50126. * @param {string} access - The access.
  50127. * @param {number} [binding=0] - The binding index.
  50128. * @param {number} [group=0] - The group index.
  50129. * @return {string} The WGSL snippet representing a struct binding.
  50130. */
  50131. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  50132. const structName = name + 'Struct';
  50133. const structSnippet = this._getWGSLStruct( structName, vars );
  50134. return `${structSnippet}
  50135. @binding( ${ binding } ) @group( ${ group } )
  50136. var<${access}> ${ name } : ${ structName };`;
  50137. }
  50138. }
  50139. /**
  50140. * A WebGPU backend utility module with common helpers.
  50141. *
  50142. * @private
  50143. */
  50144. class WebGPUUtils {
  50145. /**
  50146. * Constructs a new utility object.
  50147. *
  50148. * @param {WebGPUBackend} backend - The WebGPU backend.
  50149. */
  50150. constructor( backend ) {
  50151. /**
  50152. * A reference to the WebGPU backend.
  50153. *
  50154. * @type {WebGPUBackend}
  50155. */
  50156. this.backend = backend;
  50157. }
  50158. /**
  50159. * Returns the depth/stencil GPU format for the given render context.
  50160. *
  50161. * @param {RenderContext} renderContext - The render context.
  50162. * @return {string} The depth/stencil GPU texture format.
  50163. */
  50164. getCurrentDepthStencilFormat( renderContext ) {
  50165. let format;
  50166. if ( renderContext.depthTexture !== null ) {
  50167. format = this.getTextureFormatGPU( renderContext.depthTexture );
  50168. } else if ( renderContext.depth && renderContext.stencil ) {
  50169. format = GPUTextureFormat.Depth24PlusStencil8;
  50170. } else if ( renderContext.depth ) {
  50171. format = GPUTextureFormat.Depth24Plus;
  50172. }
  50173. return format;
  50174. }
  50175. /**
  50176. * Returns the GPU format for the given texture.
  50177. *
  50178. * @param {Texture} texture - The texture.
  50179. * @return {string} The GPU texture format.
  50180. */
  50181. getTextureFormatGPU( texture ) {
  50182. return this.backend.get( texture ).format;
  50183. }
  50184. /**
  50185. * Returns an object that defines the multi-sampling state of the given texture.
  50186. *
  50187. * @param {Texture} texture - The texture.
  50188. * @return {Object} The multi-sampling state.
  50189. */
  50190. getTextureSampleData( texture ) {
  50191. let samples;
  50192. if ( texture.isFramebufferTexture ) {
  50193. samples = 1;
  50194. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  50195. const renderer = this.backend.renderer;
  50196. const renderTarget = renderer.getRenderTarget();
  50197. samples = renderTarget ? renderTarget.samples : renderer.samples;
  50198. } else if ( texture.renderTarget ) {
  50199. samples = texture.renderTarget.samples;
  50200. }
  50201. samples = samples || 1;
  50202. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  50203. const primarySamples = isMSAA ? 1 : samples;
  50204. return { samples, primarySamples, isMSAA };
  50205. }
  50206. /**
  50207. * Returns the default color attachment's GPU format of the current render context.
  50208. *
  50209. * @param {RenderContext} renderContext - The render context.
  50210. * @return {string} The GPU texture format of the default color attachment.
  50211. */
  50212. getCurrentColorFormat( renderContext ) {
  50213. let format;
  50214. if ( renderContext.textures !== null ) {
  50215. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  50216. } else {
  50217. format = this.getPreferredCanvasFormat(); // default context format
  50218. }
  50219. return format;
  50220. }
  50221. /**
  50222. * Returns the output color space of the current render context.
  50223. *
  50224. * @param {RenderContext} renderContext - The render context.
  50225. * @return {string} The output color space.
  50226. */
  50227. getCurrentColorSpace( renderContext ) {
  50228. if ( renderContext.textures !== null ) {
  50229. return renderContext.textures[ 0 ].colorSpace;
  50230. }
  50231. return this.backend.renderer.outputColorSpace;
  50232. }
  50233. /**
  50234. * Returns GPU primitive topology for the given object and material.
  50235. *
  50236. * @param {Object3D} object - The 3D object.
  50237. * @param {Material} material - The material.
  50238. * @return {string} The GPU primitive topology.
  50239. */
  50240. getPrimitiveTopology( object, material ) {
  50241. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  50242. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  50243. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  50244. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  50245. }
  50246. /**
  50247. * Returns a modified sample count from the given sample count value.
  50248. *
  50249. * That is required since WebGPU only supports either 1 or 4.
  50250. *
  50251. * @param {number} sampleCount - The input sample count.
  50252. * @return {number} The (potentially updated) output sample count.
  50253. */
  50254. getSampleCount( sampleCount ) {
  50255. return sampleCount >= 4 ? 4 : 1;
  50256. }
  50257. /**
  50258. * Returns the sample count of the given render context.
  50259. *
  50260. * @param {RenderContext} renderContext - The render context.
  50261. * @return {number} The sample count.
  50262. */
  50263. getSampleCountRenderContext( renderContext ) {
  50264. if ( renderContext.textures !== null ) {
  50265. return this.getSampleCount( renderContext.sampleCount );
  50266. }
  50267. return this.getSampleCount( this.backend.renderer.samples );
  50268. }
  50269. /**
  50270. * Returns the preferred canvas format.
  50271. *
  50272. * There is a separate method for this so it's possible to
  50273. * honor edge cases for specific devices.
  50274. *
  50275. * @return {string} The GPU texture format of the canvas.
  50276. */
  50277. getPreferredCanvasFormat() {
  50278. const outputType = this.backend.parameters.outputType;
  50279. if ( outputType === undefined ) {
  50280. return navigator.gpu.getPreferredCanvasFormat();
  50281. } else if ( outputType === UnsignedByteType ) {
  50282. return GPUTextureFormat.BGRA8Unorm;
  50283. } else if ( outputType === HalfFloatType ) {
  50284. return GPUTextureFormat.RGBA16Float;
  50285. } else {
  50286. throw new Error( 'Unsupported outputType' );
  50287. }
  50288. }
  50289. }
  50290. const typedArraysToVertexFormatPrefix = new Map( [
  50291. [ Int8Array, [ 'sint8', 'snorm8' ]],
  50292. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  50293. [ Int16Array, [ 'sint16', 'snorm16' ]],
  50294. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  50295. [ Int32Array, [ 'sint32', 'snorm32' ]],
  50296. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  50297. [ Float32Array, [ 'float32', ]],
  50298. ] );
  50299. if ( typeof Float16Array !== 'undefined' ) {
  50300. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  50301. }
  50302. const typedAttributeToVertexFormatPrefix = new Map( [
  50303. [ Float16BufferAttribute, [ 'float16', ]],
  50304. ] );
  50305. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  50306. [ Int32Array, 'sint32' ],
  50307. [ Int16Array, 'sint32' ], // patch for INT16
  50308. [ Uint32Array, 'uint32' ],
  50309. [ Uint16Array, 'uint32' ], // patch for UINT16
  50310. [ Float32Array, 'float32' ]
  50311. ] );
  50312. /**
  50313. * A WebGPU backend utility module for managing shader attributes.
  50314. *
  50315. * @private
  50316. */
  50317. class WebGPUAttributeUtils {
  50318. /**
  50319. * Constructs a new utility object.
  50320. *
  50321. * @param {WebGPUBackend} backend - The WebGPU backend.
  50322. */
  50323. constructor( backend ) {
  50324. /**
  50325. * A reference to the WebGPU backend.
  50326. *
  50327. * @type {WebGPUBackend}
  50328. */
  50329. this.backend = backend;
  50330. }
  50331. /**
  50332. * Creates the GPU buffer for the given buffer attribute.
  50333. *
  50334. * @param {BufferAttribute} attribute - The buffer attribute.
  50335. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  50336. */
  50337. createAttribute( attribute, usage ) {
  50338. const bufferAttribute = this._getBufferAttribute( attribute );
  50339. const backend = this.backend;
  50340. const bufferData = backend.get( bufferAttribute );
  50341. let buffer = bufferData.buffer;
  50342. if ( buffer === undefined ) {
  50343. const device = backend.device;
  50344. let array = bufferAttribute.array;
  50345. // patch for INT16 and UINT16
  50346. if ( attribute.normalized === false ) {
  50347. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  50348. array = new Int32Array( array );
  50349. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  50350. array = new Uint32Array( array );
  50351. if ( usage & GPUBufferUsage.INDEX ) {
  50352. for ( let i = 0; i < array.length; i ++ ) {
  50353. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  50354. }
  50355. }
  50356. }
  50357. }
  50358. bufferAttribute.array = array;
  50359. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  50360. array = new array.constructor( bufferAttribute.count * 4 );
  50361. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  50362. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  50363. }
  50364. // Update BufferAttribute
  50365. bufferAttribute.itemSize = 4;
  50366. bufferAttribute.array = array;
  50367. bufferData._force3to4BytesAlignment = true;
  50368. }
  50369. // ensure 4 byte alignment
  50370. const byteLength = array.byteLength;
  50371. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  50372. buffer = device.createBuffer( {
  50373. label: bufferAttribute.name,
  50374. size: size,
  50375. usage: usage,
  50376. mappedAtCreation: true
  50377. } );
  50378. new array.constructor( buffer.getMappedRange() ).set( array );
  50379. buffer.unmap();
  50380. bufferData.buffer = buffer;
  50381. }
  50382. }
  50383. /**
  50384. * Updates the GPU buffer of the given buffer attribute.
  50385. *
  50386. * @param {BufferAttribute} attribute - The buffer attribute.
  50387. */
  50388. updateAttribute( attribute ) {
  50389. const bufferAttribute = this._getBufferAttribute( attribute );
  50390. const backend = this.backend;
  50391. const device = backend.device;
  50392. const bufferData = backend.get( bufferAttribute );
  50393. const buffer = backend.get( bufferAttribute ).buffer;
  50394. let array = bufferAttribute.array;
  50395. // if storage buffer ensure 4 byte alignment
  50396. if ( bufferData._force3to4BytesAlignment === true ) {
  50397. array = new array.constructor( bufferAttribute.count * 4 );
  50398. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  50399. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  50400. }
  50401. bufferAttribute.array = array;
  50402. }
  50403. const isTypedArray = this._isTypedArray( array );
  50404. const updateRanges = bufferAttribute.updateRanges;
  50405. if ( updateRanges.length === 0 ) {
  50406. // Not using update ranges
  50407. device.queue.writeBuffer(
  50408. buffer,
  50409. 0,
  50410. array,
  50411. 0
  50412. );
  50413. } else {
  50414. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  50415. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  50416. const range = updateRanges[ i ];
  50417. let dataOffset, size;
  50418. if ( bufferData._force3to4BytesAlignment === true ) {
  50419. const vertexStart = Math.floor( range.start / 3 );
  50420. const vertexCount = Math.ceil( range.count / 3 );
  50421. dataOffset = vertexStart * 4 * byteOffsetFactor;
  50422. size = vertexCount * 4 * byteOffsetFactor;
  50423. } else {
  50424. dataOffset = range.start * byteOffsetFactor;
  50425. size = range.count * byteOffsetFactor;
  50426. }
  50427. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  50428. device.queue.writeBuffer(
  50429. buffer,
  50430. bufferOffset,
  50431. array,
  50432. dataOffset,
  50433. size
  50434. );
  50435. }
  50436. bufferAttribute.clearUpdateRanges();
  50437. }
  50438. }
  50439. /**
  50440. * This method creates the vertex buffer layout data which are
  50441. * require when creating a render pipeline for the given render object.
  50442. *
  50443. * @param {RenderObject} renderObject - The render object.
  50444. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  50445. */
  50446. createShaderVertexBuffers( renderObject ) {
  50447. const attributes = renderObject.getAttributes();
  50448. const vertexBuffers = new Map();
  50449. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  50450. const geometryAttribute = attributes[ slot ];
  50451. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  50452. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  50453. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  50454. if ( vertexBufferLayout === undefined ) {
  50455. let arrayStride, stepMode;
  50456. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  50457. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  50458. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  50459. } else {
  50460. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  50461. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  50462. }
  50463. // patch for INT16 and UINT16
  50464. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  50465. arrayStride = 4;
  50466. }
  50467. vertexBufferLayout = {
  50468. arrayStride,
  50469. attributes: [],
  50470. stepMode
  50471. };
  50472. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  50473. }
  50474. const format = this._getVertexFormat( geometryAttribute );
  50475. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  50476. vertexBufferLayout.attributes.push( {
  50477. shaderLocation: slot,
  50478. offset,
  50479. format
  50480. } );
  50481. }
  50482. return Array.from( vertexBuffers.values() );
  50483. }
  50484. /**
  50485. * Destroys the GPU buffer of the given buffer attribute.
  50486. *
  50487. * @param {BufferAttribute} attribute - The buffer attribute.
  50488. */
  50489. destroyAttribute( attribute ) {
  50490. const backend = this.backend;
  50491. const data = backend.get( this._getBufferAttribute( attribute ) );
  50492. data.buffer.destroy();
  50493. backend.delete( attribute );
  50494. }
  50495. /**
  50496. * This method performs a readback operation by moving buffer data from
  50497. * a storage buffer attribute from the GPU to the CPU.
  50498. *
  50499. * @async
  50500. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  50501. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  50502. */
  50503. async getArrayBufferAsync( attribute ) {
  50504. const backend = this.backend;
  50505. const device = backend.device;
  50506. const data = backend.get( this._getBufferAttribute( attribute ) );
  50507. const bufferGPU = data.buffer;
  50508. const size = bufferGPU.size;
  50509. const readBufferGPU = device.createBuffer( {
  50510. label: `${ attribute.name }_readback`,
  50511. size,
  50512. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50513. } );
  50514. const cmdEncoder = device.createCommandEncoder( {
  50515. label: `readback_encoder_${ attribute.name }`
  50516. } );
  50517. cmdEncoder.copyBufferToBuffer(
  50518. bufferGPU,
  50519. 0,
  50520. readBufferGPU,
  50521. 0,
  50522. size
  50523. );
  50524. const gpuCommands = cmdEncoder.finish();
  50525. device.queue.submit( [ gpuCommands ] );
  50526. await readBufferGPU.mapAsync( GPUMapMode.READ );
  50527. const arrayBuffer = readBufferGPU.getMappedRange();
  50528. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  50529. readBufferGPU.unmap();
  50530. return dstBuffer.buffer;
  50531. }
  50532. /**
  50533. * Returns the vertex format of the given buffer attribute.
  50534. *
  50535. * @private
  50536. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  50537. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  50538. */
  50539. _getVertexFormat( geometryAttribute ) {
  50540. const { itemSize, normalized } = geometryAttribute;
  50541. const ArrayType = geometryAttribute.array.constructor;
  50542. const AttributeType = geometryAttribute.constructor;
  50543. let format;
  50544. if ( itemSize === 1 ) {
  50545. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  50546. } else {
  50547. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  50548. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  50549. if ( prefix ) {
  50550. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  50551. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  50552. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  50553. if ( paddedItemSize % 1 ) {
  50554. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  50555. }
  50556. format = `${prefix}x${paddedItemSize}`;
  50557. }
  50558. }
  50559. if ( ! format ) {
  50560. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  50561. }
  50562. return format;
  50563. }
  50564. /**
  50565. * Returns `true` if the given array is a typed array.
  50566. *
  50567. * @private
  50568. * @param {any} array - The array.
  50569. * @return {boolean} Whether the given array is a typed array or not.
  50570. */
  50571. _isTypedArray( array ) {
  50572. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  50573. }
  50574. /**
  50575. * Utility method for handling interleaved buffer attributes correctly.
  50576. * To process them, their `InterleavedBuffer` is returned.
  50577. *
  50578. * @private
  50579. * @param {BufferAttribute} attribute - The attribute.
  50580. * @return {BufferAttribute|InterleavedBuffer}
  50581. */
  50582. _getBufferAttribute( attribute ) {
  50583. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  50584. return attribute;
  50585. }
  50586. }
  50587. /**
  50588. * A WebGPU backend utility module for managing bindings.
  50589. *
  50590. * When reading the documentation it's helpful to keep in mind that
  50591. * all class definitions starting with 'GPU*' are modules from the
  50592. * WebGPU API. So for example `BindGroup` is a class from the engine
  50593. * whereas `GPUBindGroup` is a class from WebGPU.
  50594. *
  50595. * @private
  50596. */
  50597. class WebGPUBindingUtils {
  50598. /**
  50599. * Constructs a new utility object.
  50600. *
  50601. * @param {WebGPUBackend} backend - The WebGPU backend.
  50602. */
  50603. constructor( backend ) {
  50604. /**
  50605. * A reference to the WebGPU backend.
  50606. *
  50607. * @type {WebGPUBackend}
  50608. */
  50609. this.backend = backend;
  50610. /**
  50611. * A cache for managing bind group layouts.
  50612. *
  50613. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  50614. */
  50615. this.bindGroupLayoutCache = new WeakMap();
  50616. }
  50617. /**
  50618. * Creates a GPU bind group layout for the given bind group.
  50619. *
  50620. * @param {BindGroup} bindGroup - The bind group.
  50621. * @return {GPUBindGroupLayout} The GPU bind group layout.
  50622. */
  50623. createBindingsLayout( bindGroup ) {
  50624. const backend = this.backend;
  50625. const device = backend.device;
  50626. const entries = [];
  50627. let index = 0;
  50628. for ( const binding of bindGroup.bindings ) {
  50629. const bindingGPU = {
  50630. binding: index ++,
  50631. visibility: binding.visibility
  50632. };
  50633. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  50634. const buffer = {}; // GPUBufferBindingLayout
  50635. if ( binding.isStorageBuffer ) {
  50636. if ( binding.visibility & 4 ) {
  50637. // compute
  50638. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  50639. buffer.type = GPUBufferBindingType.Storage;
  50640. } else {
  50641. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  50642. }
  50643. } else {
  50644. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  50645. }
  50646. }
  50647. bindingGPU.buffer = buffer;
  50648. } else if ( binding.isSampledTexture && binding.store ) {
  50649. const storageTexture = {}; // GPUStorageTextureBindingLayout
  50650. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  50651. const access = binding.access;
  50652. if ( access === NodeAccess.READ_WRITE ) {
  50653. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  50654. } else if ( access === NodeAccess.WRITE_ONLY ) {
  50655. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  50656. } else {
  50657. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  50658. }
  50659. if ( binding.texture.isArrayTexture ) {
  50660. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  50661. } else if ( binding.texture.is3DTexture ) {
  50662. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  50663. }
  50664. bindingGPU.storageTexture = storageTexture;
  50665. } else if ( binding.isSampledTexture ) {
  50666. const texture = {}; // GPUTextureBindingLayout
  50667. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  50668. if ( primarySamples > 1 ) {
  50669. texture.multisampled = true;
  50670. if ( ! binding.texture.isDepthTexture ) {
  50671. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  50672. }
  50673. }
  50674. if ( binding.texture.isDepthTexture ) {
  50675. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  50676. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  50677. } else {
  50678. texture.sampleType = GPUTextureSampleType.Depth;
  50679. }
  50680. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  50681. const type = binding.texture.type;
  50682. if ( type === IntType ) {
  50683. texture.sampleType = GPUTextureSampleType.SInt;
  50684. } else if ( type === UnsignedIntType ) {
  50685. texture.sampleType = GPUTextureSampleType.UInt;
  50686. } else if ( type === FloatType ) {
  50687. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  50688. texture.sampleType = GPUTextureSampleType.Float;
  50689. } else {
  50690. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  50691. }
  50692. }
  50693. }
  50694. if ( binding.isSampledCubeTexture ) {
  50695. texture.viewDimension = GPUTextureViewDimension.Cube;
  50696. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  50697. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  50698. } else if ( binding.isSampledTexture3D ) {
  50699. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  50700. }
  50701. bindingGPU.texture = texture;
  50702. } else if ( binding.isSampler ) {
  50703. const sampler = {}; // GPUSamplerBindingLayout
  50704. if ( binding.texture.isDepthTexture ) {
  50705. if ( binding.texture.compareFunction !== null ) {
  50706. sampler.type = GPUSamplerBindingType.Comparison;
  50707. } else if ( backend.compatibilityMode ) {
  50708. sampler.type = GPUSamplerBindingType.NonFiltering;
  50709. }
  50710. }
  50711. bindingGPU.sampler = sampler;
  50712. } else {
  50713. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  50714. }
  50715. entries.push( bindingGPU );
  50716. }
  50717. return device.createBindGroupLayout( { entries } );
  50718. }
  50719. /**
  50720. * Creates bindings from the given bind group definition.
  50721. *
  50722. * @param {BindGroup} bindGroup - The bind group.
  50723. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50724. * @param {number} cacheIndex - The cache index.
  50725. * @param {number} version - The version.
  50726. */
  50727. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  50728. const { backend, bindGroupLayoutCache } = this;
  50729. const bindingsData = backend.get( bindGroup );
  50730. // setup (static) binding layout and (dynamic) binding group
  50731. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  50732. if ( bindLayoutGPU === undefined ) {
  50733. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  50734. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  50735. }
  50736. let bindGroupGPU;
  50737. if ( cacheIndex > 0 ) {
  50738. if ( bindingsData.groups === undefined ) {
  50739. bindingsData.groups = [];
  50740. bindingsData.versions = [];
  50741. }
  50742. if ( bindingsData.versions[ cacheIndex ] === version ) {
  50743. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  50744. }
  50745. }
  50746. if ( bindGroupGPU === undefined ) {
  50747. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  50748. if ( cacheIndex > 0 ) {
  50749. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  50750. bindingsData.versions[ cacheIndex ] = version;
  50751. }
  50752. }
  50753. bindingsData.group = bindGroupGPU;
  50754. bindingsData.layout = bindLayoutGPU;
  50755. }
  50756. /**
  50757. * Updates a buffer binding.
  50758. *
  50759. * @param {Buffer} binding - The buffer binding to update.
  50760. */
  50761. updateBinding( binding ) {
  50762. const backend = this.backend;
  50763. const device = backend.device;
  50764. const buffer = binding.buffer;
  50765. const bufferGPU = backend.get( binding ).buffer;
  50766. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  50767. }
  50768. /**
  50769. * Creates a GPU bind group for the camera index.
  50770. *
  50771. * @param {Uint32Array} data - The index data.
  50772. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  50773. * @return {GPUBindGroup} The GPU bind group.
  50774. */
  50775. createBindGroupIndex( data, layout ) {
  50776. const backend = this.backend;
  50777. const device = backend.device;
  50778. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  50779. const index = data[ 0 ];
  50780. const buffer = device.createBuffer( {
  50781. label: 'bindingCameraIndex_' + index,
  50782. size: 16, // uint(4) * 4
  50783. usage: usage
  50784. } );
  50785. device.queue.writeBuffer( buffer, 0, data, 0 );
  50786. const entries = [ { binding: 0, resource: { buffer } } ];
  50787. return device.createBindGroup( {
  50788. label: 'bindGroupCameraIndex_' + index,
  50789. layout,
  50790. entries
  50791. } );
  50792. }
  50793. /**
  50794. * Creates a GPU bind group for the given bind group and GPU layout.
  50795. *
  50796. * @param {BindGroup} bindGroup - The bind group.
  50797. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  50798. * @return {GPUBindGroup} The GPU bind group.
  50799. */
  50800. createBindGroup( bindGroup, layoutGPU ) {
  50801. const backend = this.backend;
  50802. const device = backend.device;
  50803. let bindingPoint = 0;
  50804. const entriesGPU = [];
  50805. for ( const binding of bindGroup.bindings ) {
  50806. if ( binding.isUniformBuffer ) {
  50807. const bindingData = backend.get( binding );
  50808. if ( bindingData.buffer === undefined ) {
  50809. const byteLength = binding.byteLength;
  50810. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  50811. const bufferGPU = device.createBuffer( {
  50812. label: 'bindingBuffer_' + binding.name,
  50813. size: byteLength,
  50814. usage: usage
  50815. } );
  50816. bindingData.buffer = bufferGPU;
  50817. }
  50818. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  50819. } else if ( binding.isStorageBuffer ) {
  50820. const bindingData = backend.get( binding );
  50821. if ( bindingData.buffer === undefined ) {
  50822. const attribute = binding.attribute;
  50823. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  50824. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  50825. bindingData.buffer = backend.get( attribute ).buffer;
  50826. }
  50827. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  50828. } else if ( binding.isSampledTexture ) {
  50829. const textureData = backend.get( binding.texture );
  50830. let resourceGPU;
  50831. if ( textureData.externalTexture !== undefined ) {
  50832. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  50833. } else {
  50834. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  50835. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  50836. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  50837. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  50838. }
  50839. propertyName += `-${ mipLevelCount }`;
  50840. resourceGPU = textureData[ propertyName ];
  50841. if ( resourceGPU === undefined ) {
  50842. const aspectGPU = GPUTextureAspect.All;
  50843. let dimensionViewGPU;
  50844. if ( binding.isSampledCubeTexture ) {
  50845. dimensionViewGPU = GPUTextureViewDimension.Cube;
  50846. } else if ( binding.isSampledTexture3D ) {
  50847. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  50848. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  50849. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  50850. } else {
  50851. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  50852. }
  50853. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  50854. }
  50855. }
  50856. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  50857. } else if ( binding.isSampler ) {
  50858. const textureGPU = backend.get( binding.texture );
  50859. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  50860. }
  50861. bindingPoint ++;
  50862. }
  50863. return device.createBindGroup( {
  50864. label: 'bindGroup_' + bindGroup.name,
  50865. layout: layoutGPU,
  50866. entries: entriesGPU
  50867. } );
  50868. }
  50869. }
  50870. /**
  50871. * A WebGPU backend utility module for managing pipelines.
  50872. *
  50873. * @private
  50874. */
  50875. class WebGPUPipelineUtils {
  50876. /**
  50877. * Constructs a new utility object.
  50878. *
  50879. * @param {WebGPUBackend} backend - The WebGPU backend.
  50880. */
  50881. constructor( backend ) {
  50882. /**
  50883. * A reference to the WebGPU backend.
  50884. *
  50885. * @type {WebGPUBackend}
  50886. */
  50887. this.backend = backend;
  50888. /**
  50889. * A Weak Map that tracks the active pipeline for render or compute passes.
  50890. *
  50891. * @private
  50892. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  50893. */
  50894. this._activePipelines = new WeakMap();
  50895. }
  50896. /**
  50897. * Sets the given pipeline for the given pass. The method makes sure to only set the
  50898. * pipeline when necessary.
  50899. *
  50900. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  50901. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  50902. */
  50903. setPipeline( pass, pipeline ) {
  50904. const currentPipeline = this._activePipelines.get( pass );
  50905. if ( currentPipeline !== pipeline ) {
  50906. pass.setPipeline( pipeline );
  50907. this._activePipelines.set( pass, pipeline );
  50908. }
  50909. }
  50910. /**
  50911. * Returns the sample count derived from the given render context.
  50912. *
  50913. * @private
  50914. * @param {RenderContext} renderContext - The render context.
  50915. * @return {number} The sample count.
  50916. */
  50917. _getSampleCount( renderContext ) {
  50918. return this.backend.utils.getSampleCountRenderContext( renderContext );
  50919. }
  50920. /**
  50921. * Creates a render pipeline for the given render object.
  50922. *
  50923. * @param {RenderObject} renderObject - The render object.
  50924. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  50925. */
  50926. createRenderPipeline( renderObject, promises ) {
  50927. const { object, material, geometry, pipeline } = renderObject;
  50928. const { vertexProgram, fragmentProgram } = pipeline;
  50929. const backend = this.backend;
  50930. const device = backend.device;
  50931. const utils = backend.utils;
  50932. const pipelineData = backend.get( pipeline );
  50933. // bind group layouts
  50934. const bindGroupLayouts = [];
  50935. for ( const bindGroup of renderObject.getBindings() ) {
  50936. const bindingsData = backend.get( bindGroup );
  50937. bindGroupLayouts.push( bindingsData.layout );
  50938. }
  50939. // vertex buffers
  50940. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  50941. // blending
  50942. let blending;
  50943. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  50944. blending = this._getBlending( material );
  50945. }
  50946. // stencil
  50947. let stencilFront = {};
  50948. if ( material.stencilWrite === true ) {
  50949. stencilFront = {
  50950. compare: this._getStencilCompare( material ),
  50951. failOp: this._getStencilOperation( material.stencilFail ),
  50952. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  50953. passOp: this._getStencilOperation( material.stencilZPass )
  50954. };
  50955. }
  50956. const colorWriteMask = this._getColorWriteMask( material );
  50957. const targets = [];
  50958. if ( renderObject.context.textures !== null ) {
  50959. const textures = renderObject.context.textures;
  50960. for ( let i = 0; i < textures.length; i ++ ) {
  50961. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  50962. targets.push( {
  50963. format: colorFormat,
  50964. blend: blending,
  50965. writeMask: colorWriteMask
  50966. } );
  50967. }
  50968. } else {
  50969. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  50970. targets.push( {
  50971. format: colorFormat,
  50972. blend: blending,
  50973. writeMask: colorWriteMask
  50974. } );
  50975. }
  50976. const vertexModule = backend.get( vertexProgram ).module;
  50977. const fragmentModule = backend.get( fragmentProgram ).module;
  50978. const primitiveState = this._getPrimitiveState( object, geometry, material );
  50979. const depthCompare = this._getDepthCompare( material );
  50980. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  50981. const sampleCount = this._getSampleCount( renderObject.context );
  50982. const pipelineDescriptor = {
  50983. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  50984. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  50985. fragment: Object.assign( {}, fragmentModule, { targets } ),
  50986. primitive: primitiveState,
  50987. multisample: {
  50988. count: sampleCount,
  50989. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  50990. },
  50991. layout: device.createPipelineLayout( {
  50992. bindGroupLayouts
  50993. } )
  50994. };
  50995. const depthStencil = {};
  50996. const renderDepth = renderObject.context.depth;
  50997. const renderStencil = renderObject.context.stencil;
  50998. if ( renderDepth === true || renderStencil === true ) {
  50999. if ( renderDepth === true ) {
  51000. depthStencil.format = depthStencilFormat;
  51001. depthStencil.depthWriteEnabled = material.depthWrite;
  51002. depthStencil.depthCompare = depthCompare;
  51003. }
  51004. if ( renderStencil === true ) {
  51005. depthStencil.stencilFront = stencilFront;
  51006. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  51007. depthStencil.stencilReadMask = material.stencilFuncMask;
  51008. depthStencil.stencilWriteMask = material.stencilWriteMask;
  51009. }
  51010. if ( material.polygonOffset === true ) {
  51011. depthStencil.depthBias = material.polygonOffsetUnits;
  51012. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  51013. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  51014. }
  51015. pipelineDescriptor.depthStencil = depthStencil;
  51016. }
  51017. if ( promises === null ) {
  51018. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  51019. } else {
  51020. const p = new Promise( ( resolve /*, reject*/ ) => {
  51021. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  51022. pipelineData.pipeline = pipeline;
  51023. resolve();
  51024. } );
  51025. } );
  51026. promises.push( p );
  51027. }
  51028. }
  51029. /**
  51030. * Creates GPU render bundle encoder for the given render context.
  51031. *
  51032. * @param {RenderContext} renderContext - The render context.
  51033. * @param {?string} [label='renderBundleEncoder'] - The label.
  51034. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  51035. */
  51036. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  51037. const backend = this.backend;
  51038. const { utils, device } = backend;
  51039. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  51040. const colorFormat = utils.getCurrentColorFormat( renderContext );
  51041. const sampleCount = this._getSampleCount( renderContext );
  51042. const descriptor = {
  51043. label: label,
  51044. colorFormats: [ colorFormat ],
  51045. depthStencilFormat,
  51046. sampleCount
  51047. };
  51048. return device.createRenderBundleEncoder( descriptor );
  51049. }
  51050. /**
  51051. * Creates a compute pipeline for the given compute node.
  51052. *
  51053. * @param {ComputePipeline} pipeline - The compute pipeline.
  51054. * @param {Array<BindGroup>} bindings - The bindings.
  51055. */
  51056. createComputePipeline( pipeline, bindings ) {
  51057. const backend = this.backend;
  51058. const device = backend.device;
  51059. const computeProgram = backend.get( pipeline.computeProgram ).module;
  51060. const pipelineGPU = backend.get( pipeline );
  51061. // bind group layouts
  51062. const bindGroupLayouts = [];
  51063. for ( const bindingsGroup of bindings ) {
  51064. const bindingsData = backend.get( bindingsGroup );
  51065. bindGroupLayouts.push( bindingsData.layout );
  51066. }
  51067. pipelineGPU.pipeline = device.createComputePipeline( {
  51068. compute: computeProgram,
  51069. layout: device.createPipelineLayout( {
  51070. bindGroupLayouts
  51071. } )
  51072. } );
  51073. }
  51074. /**
  51075. * Returns the blending state as a descriptor object required
  51076. * for the pipeline creation.
  51077. *
  51078. * @private
  51079. * @param {Material} material - The material.
  51080. * @return {Object} The blending state.
  51081. */
  51082. _getBlending( material ) {
  51083. let color, alpha;
  51084. const blending = material.blending;
  51085. const blendSrc = material.blendSrc;
  51086. const blendDst = material.blendDst;
  51087. const blendEquation = material.blendEquation;
  51088. if ( blending === CustomBlending ) {
  51089. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  51090. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  51091. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  51092. color = {
  51093. srcFactor: this._getBlendFactor( blendSrc ),
  51094. dstFactor: this._getBlendFactor( blendDst ),
  51095. operation: this._getBlendOperation( blendEquation )
  51096. };
  51097. alpha = {
  51098. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  51099. dstFactor: this._getBlendFactor( blendDstAlpha ),
  51100. operation: this._getBlendOperation( blendEquationAlpha )
  51101. };
  51102. } else {
  51103. const premultipliedAlpha = material.premultipliedAlpha;
  51104. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  51105. color = {
  51106. srcFactor: srcRGB,
  51107. dstFactor: dstRGB,
  51108. operation: GPUBlendOperation.Add
  51109. };
  51110. alpha = {
  51111. srcFactor: srcAlpha,
  51112. dstFactor: dstAlpha,
  51113. operation: GPUBlendOperation.Add
  51114. };
  51115. };
  51116. if ( premultipliedAlpha ) {
  51117. switch ( blending ) {
  51118. case NormalBlending:
  51119. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  51120. break;
  51121. case AdditiveBlending:
  51122. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  51123. break;
  51124. case SubtractiveBlending:
  51125. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  51126. break;
  51127. case MultiplyBlending:
  51128. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  51129. break;
  51130. }
  51131. } else {
  51132. switch ( blending ) {
  51133. case NormalBlending:
  51134. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  51135. break;
  51136. case AdditiveBlending:
  51137. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  51138. break;
  51139. case SubtractiveBlending:
  51140. console.error( 'THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  51141. break;
  51142. case MultiplyBlending:
  51143. console.error( 'THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  51144. break;
  51145. }
  51146. }
  51147. }
  51148. if ( color !== undefined && alpha !== undefined ) {
  51149. return { color, alpha };
  51150. } else {
  51151. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  51152. }
  51153. }
  51154. /**
  51155. * Returns the GPU blend factor which is required for the pipeline creation.
  51156. *
  51157. * @private
  51158. * @param {number} blend - The blend factor as a three.js constant.
  51159. * @return {string} The GPU blend factor.
  51160. */
  51161. _getBlendFactor( blend ) {
  51162. let blendFactor;
  51163. switch ( blend ) {
  51164. case ZeroFactor:
  51165. blendFactor = GPUBlendFactor.Zero;
  51166. break;
  51167. case OneFactor:
  51168. blendFactor = GPUBlendFactor.One;
  51169. break;
  51170. case SrcColorFactor:
  51171. blendFactor = GPUBlendFactor.Src;
  51172. break;
  51173. case OneMinusSrcColorFactor:
  51174. blendFactor = GPUBlendFactor.OneMinusSrc;
  51175. break;
  51176. case SrcAlphaFactor:
  51177. blendFactor = GPUBlendFactor.SrcAlpha;
  51178. break;
  51179. case OneMinusSrcAlphaFactor:
  51180. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  51181. break;
  51182. case DstColorFactor:
  51183. blendFactor = GPUBlendFactor.Dst;
  51184. break;
  51185. case OneMinusDstColorFactor:
  51186. blendFactor = GPUBlendFactor.OneMinusDst;
  51187. break;
  51188. case DstAlphaFactor:
  51189. blendFactor = GPUBlendFactor.DstAlpha;
  51190. break;
  51191. case OneMinusDstAlphaFactor:
  51192. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  51193. break;
  51194. case SrcAlphaSaturateFactor:
  51195. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  51196. break;
  51197. case BlendColorFactor:
  51198. blendFactor = GPUBlendFactor.Constant;
  51199. break;
  51200. case OneMinusBlendColorFactor:
  51201. blendFactor = GPUBlendFactor.OneMinusConstant;
  51202. break;
  51203. default:
  51204. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  51205. }
  51206. return blendFactor;
  51207. }
  51208. /**
  51209. * Returns the GPU stencil compare function which is required for the pipeline creation.
  51210. *
  51211. * @private
  51212. * @param {Material} material - The material.
  51213. * @return {string} The GPU stencil compare function.
  51214. */
  51215. _getStencilCompare( material ) {
  51216. let stencilCompare;
  51217. const stencilFunc = material.stencilFunc;
  51218. switch ( stencilFunc ) {
  51219. case NeverStencilFunc:
  51220. stencilCompare = GPUCompareFunction.Never;
  51221. break;
  51222. case AlwaysStencilFunc:
  51223. stencilCompare = GPUCompareFunction.Always;
  51224. break;
  51225. case LessStencilFunc:
  51226. stencilCompare = GPUCompareFunction.Less;
  51227. break;
  51228. case LessEqualStencilFunc:
  51229. stencilCompare = GPUCompareFunction.LessEqual;
  51230. break;
  51231. case EqualStencilFunc:
  51232. stencilCompare = GPUCompareFunction.Equal;
  51233. break;
  51234. case GreaterEqualStencilFunc:
  51235. stencilCompare = GPUCompareFunction.GreaterEqual;
  51236. break;
  51237. case GreaterStencilFunc:
  51238. stencilCompare = GPUCompareFunction.Greater;
  51239. break;
  51240. case NotEqualStencilFunc:
  51241. stencilCompare = GPUCompareFunction.NotEqual;
  51242. break;
  51243. default:
  51244. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  51245. }
  51246. return stencilCompare;
  51247. }
  51248. /**
  51249. * Returns the GPU stencil operation which is required for the pipeline creation.
  51250. *
  51251. * @private
  51252. * @param {number} op - A three.js constant defining the stencil operation.
  51253. * @return {string} The GPU stencil operation.
  51254. */
  51255. _getStencilOperation( op ) {
  51256. let stencilOperation;
  51257. switch ( op ) {
  51258. case KeepStencilOp:
  51259. stencilOperation = GPUStencilOperation.Keep;
  51260. break;
  51261. case ZeroStencilOp:
  51262. stencilOperation = GPUStencilOperation.Zero;
  51263. break;
  51264. case ReplaceStencilOp:
  51265. stencilOperation = GPUStencilOperation.Replace;
  51266. break;
  51267. case InvertStencilOp:
  51268. stencilOperation = GPUStencilOperation.Invert;
  51269. break;
  51270. case IncrementStencilOp:
  51271. stencilOperation = GPUStencilOperation.IncrementClamp;
  51272. break;
  51273. case DecrementStencilOp:
  51274. stencilOperation = GPUStencilOperation.DecrementClamp;
  51275. break;
  51276. case IncrementWrapStencilOp:
  51277. stencilOperation = GPUStencilOperation.IncrementWrap;
  51278. break;
  51279. case DecrementWrapStencilOp:
  51280. stencilOperation = GPUStencilOperation.DecrementWrap;
  51281. break;
  51282. default:
  51283. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  51284. }
  51285. return stencilOperation;
  51286. }
  51287. /**
  51288. * Returns the GPU blend operation which is required for the pipeline creation.
  51289. *
  51290. * @private
  51291. * @param {number} blendEquation - A three.js constant defining the blend equation.
  51292. * @return {string} The GPU blend operation.
  51293. */
  51294. _getBlendOperation( blendEquation ) {
  51295. let blendOperation;
  51296. switch ( blendEquation ) {
  51297. case AddEquation:
  51298. blendOperation = GPUBlendOperation.Add;
  51299. break;
  51300. case SubtractEquation:
  51301. blendOperation = GPUBlendOperation.Subtract;
  51302. break;
  51303. case ReverseSubtractEquation:
  51304. blendOperation = GPUBlendOperation.ReverseSubtract;
  51305. break;
  51306. case MinEquation:
  51307. blendOperation = GPUBlendOperation.Min;
  51308. break;
  51309. case MaxEquation:
  51310. blendOperation = GPUBlendOperation.Max;
  51311. break;
  51312. default:
  51313. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  51314. }
  51315. return blendOperation;
  51316. }
  51317. /**
  51318. * Returns the primitive state as a descriptor object required
  51319. * for the pipeline creation.
  51320. *
  51321. * @private
  51322. * @param {Object3D} object - The 3D object.
  51323. * @param {BufferGeometry} geometry - The geometry.
  51324. * @param {Material} material - The material.
  51325. * @return {Object} The primitive state.
  51326. */
  51327. _getPrimitiveState( object, geometry, material ) {
  51328. const descriptor = {};
  51329. const utils = this.backend.utils;
  51330. descriptor.topology = utils.getPrimitiveTopology( object, material );
  51331. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  51332. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  51333. }
  51334. switch ( material.side ) {
  51335. case FrontSide:
  51336. descriptor.frontFace = GPUFrontFace.CCW;
  51337. descriptor.cullMode = GPUCullMode.Back;
  51338. break;
  51339. case BackSide:
  51340. descriptor.frontFace = GPUFrontFace.CCW;
  51341. descriptor.cullMode = GPUCullMode.Front;
  51342. break;
  51343. case DoubleSide:
  51344. descriptor.frontFace = GPUFrontFace.CCW;
  51345. descriptor.cullMode = GPUCullMode.None;
  51346. break;
  51347. default:
  51348. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  51349. break;
  51350. }
  51351. return descriptor;
  51352. }
  51353. /**
  51354. * Returns the GPU color write mask which is required for the pipeline creation.
  51355. *
  51356. * @private
  51357. * @param {Material} material - The material.
  51358. * @return {number} The GPU color write mask.
  51359. */
  51360. _getColorWriteMask( material ) {
  51361. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  51362. }
  51363. /**
  51364. * Returns the GPU depth compare function which is required for the pipeline creation.
  51365. *
  51366. * @private
  51367. * @param {Material} material - The material.
  51368. * @return {string} The GPU depth compare function.
  51369. */
  51370. _getDepthCompare( material ) {
  51371. let depthCompare;
  51372. if ( material.depthTest === false ) {
  51373. depthCompare = GPUCompareFunction.Always;
  51374. } else {
  51375. const depthFunc = material.depthFunc;
  51376. switch ( depthFunc ) {
  51377. case NeverDepth:
  51378. depthCompare = GPUCompareFunction.Never;
  51379. break;
  51380. case AlwaysDepth:
  51381. depthCompare = GPUCompareFunction.Always;
  51382. break;
  51383. case LessDepth:
  51384. depthCompare = GPUCompareFunction.Less;
  51385. break;
  51386. case LessEqualDepth:
  51387. depthCompare = GPUCompareFunction.LessEqual;
  51388. break;
  51389. case EqualDepth:
  51390. depthCompare = GPUCompareFunction.Equal;
  51391. break;
  51392. case GreaterEqualDepth:
  51393. depthCompare = GPUCompareFunction.GreaterEqual;
  51394. break;
  51395. case GreaterDepth:
  51396. depthCompare = GPUCompareFunction.Greater;
  51397. break;
  51398. case NotEqualDepth:
  51399. depthCompare = GPUCompareFunction.NotEqual;
  51400. break;
  51401. default:
  51402. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  51403. }
  51404. }
  51405. return depthCompare;
  51406. }
  51407. }
  51408. /**
  51409. * Manages a pool of WebGPU timestamp queries for performance measurement.
  51410. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  51411. *
  51412. * @augments TimestampQueryPool
  51413. */
  51414. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  51415. /**
  51416. * Creates a new WebGPU timestamp query pool.
  51417. *
  51418. * @param {GPUDevice} device - The WebGPU device to create queries on.
  51419. * @param {string} type - The type identifier for this query pool.
  51420. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  51421. */
  51422. constructor( device, type, maxQueries = 2048 ) {
  51423. super( maxQueries );
  51424. this.device = device;
  51425. this.type = type;
  51426. this.querySet = this.device.createQuerySet( {
  51427. type: 'timestamp',
  51428. count: this.maxQueries,
  51429. label: `queryset_global_timestamp_${type}`
  51430. } );
  51431. const bufferSize = this.maxQueries * 8;
  51432. this.resolveBuffer = this.device.createBuffer( {
  51433. label: `buffer_timestamp_resolve_${type}`,
  51434. size: bufferSize,
  51435. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  51436. } );
  51437. this.resultBuffer = this.device.createBuffer( {
  51438. label: `buffer_timestamp_result_${type}`,
  51439. size: bufferSize,
  51440. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51441. } );
  51442. }
  51443. /**
  51444. * Allocates a pair of queries for a given render context.
  51445. *
  51446. * @param {Object} renderContext - The render context to allocate queries for.
  51447. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  51448. */
  51449. allocateQueriesForContext( renderContext ) {
  51450. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  51451. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  51452. 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() } ).` );
  51453. return null;
  51454. }
  51455. const baseOffset = this.currentQueryIndex;
  51456. this.currentQueryIndex += 2;
  51457. this.queryOffsets.set( renderContext.id, baseOffset );
  51458. return baseOffset;
  51459. }
  51460. /**
  51461. * Asynchronously resolves all pending queries and returns the total duration.
  51462. * If there's already a pending resolve operation, returns that promise instead.
  51463. *
  51464. * @async
  51465. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  51466. */
  51467. async resolveQueriesAsync() {
  51468. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  51469. return this.lastValue;
  51470. }
  51471. if ( this.pendingResolve ) {
  51472. return this.pendingResolve;
  51473. }
  51474. this.pendingResolve = this._resolveQueries();
  51475. try {
  51476. const result = await this.pendingResolve;
  51477. return result;
  51478. } finally {
  51479. this.pendingResolve = null;
  51480. }
  51481. }
  51482. /**
  51483. * Internal method to resolve queries and calculate total duration.
  51484. *
  51485. * @async
  51486. * @private
  51487. * @returns {Promise<number>} The total duration in milliseconds.
  51488. */
  51489. async _resolveQueries() {
  51490. if ( this.isDisposed ) {
  51491. return this.lastValue;
  51492. }
  51493. try {
  51494. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  51495. return this.lastValue;
  51496. }
  51497. const currentOffsets = new Map( this.queryOffsets );
  51498. const queryCount = this.currentQueryIndex;
  51499. const bytesUsed = queryCount * 8;
  51500. // Reset state before GPU work
  51501. this.currentQueryIndex = 0;
  51502. this.queryOffsets.clear();
  51503. const commandEncoder = this.device.createCommandEncoder();
  51504. commandEncoder.resolveQuerySet(
  51505. this.querySet,
  51506. 0,
  51507. queryCount,
  51508. this.resolveBuffer,
  51509. 0
  51510. );
  51511. commandEncoder.copyBufferToBuffer(
  51512. this.resolveBuffer,
  51513. 0,
  51514. this.resultBuffer,
  51515. 0,
  51516. bytesUsed
  51517. );
  51518. const commandBuffer = commandEncoder.finish();
  51519. this.device.queue.submit( [ commandBuffer ] );
  51520. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  51521. return this.lastValue;
  51522. }
  51523. // Create and track the mapping operation
  51524. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  51525. if ( this.isDisposed ) {
  51526. if ( this.resultBuffer.mapState === 'mapped' ) {
  51527. this.resultBuffer.unmap();
  51528. }
  51529. return this.lastValue;
  51530. }
  51531. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  51532. let totalDuration = 0;
  51533. for ( const [ , baseOffset ] of currentOffsets ) {
  51534. const startTime = times[ baseOffset ];
  51535. const endTime = times[ baseOffset + 1 ];
  51536. const duration = Number( endTime - startTime ) / 1e6;
  51537. totalDuration += duration;
  51538. }
  51539. this.resultBuffer.unmap();
  51540. this.lastValue = totalDuration;
  51541. return totalDuration;
  51542. } catch ( error ) {
  51543. console.error( 'Error resolving queries:', error );
  51544. if ( this.resultBuffer.mapState === 'mapped' ) {
  51545. this.resultBuffer.unmap();
  51546. }
  51547. return this.lastValue;
  51548. }
  51549. }
  51550. /**
  51551. * Dispose of the query pool.
  51552. *
  51553. * @async
  51554. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  51555. */
  51556. async dispose() {
  51557. if ( this.isDisposed ) {
  51558. return;
  51559. }
  51560. this.isDisposed = true;
  51561. // Wait for pending resolve operation
  51562. if ( this.pendingResolve ) {
  51563. try {
  51564. await this.pendingResolve;
  51565. } catch ( error ) {
  51566. console.error( 'Error waiting for pending resolve:', error );
  51567. }
  51568. }
  51569. // Ensure buffer is unmapped before destroying
  51570. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  51571. try {
  51572. this.resultBuffer.unmap();
  51573. } catch ( error ) {
  51574. console.error( 'Error unmapping buffer:', error );
  51575. }
  51576. }
  51577. // Destroy resources
  51578. if ( this.querySet ) {
  51579. this.querySet.destroy();
  51580. this.querySet = null;
  51581. }
  51582. if ( this.resolveBuffer ) {
  51583. this.resolveBuffer.destroy();
  51584. this.resolveBuffer = null;
  51585. }
  51586. if ( this.resultBuffer ) {
  51587. this.resultBuffer.destroy();
  51588. this.resultBuffer = null;
  51589. }
  51590. this.queryOffsets.clear();
  51591. this.pendingResolve = null;
  51592. }
  51593. }
  51594. /*// debugger tools
  51595. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  51596. //*/
  51597. /**
  51598. * A backend implementation targeting WebGPU.
  51599. *
  51600. * @private
  51601. * @augments Backend
  51602. */
  51603. class WebGPUBackend extends Backend {
  51604. /**
  51605. * WebGPUBackend options.
  51606. *
  51607. * @typedef {Object} WebGPUBackend~Options
  51608. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  51609. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  51610. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  51611. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  51612. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  51613. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  51614. * @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.
  51615. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  51616. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  51617. * @property {string} [powerPreference=undefined] - The power preference.
  51618. * @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.
  51619. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  51620. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  51621. */
  51622. /**
  51623. * Constructs a new WebGPU backend.
  51624. *
  51625. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  51626. */
  51627. constructor( parameters = {} ) {
  51628. super( parameters );
  51629. /**
  51630. * This flag can be used for type testing.
  51631. *
  51632. * @type {boolean}
  51633. * @readonly
  51634. * @default true
  51635. */
  51636. this.isWebGPUBackend = true;
  51637. // some parameters require default values other than "undefined"
  51638. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  51639. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  51640. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  51641. /**
  51642. * Indicates whether the backend is in compatibility mode or not.
  51643. * @type {boolean}
  51644. * @default false
  51645. */
  51646. this.compatibilityMode = this.parameters.compatibilityMode;
  51647. /**
  51648. * A reference to the device.
  51649. *
  51650. * @type {?GPUDevice}
  51651. * @default null
  51652. */
  51653. this.device = null;
  51654. /**
  51655. * A reference to the context.
  51656. *
  51657. * @type {?GPUCanvasContext}
  51658. * @default null
  51659. */
  51660. this.context = null;
  51661. /**
  51662. * A reference to the color attachment of the default framebuffer.
  51663. *
  51664. * @type {?GPUTexture}
  51665. * @default null
  51666. */
  51667. this.colorBuffer = null;
  51668. /**
  51669. * A reference to the default render pass descriptor.
  51670. *
  51671. * @type {?Object}
  51672. * @default null
  51673. */
  51674. this.defaultRenderPassdescriptor = null;
  51675. /**
  51676. * A reference to a backend module holding common utility functions.
  51677. *
  51678. * @type {WebGPUUtils}
  51679. */
  51680. this.utils = new WebGPUUtils( this );
  51681. /**
  51682. * A reference to a backend module holding shader attribute-related
  51683. * utility functions.
  51684. *
  51685. * @type {WebGPUAttributeUtils}
  51686. */
  51687. this.attributeUtils = new WebGPUAttributeUtils( this );
  51688. /**
  51689. * A reference to a backend module holding shader binding-related
  51690. * utility functions.
  51691. *
  51692. * @type {WebGPUBindingUtils}
  51693. */
  51694. this.bindingUtils = new WebGPUBindingUtils( this );
  51695. /**
  51696. * A reference to a backend module holding shader pipeline-related
  51697. * utility functions.
  51698. *
  51699. * @type {WebGPUPipelineUtils}
  51700. */
  51701. this.pipelineUtils = new WebGPUPipelineUtils( this );
  51702. /**
  51703. * A reference to a backend module holding shader texture-related
  51704. * utility functions.
  51705. *
  51706. * @type {WebGPUTextureUtils}
  51707. */
  51708. this.textureUtils = new WebGPUTextureUtils( this );
  51709. /**
  51710. * A map that manages the resolve buffers for occlusion queries.
  51711. *
  51712. * @type {Map<number,GPUBuffer>}
  51713. */
  51714. this.occludedResolveCache = new Map();
  51715. }
  51716. /**
  51717. * Initializes the backend so it is ready for usage.
  51718. *
  51719. * @async
  51720. * @param {Renderer} renderer - The renderer.
  51721. * @return {Promise} A Promise that resolves when the backend has been initialized.
  51722. */
  51723. async init( renderer ) {
  51724. await super.init( renderer );
  51725. //
  51726. const parameters = this.parameters;
  51727. // create the device if it is not passed with parameters
  51728. let device;
  51729. if ( parameters.device === undefined ) {
  51730. const adapterOptions = {
  51731. powerPreference: parameters.powerPreference,
  51732. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  51733. };
  51734. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  51735. if ( adapter === null ) {
  51736. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  51737. }
  51738. // feature support
  51739. const features = Object.values( GPUFeatureName );
  51740. const supportedFeatures = [];
  51741. for ( const name of features ) {
  51742. if ( adapter.features.has( name ) ) {
  51743. supportedFeatures.push( name );
  51744. }
  51745. }
  51746. const deviceDescriptor = {
  51747. requiredFeatures: supportedFeatures,
  51748. requiredLimits: parameters.requiredLimits
  51749. };
  51750. device = await adapter.requestDevice( deviceDescriptor );
  51751. } else {
  51752. device = parameters.device;
  51753. }
  51754. device.lost.then( ( info ) => {
  51755. const deviceLossInfo = {
  51756. api: 'WebGPU',
  51757. message: info.message || 'Unknown reason',
  51758. reason: info.reason || null,
  51759. originalEvent: info
  51760. };
  51761. renderer.onDeviceLost( deviceLossInfo );
  51762. } );
  51763. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  51764. this.device = device;
  51765. this.context = context;
  51766. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  51767. const toneMappingMode = ColorManagement.getToneMappingMode( this.renderer.outputColorSpace );
  51768. this.context.configure( {
  51769. device: this.device,
  51770. format: this.utils.getPreferredCanvasFormat(),
  51771. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  51772. alphaMode: alphaMode,
  51773. toneMapping: {
  51774. mode: toneMappingMode
  51775. }
  51776. } );
  51777. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  51778. this.updateSize();
  51779. }
  51780. /**
  51781. * The coordinate system of the backend.
  51782. *
  51783. * @type {number}
  51784. * @readonly
  51785. */
  51786. get coordinateSystem() {
  51787. return WebGPUCoordinateSystem;
  51788. }
  51789. /**
  51790. * This method performs a readback operation by moving buffer data from
  51791. * a storage buffer attribute from the GPU to the CPU.
  51792. *
  51793. * @async
  51794. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  51795. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  51796. */
  51797. async getArrayBufferAsync( attribute ) {
  51798. return await this.attributeUtils.getArrayBufferAsync( attribute );
  51799. }
  51800. /**
  51801. * Returns the backend's rendering context.
  51802. *
  51803. * @return {GPUCanvasContext} The rendering context.
  51804. */
  51805. getContext() {
  51806. return this.context;
  51807. }
  51808. /**
  51809. * Returns the default render pass descriptor.
  51810. *
  51811. * In WebGPU, the default framebuffer must be configured
  51812. * like custom framebuffers so the backend needs a render
  51813. * pass descriptor even when rendering directly to screen.
  51814. *
  51815. * @private
  51816. * @return {Object} The render pass descriptor.
  51817. */
  51818. _getDefaultRenderPassDescriptor() {
  51819. let descriptor = this.defaultRenderPassdescriptor;
  51820. if ( descriptor === null ) {
  51821. const renderer = this.renderer;
  51822. descriptor = {
  51823. colorAttachments: [ {
  51824. view: null
  51825. } ],
  51826. };
  51827. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  51828. descriptor.depthStencilAttachment = {
  51829. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  51830. };
  51831. }
  51832. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51833. if ( this.renderer.samples > 0 ) {
  51834. colorAttachment.view = this.colorBuffer.createView();
  51835. } else {
  51836. colorAttachment.resolveTarget = undefined;
  51837. }
  51838. this.defaultRenderPassdescriptor = descriptor;
  51839. }
  51840. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51841. if ( this.renderer.samples > 0 ) {
  51842. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  51843. } else {
  51844. colorAttachment.view = this.context.getCurrentTexture().createView();
  51845. }
  51846. return descriptor;
  51847. }
  51848. /**
  51849. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  51850. *
  51851. * @param {RenderContext} renderContext - The render context.
  51852. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  51853. *
  51854. * @private
  51855. */
  51856. _isRenderCameraDepthArray( renderContext ) {
  51857. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  51858. }
  51859. /**
  51860. * Returns the render pass descriptor for the given render context.
  51861. *
  51862. * @private
  51863. * @param {RenderContext} renderContext - The render context.
  51864. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  51865. * @return {Object} The render pass descriptor.
  51866. */
  51867. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  51868. const renderTarget = renderContext.renderTarget;
  51869. const renderTargetData = this.get( renderTarget );
  51870. let descriptors = renderTargetData.descriptors;
  51871. if ( descriptors === undefined ||
  51872. renderTargetData.width !== renderTarget.width ||
  51873. renderTargetData.height !== renderTarget.height ||
  51874. renderTargetData.samples !== renderTarget.samples
  51875. ) {
  51876. descriptors = {};
  51877. renderTargetData.descriptors = descriptors;
  51878. }
  51879. const cacheKey = renderContext.getCacheKey();
  51880. let descriptorBase = descriptors[ cacheKey ];
  51881. if ( descriptorBase === undefined ) {
  51882. const textures = renderContext.textures;
  51883. const textureViews = [];
  51884. let sliceIndex;
  51885. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  51886. for ( let i = 0; i < textures.length; i ++ ) {
  51887. const textureData = this.get( textures[ i ] );
  51888. const viewDescriptor = {
  51889. label: `colorAttachment_${ i }`,
  51890. baseMipLevel: renderContext.activeMipmapLevel,
  51891. mipLevelCount: 1,
  51892. baseArrayLayer: renderContext.activeCubeFace,
  51893. arrayLayerCount: 1,
  51894. dimension: GPUTextureViewDimension.TwoD
  51895. };
  51896. if ( renderTarget.isRenderTarget3D ) {
  51897. sliceIndex = renderContext.activeCubeFace;
  51898. viewDescriptor.baseArrayLayer = 0;
  51899. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  51900. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  51901. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  51902. if ( isRenderCameraDepthArray === true ) {
  51903. const cameras = renderContext.camera.cameras;
  51904. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  51905. const layerViewDescriptor = {
  51906. ...viewDescriptor,
  51907. baseArrayLayer: layer,
  51908. arrayLayerCount: 1,
  51909. dimension: GPUTextureViewDimension.TwoD
  51910. };
  51911. const textureView = textureData.texture.createView( layerViewDescriptor );
  51912. textureViews.push( {
  51913. view: textureView,
  51914. resolveTarget: undefined,
  51915. depthSlice: undefined
  51916. } );
  51917. }
  51918. } else {
  51919. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  51920. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  51921. }
  51922. }
  51923. if ( isRenderCameraDepthArray !== true ) {
  51924. const textureView = textureData.texture.createView( viewDescriptor );
  51925. let view, resolveTarget;
  51926. if ( textureData.msaaTexture !== undefined ) {
  51927. view = textureData.msaaTexture.createView();
  51928. resolveTarget = textureView;
  51929. } else {
  51930. view = textureView;
  51931. resolveTarget = undefined;
  51932. }
  51933. textureViews.push( {
  51934. view,
  51935. resolveTarget,
  51936. depthSlice: sliceIndex
  51937. } );
  51938. }
  51939. }
  51940. descriptorBase = { textureViews };
  51941. if ( renderContext.depth ) {
  51942. const depthTextureData = this.get( renderContext.depthTexture );
  51943. const options = {};
  51944. if ( renderContext.depthTexture.isArrayTexture ) {
  51945. options.dimension = GPUTextureViewDimension.TwoD;
  51946. options.arrayLayerCount = 1;
  51947. options.baseArrayLayer = renderContext.activeCubeFace;
  51948. }
  51949. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  51950. }
  51951. descriptors[ cacheKey ] = descriptorBase;
  51952. renderTargetData.width = renderTarget.width;
  51953. renderTargetData.height = renderTarget.height;
  51954. renderTargetData.samples = renderTarget.samples;
  51955. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  51956. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  51957. }
  51958. const descriptor = {
  51959. colorAttachments: []
  51960. };
  51961. // Apply dynamic properties to cached views
  51962. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  51963. const viewInfo = descriptorBase.textureViews[ i ];
  51964. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  51965. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  51966. clearValue = colorAttachmentsConfig.clearValue;
  51967. }
  51968. descriptor.colorAttachments.push( {
  51969. view: viewInfo.view,
  51970. depthSlice: viewInfo.depthSlice,
  51971. resolveTarget: viewInfo.resolveTarget,
  51972. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  51973. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  51974. clearValue: clearValue
  51975. } );
  51976. }
  51977. if ( descriptorBase.depthStencilView ) {
  51978. descriptor.depthStencilAttachment = {
  51979. view: descriptorBase.depthStencilView
  51980. };
  51981. }
  51982. return descriptor;
  51983. }
  51984. /**
  51985. * This method is executed at the beginning of a render call and prepares
  51986. * the WebGPU state for upcoming render calls
  51987. *
  51988. * @param {RenderContext} renderContext - The render context.
  51989. */
  51990. beginRender( renderContext ) {
  51991. const renderContextData = this.get( renderContext );
  51992. const device = this.device;
  51993. const occlusionQueryCount = renderContext.occlusionQueryCount;
  51994. let occlusionQuerySet;
  51995. if ( occlusionQueryCount > 0 ) {
  51996. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  51997. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  51998. // Get a reference to the array of objects with queries. The renderContextData property
  51999. // can be changed by another render pass before the buffer.mapAsyc() completes.
  52000. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  52001. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  52002. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  52003. //
  52004. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  52005. renderContextData.occlusionQuerySet = occlusionQuerySet;
  52006. renderContextData.occlusionQueryIndex = 0;
  52007. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  52008. renderContextData.lastOcclusionObject = null;
  52009. }
  52010. let descriptor;
  52011. if ( renderContext.textures === null ) {
  52012. descriptor = this._getDefaultRenderPassDescriptor();
  52013. } else {
  52014. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  52015. }
  52016. this.initTimestampQuery( renderContext, descriptor );
  52017. descriptor.occlusionQuerySet = occlusionQuerySet;
  52018. const depthStencilAttachment = descriptor.depthStencilAttachment;
  52019. if ( renderContext.textures !== null ) {
  52020. const colorAttachments = descriptor.colorAttachments;
  52021. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  52022. const colorAttachment = colorAttachments[ i ];
  52023. if ( renderContext.clearColor ) {
  52024. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  52025. colorAttachment.loadOp = GPULoadOp.Clear;
  52026. } else {
  52027. colorAttachment.loadOp = GPULoadOp.Load;
  52028. }
  52029. colorAttachment.storeOp = GPUStoreOp.Store;
  52030. }
  52031. } else {
  52032. const colorAttachment = descriptor.colorAttachments[ 0 ];
  52033. if ( renderContext.clearColor ) {
  52034. colorAttachment.clearValue = renderContext.clearColorValue;
  52035. colorAttachment.loadOp = GPULoadOp.Clear;
  52036. } else {
  52037. colorAttachment.loadOp = GPULoadOp.Load;
  52038. }
  52039. colorAttachment.storeOp = GPUStoreOp.Store;
  52040. }
  52041. //
  52042. if ( renderContext.depth ) {
  52043. if ( renderContext.clearDepth ) {
  52044. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  52045. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  52046. } else {
  52047. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  52048. }
  52049. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52050. }
  52051. if ( renderContext.stencil ) {
  52052. if ( renderContext.clearStencil ) {
  52053. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  52054. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  52055. } else {
  52056. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  52057. }
  52058. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52059. }
  52060. //
  52061. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  52062. // shadow arrays - prepare bundle encoders for each camera in an array camera
  52063. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  52064. const cameras = renderContext.camera.cameras;
  52065. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  52066. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  52067. } else {
  52068. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  52069. }
  52070. // Create bundle encoders for each layer
  52071. renderContextData.bundleEncoders = [];
  52072. renderContextData.bundleSets = [];
  52073. // Create separate bundle encoders for each camera in the array
  52074. for ( let i = 0; i < cameras.length; i ++ ) {
  52075. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  52076. renderContext,
  52077. 'renderBundleArrayCamera_' + i
  52078. );
  52079. // Initialize state tracking for this bundle
  52080. const bundleSets = {
  52081. attributes: {},
  52082. bindingGroups: [],
  52083. pipeline: null,
  52084. index: null
  52085. };
  52086. renderContextData.bundleEncoders.push( bundleEncoder );
  52087. renderContextData.bundleSets.push( bundleSets );
  52088. }
  52089. // We'll complete the bundles in finishRender
  52090. renderContextData.currentPass = null;
  52091. } else {
  52092. const currentPass = encoder.beginRenderPass( descriptor );
  52093. renderContextData.currentPass = currentPass;
  52094. if ( renderContext.viewport ) {
  52095. this.updateViewport( renderContext );
  52096. }
  52097. if ( renderContext.scissor ) {
  52098. const { x, y, width, height } = renderContext.scissorValue;
  52099. currentPass.setScissorRect( x, y, width, height );
  52100. }
  52101. }
  52102. //
  52103. renderContextData.descriptor = descriptor;
  52104. renderContextData.encoder = encoder;
  52105. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52106. renderContextData.renderBundles = [];
  52107. }
  52108. /**
  52109. * This method creates layer descriptors for each camera in an array camera
  52110. * to prepare for rendering to a depth array texture.
  52111. *
  52112. * @param {RenderContext} renderContext - The render context.
  52113. * @param {Object} renderContextData - The render context data.
  52114. * @param {Object} descriptor - The render pass descriptor.
  52115. * @param {ArrayCamera} cameras - The array camera.
  52116. *
  52117. * @private
  52118. */
  52119. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  52120. const depthStencilAttachment = descriptor.depthStencilAttachment;
  52121. renderContextData.layerDescriptors = [];
  52122. const depthTextureData = this.get( renderContext.depthTexture );
  52123. if ( ! depthTextureData.viewCache ) {
  52124. depthTextureData.viewCache = [];
  52125. }
  52126. for ( let i = 0; i < cameras.length; i ++ ) {
  52127. const layerDescriptor = {
  52128. ...descriptor,
  52129. colorAttachments: [ {
  52130. ...descriptor.colorAttachments[ 0 ],
  52131. view: descriptor.colorAttachments[ i ].view
  52132. } ]
  52133. };
  52134. if ( descriptor.depthStencilAttachment ) {
  52135. const layerIndex = i;
  52136. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  52137. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  52138. dimension: GPUTextureViewDimension.TwoD,
  52139. baseArrayLayer: i,
  52140. arrayLayerCount: 1
  52141. } );
  52142. }
  52143. layerDescriptor.depthStencilAttachment = {
  52144. view: depthTextureData.viewCache[ layerIndex ],
  52145. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  52146. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  52147. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  52148. };
  52149. if ( renderContext.stencil ) {
  52150. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  52151. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  52152. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  52153. }
  52154. } else {
  52155. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  52156. }
  52157. renderContextData.layerDescriptors.push( layerDescriptor );
  52158. }
  52159. }
  52160. /**
  52161. * This method updates the layer descriptors for each camera in an array camera
  52162. * to prepare for rendering to a depth array texture.
  52163. *
  52164. * @param {RenderContext} renderContext - The render context.
  52165. * @param {Object} renderContextData - The render context data.
  52166. * @param {ArrayCamera} cameras - The array camera.
  52167. *
  52168. */
  52169. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  52170. for ( let i = 0; i < cameras.length; i ++ ) {
  52171. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  52172. if ( layerDescriptor.depthStencilAttachment ) {
  52173. const depthAttachment = layerDescriptor.depthStencilAttachment;
  52174. if ( renderContext.depth ) {
  52175. if ( renderContext.clearDepth ) {
  52176. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  52177. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  52178. } else {
  52179. depthAttachment.depthLoadOp = GPULoadOp.Load;
  52180. }
  52181. }
  52182. if ( renderContext.stencil ) {
  52183. if ( renderContext.clearStencil ) {
  52184. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  52185. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  52186. } else {
  52187. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  52188. }
  52189. }
  52190. }
  52191. }
  52192. }
  52193. /**
  52194. * This method is executed at the end of a render call and finalizes work
  52195. * after draw calls.
  52196. *
  52197. * @param {RenderContext} renderContext - The render context.
  52198. */
  52199. finishRender( renderContext ) {
  52200. const renderContextData = this.get( renderContext );
  52201. const occlusionQueryCount = renderContext.occlusionQueryCount;
  52202. if ( renderContextData.renderBundles.length > 0 ) {
  52203. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  52204. }
  52205. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  52206. renderContextData.currentPass.endOcclusionQuery();
  52207. }
  52208. // shadow arrays - Execute bundles for each layer
  52209. const encoder = renderContextData.encoder;
  52210. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  52211. const bundles = [];
  52212. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  52213. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  52214. bundles.push( bundleEncoder.finish() );
  52215. }
  52216. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  52217. if ( i < bundles.length ) {
  52218. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  52219. const renderPass = encoder.beginRenderPass( layerDescriptor );
  52220. if ( renderContext.viewport ) {
  52221. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  52222. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  52223. }
  52224. if ( renderContext.scissor ) {
  52225. const { x, y, width, height } = renderContext.scissorValue;
  52226. renderPass.setScissorRect( x, y, width, height );
  52227. }
  52228. renderPass.executeBundles( [ bundles[ i ] ] );
  52229. renderPass.end();
  52230. }
  52231. }
  52232. } else if ( renderContextData.currentPass ) {
  52233. renderContextData.currentPass.end();
  52234. }
  52235. if ( occlusionQueryCount > 0 ) {
  52236. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  52237. //
  52238. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  52239. if ( queryResolveBuffer === undefined ) {
  52240. queryResolveBuffer = this.device.createBuffer(
  52241. {
  52242. size: bufferSize,
  52243. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  52244. }
  52245. );
  52246. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  52247. }
  52248. //
  52249. const readBuffer = this.device.createBuffer(
  52250. {
  52251. size: bufferSize,
  52252. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52253. }
  52254. );
  52255. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  52256. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  52257. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  52258. renderContextData.occlusionQueryBuffer = readBuffer;
  52259. //
  52260. this.resolveOccludedAsync( renderContext );
  52261. }
  52262. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  52263. //
  52264. if ( renderContext.textures !== null ) {
  52265. const textures = renderContext.textures;
  52266. for ( let i = 0; i < textures.length; i ++ ) {
  52267. const texture = textures[ i ];
  52268. if ( texture.generateMipmaps === true ) {
  52269. this.textureUtils.generateMipmaps( texture );
  52270. }
  52271. }
  52272. }
  52273. }
  52274. /**
  52275. * Returns `true` if the given 3D object is fully occluded by other
  52276. * 3D objects in the scene.
  52277. *
  52278. * @param {RenderContext} renderContext - The render context.
  52279. * @param {Object3D} object - The 3D object to test.
  52280. * @return {boolean} Whether the 3D object is fully occluded or not.
  52281. */
  52282. isOccluded( renderContext, object ) {
  52283. const renderContextData = this.get( renderContext );
  52284. return renderContextData.occluded && renderContextData.occluded.has( object );
  52285. }
  52286. /**
  52287. * This method processes the result of occlusion queries and writes it
  52288. * into render context data.
  52289. *
  52290. * @async
  52291. * @param {RenderContext} renderContext - The render context.
  52292. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  52293. */
  52294. async resolveOccludedAsync( renderContext ) {
  52295. const renderContextData = this.get( renderContext );
  52296. // handle occlusion query results
  52297. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  52298. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  52299. const occluded = new WeakSet();
  52300. renderContextData.currentOcclusionQueryObjects = null;
  52301. renderContextData.currentOcclusionQueryBuffer = null;
  52302. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  52303. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  52304. const results = new BigUint64Array( buffer );
  52305. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  52306. if ( results[ i ] === BigInt( 0 ) ) {
  52307. occluded.add( currentOcclusionQueryObjects[ i ] );
  52308. }
  52309. }
  52310. currentOcclusionQueryBuffer.destroy();
  52311. renderContextData.occluded = occluded;
  52312. }
  52313. }
  52314. /**
  52315. * Updates the viewport with the values from the given render context.
  52316. *
  52317. * @param {RenderContext} renderContext - The render context.
  52318. */
  52319. updateViewport( renderContext ) {
  52320. const { currentPass } = this.get( renderContext );
  52321. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  52322. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  52323. }
  52324. /**
  52325. * Returns the clear color and alpha into a single
  52326. * color object.
  52327. *
  52328. * @return {Color4} The clear color.
  52329. */
  52330. getClearColor() {
  52331. const clearColor = super.getClearColor();
  52332. // only premultiply alpha when alphaMode is "premultiplied"
  52333. if ( this.renderer.alpha === true ) {
  52334. clearColor.r *= clearColor.a;
  52335. clearColor.g *= clearColor.a;
  52336. clearColor.b *= clearColor.a;
  52337. }
  52338. return clearColor;
  52339. }
  52340. /**
  52341. * Performs a clear operation.
  52342. *
  52343. * @param {boolean} color - Whether the color buffer should be cleared or not.
  52344. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  52345. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  52346. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  52347. */
  52348. clear( color, depth, stencil, renderTargetContext = null ) {
  52349. const device = this.device;
  52350. const renderer = this.renderer;
  52351. let colorAttachments = [];
  52352. let depthStencilAttachment;
  52353. let clearValue;
  52354. let supportsDepth;
  52355. let supportsStencil;
  52356. if ( color ) {
  52357. const clearColor = this.getClearColor();
  52358. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  52359. }
  52360. if ( renderTargetContext === null ) {
  52361. supportsDepth = renderer.depth;
  52362. supportsStencil = renderer.stencil;
  52363. const descriptor = this._getDefaultRenderPassDescriptor();
  52364. if ( color ) {
  52365. colorAttachments = descriptor.colorAttachments;
  52366. const colorAttachment = colorAttachments[ 0 ];
  52367. colorAttachment.clearValue = clearValue;
  52368. colorAttachment.loadOp = GPULoadOp.Clear;
  52369. colorAttachment.storeOp = GPUStoreOp.Store;
  52370. }
  52371. if ( supportsDepth || supportsStencil ) {
  52372. depthStencilAttachment = descriptor.depthStencilAttachment;
  52373. }
  52374. } else {
  52375. supportsDepth = renderTargetContext.depth;
  52376. supportsStencil = renderTargetContext.stencil;
  52377. const clearConfig = {
  52378. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  52379. clearValue: color ? clearValue : undefined
  52380. };
  52381. if ( supportsDepth ) {
  52382. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  52383. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  52384. clearConfig.depthStoreOp = GPUStoreOp.Store;
  52385. }
  52386. if ( supportsStencil ) {
  52387. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  52388. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  52389. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  52390. }
  52391. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  52392. colorAttachments = descriptor.colorAttachments;
  52393. depthStencilAttachment = descriptor.depthStencilAttachment;
  52394. }
  52395. if ( supportsDepth && depthStencilAttachment ) {
  52396. if ( depth ) {
  52397. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  52398. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  52399. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52400. } else {
  52401. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  52402. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52403. }
  52404. }
  52405. //
  52406. if ( supportsStencil && depthStencilAttachment ) {
  52407. if ( stencil ) {
  52408. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  52409. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  52410. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52411. } else {
  52412. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  52413. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52414. }
  52415. }
  52416. //
  52417. const encoder = device.createCommandEncoder( { label: 'clear' } );
  52418. const currentPass = encoder.beginRenderPass( {
  52419. colorAttachments,
  52420. depthStencilAttachment
  52421. } );
  52422. currentPass.end();
  52423. device.queue.submit( [ encoder.finish() ] );
  52424. }
  52425. // compute
  52426. /**
  52427. * This method is executed at the beginning of a compute call and
  52428. * prepares the state for upcoming compute tasks.
  52429. *
  52430. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  52431. */
  52432. beginCompute( computeGroup ) {
  52433. const groupGPU = this.get( computeGroup );
  52434. const descriptor = {
  52435. label: 'computeGroup_' + computeGroup.id
  52436. };
  52437. this.initTimestampQuery( computeGroup, descriptor );
  52438. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  52439. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  52440. }
  52441. /**
  52442. * Executes a compute command for the given compute node.
  52443. *
  52444. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  52445. * @param {Node} computeNode - The compute node.
  52446. * @param {Array<BindGroup>} bindings - The bindings.
  52447. * @param {ComputePipeline} pipeline - The compute pipeline.
  52448. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  52449. */
  52450. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  52451. const computeNodeData = this.get( computeNode );
  52452. const { passEncoderGPU } = this.get( computeGroup );
  52453. // pipeline
  52454. const pipelineGPU = this.get( pipeline ).pipeline;
  52455. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  52456. // bind groups
  52457. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  52458. const bindGroup = bindings[ i ];
  52459. const bindingsData = this.get( bindGroup );
  52460. passEncoderGPU.setBindGroup( i, bindingsData.group );
  52461. }
  52462. let dispatchSize;
  52463. if ( dispatchSizeOrCount === null ) {
  52464. dispatchSizeOrCount = computeNode.count;
  52465. }
  52466. if ( typeof dispatchSizeOrCount === 'number' ) {
  52467. // If a single number is given, we calculate the dispatch size based on the workgroup size
  52468. const count = dispatchSizeOrCount;
  52469. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  52470. // cache dispatch size to avoid recalculating it every time
  52471. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  52472. computeNodeData.count = count;
  52473. const workgroupSize = computeNode.workgroupSize;
  52474. let size = workgroupSize[ 0 ];
  52475. for ( let i = 1; i < workgroupSize.length; i ++ )
  52476. size *= workgroupSize[ i ];
  52477. const dispatchCount = Math.ceil( count / size );
  52478. //
  52479. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  52480. dispatchSize = [ dispatchCount, 1, 1 ];
  52481. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  52482. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  52483. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  52484. }
  52485. computeNodeData.dispatchSize = dispatchSize;
  52486. }
  52487. dispatchSize = computeNodeData.dispatchSize;
  52488. } else {
  52489. dispatchSize = dispatchSizeOrCount;
  52490. }
  52491. //
  52492. passEncoderGPU.dispatchWorkgroups(
  52493. dispatchSize[ 0 ],
  52494. dispatchSize[ 1 ] || 1,
  52495. dispatchSize[ 2 ] || 1
  52496. );
  52497. }
  52498. /**
  52499. * This method is executed at the end of a compute call and
  52500. * finalizes work after compute tasks.
  52501. *
  52502. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  52503. */
  52504. finishCompute( computeGroup ) {
  52505. const groupData = this.get( computeGroup );
  52506. groupData.passEncoderGPU.end();
  52507. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  52508. }
  52509. /**
  52510. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  52511. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  52512. *
  52513. * @async
  52514. * @return {Promise} A Promise that resolves when synchronization has been finished.
  52515. */
  52516. async waitForGPU() {
  52517. await this.device.queue.onSubmittedWorkDone();
  52518. }
  52519. // render object
  52520. /**
  52521. * Executes a draw command for the given render object.
  52522. *
  52523. * @param {RenderObject} renderObject - The render object to draw.
  52524. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  52525. */
  52526. draw( renderObject, info ) {
  52527. const { object, material, context, pipeline } = renderObject;
  52528. const bindings = renderObject.getBindings();
  52529. const renderContextData = this.get( context );
  52530. const pipelineGPU = this.get( pipeline ).pipeline;
  52531. const index = renderObject.getIndex();
  52532. const hasIndex = ( index !== null );
  52533. const drawParams = renderObject.getDrawParameters();
  52534. if ( drawParams === null ) return;
  52535. // pipeline
  52536. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  52537. // pipeline
  52538. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  52539. currentSets.pipeline = pipelineGPU;
  52540. // bind groups
  52541. const currentBindingGroups = currentSets.bindingGroups;
  52542. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  52543. const bindGroup = bindings[ i ];
  52544. const bindingsData = this.get( bindGroup );
  52545. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  52546. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  52547. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  52548. }
  52549. }
  52550. // attributes
  52551. // index
  52552. if ( hasIndex === true ) {
  52553. if ( currentSets.index !== index ) {
  52554. const buffer = this.get( index ).buffer;
  52555. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  52556. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  52557. currentSets.index = index;
  52558. }
  52559. }
  52560. // vertex buffers
  52561. const vertexBuffers = renderObject.getVertexBuffers();
  52562. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  52563. const vertexBuffer = vertexBuffers[ i ];
  52564. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  52565. const buffer = this.get( vertexBuffer ).buffer;
  52566. passEncoderGPU.setVertexBuffer( i, buffer );
  52567. currentSets.attributes[ i ] = vertexBuffer;
  52568. }
  52569. }
  52570. // stencil
  52571. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  52572. passEncoderGPU.setStencilReference( material.stencilRef );
  52573. renderContextData.currentStencilRef = material.stencilRef;
  52574. }
  52575. };
  52576. // Define draw function
  52577. const draw = ( passEncoderGPU, currentSets ) => {
  52578. setPipelineAndBindings( passEncoderGPU, currentSets );
  52579. if ( object.isBatchedMesh === true ) {
  52580. const starts = object._multiDrawStarts;
  52581. const counts = object._multiDrawCounts;
  52582. const drawCount = object._multiDrawCount;
  52583. const drawInstances = object._multiDrawInstances;
  52584. if ( drawInstances !== null ) {
  52585. // @deprecated, r174
  52586. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  52587. }
  52588. for ( let i = 0; i < drawCount; i ++ ) {
  52589. const count = drawInstances ? drawInstances[ i ] : 1;
  52590. const firstInstance = count > 1 ? 0 : i;
  52591. if ( hasIndex === true ) {
  52592. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  52593. } else {
  52594. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  52595. }
  52596. info.update( object, counts[ i ], count );
  52597. }
  52598. } else if ( hasIndex === true ) {
  52599. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  52600. const indirect = renderObject.getIndirect();
  52601. if ( indirect !== null ) {
  52602. const buffer = this.get( indirect ).buffer;
  52603. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  52604. } else {
  52605. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  52606. }
  52607. info.update( object, indexCount, instanceCount );
  52608. } else {
  52609. const { vertexCount, instanceCount, firstVertex } = drawParams;
  52610. const indirect = renderObject.getIndirect();
  52611. if ( indirect !== null ) {
  52612. const buffer = this.get( indirect ).buffer;
  52613. passEncoderGPU.drawIndirect( buffer, 0 );
  52614. } else {
  52615. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  52616. }
  52617. info.update( object, vertexCount, instanceCount );
  52618. }
  52619. };
  52620. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  52621. const cameraData = this.get( renderObject.camera );
  52622. const cameras = renderObject.camera.cameras;
  52623. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  52624. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  52625. const bindingsData = this.get( cameraIndex );
  52626. const indexesGPU = [];
  52627. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  52628. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  52629. data[ 0 ] = i;
  52630. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  52631. indexesGPU.push( bindGroupIndex );
  52632. }
  52633. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  52634. }
  52635. const pixelRatio = this.renderer.getPixelRatio();
  52636. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  52637. const subCamera = cameras[ i ];
  52638. if ( object.layers.test( subCamera.layers ) ) {
  52639. const vp = subCamera.viewport;
  52640. let pass = renderContextData.currentPass;
  52641. let sets = renderContextData.currentSets;
  52642. if ( renderContextData.bundleEncoders ) {
  52643. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  52644. const bundleSets = renderContextData.bundleSets[ i ];
  52645. pass = bundleEncoder;
  52646. sets = bundleSets;
  52647. }
  52648. if ( vp ) {
  52649. pass.setViewport(
  52650. Math.floor( vp.x * pixelRatio ),
  52651. Math.floor( vp.y * pixelRatio ),
  52652. Math.floor( vp.width * pixelRatio ),
  52653. Math.floor( vp.height * pixelRatio ),
  52654. context.viewportValue.minDepth,
  52655. context.viewportValue.maxDepth
  52656. );
  52657. }
  52658. // Set camera index binding for this layer
  52659. if ( cameraIndex && cameraData.indexesGPU ) {
  52660. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  52661. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  52662. }
  52663. draw( pass, sets );
  52664. }
  52665. }
  52666. } else {
  52667. // Regular single camera rendering
  52668. if ( renderContextData.currentPass ) {
  52669. // Handle occlusion queries
  52670. if ( renderContextData.occlusionQuerySet !== undefined ) {
  52671. const lastObject = renderContextData.lastOcclusionObject;
  52672. if ( lastObject !== object ) {
  52673. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  52674. renderContextData.currentPass.endOcclusionQuery();
  52675. renderContextData.occlusionQueryIndex ++;
  52676. }
  52677. if ( object.occlusionTest === true ) {
  52678. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  52679. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  52680. }
  52681. renderContextData.lastOcclusionObject = object;
  52682. }
  52683. }
  52684. draw( renderContextData.currentPass, renderContextData.currentSets );
  52685. }
  52686. }
  52687. }
  52688. // cache key
  52689. /**
  52690. * Returns `true` if the render pipeline requires an update.
  52691. *
  52692. * @param {RenderObject} renderObject - The render object.
  52693. * @return {boolean} Whether the render pipeline requires an update or not.
  52694. */
  52695. needsRenderUpdate( renderObject ) {
  52696. const data = this.get( renderObject );
  52697. const { object, material } = renderObject;
  52698. const utils = this.utils;
  52699. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  52700. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  52701. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  52702. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  52703. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  52704. let needsUpdate = false;
  52705. if ( data.material !== material || data.materialVersion !== material.version ||
  52706. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  52707. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  52708. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  52709. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  52710. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  52711. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  52712. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  52713. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  52714. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  52715. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  52716. data.primitiveTopology !== primitiveTopology ||
  52717. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  52718. ) {
  52719. data.material = material; data.materialVersion = material.version;
  52720. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  52721. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  52722. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  52723. data.colorWrite = material.colorWrite;
  52724. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  52725. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  52726. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  52727. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  52728. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  52729. data.sampleCount = sampleCount;
  52730. data.colorSpace = colorSpace;
  52731. data.colorFormat = colorFormat;
  52732. data.depthStencilFormat = depthStencilFormat;
  52733. data.primitiveTopology = primitiveTopology;
  52734. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  52735. needsUpdate = true;
  52736. }
  52737. return needsUpdate;
  52738. }
  52739. /**
  52740. * Returns a cache key that is used to identify render pipelines.
  52741. *
  52742. * @param {RenderObject} renderObject - The render object.
  52743. * @return {string} The cache key.
  52744. */
  52745. getRenderCacheKey( renderObject ) {
  52746. const { object, material } = renderObject;
  52747. const utils = this.utils;
  52748. const renderContext = renderObject.context;
  52749. return [
  52750. material.transparent, material.blending, material.premultipliedAlpha,
  52751. material.blendSrc, material.blendDst, material.blendEquation,
  52752. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  52753. material.colorWrite,
  52754. material.depthWrite, material.depthTest, material.depthFunc,
  52755. material.stencilWrite, material.stencilFunc,
  52756. material.stencilFail, material.stencilZFail, material.stencilZPass,
  52757. material.stencilFuncMask, material.stencilWriteMask,
  52758. material.side,
  52759. utils.getSampleCountRenderContext( renderContext ),
  52760. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  52761. utils.getPrimitiveTopology( object, material ),
  52762. renderObject.getGeometryCacheKey(),
  52763. renderObject.clippingContextCacheKey
  52764. ].join();
  52765. }
  52766. // textures
  52767. /**
  52768. * Creates a GPU sampler for the given texture.
  52769. *
  52770. * @param {Texture} texture - The texture to create the sampler for.
  52771. */
  52772. createSampler( texture ) {
  52773. this.textureUtils.createSampler( texture );
  52774. }
  52775. /**
  52776. * Destroys the GPU sampler for the given texture.
  52777. *
  52778. * @param {Texture} texture - The texture to destroy the sampler for.
  52779. */
  52780. destroySampler( texture ) {
  52781. this.textureUtils.destroySampler( texture );
  52782. }
  52783. /**
  52784. * Creates a default texture for the given texture that can be used
  52785. * as a placeholder until the actual texture is ready for usage.
  52786. *
  52787. * @param {Texture} texture - The texture to create a default texture for.
  52788. */
  52789. createDefaultTexture( texture ) {
  52790. this.textureUtils.createDefaultTexture( texture );
  52791. }
  52792. /**
  52793. * Defines a texture on the GPU for the given texture object.
  52794. *
  52795. * @param {Texture} texture - The texture.
  52796. * @param {Object} [options={}] - Optional configuration parameter.
  52797. */
  52798. createTexture( texture, options ) {
  52799. this.textureUtils.createTexture( texture, options );
  52800. }
  52801. /**
  52802. * Uploads the updated texture data to the GPU.
  52803. *
  52804. * @param {Texture} texture - The texture.
  52805. * @param {Object} [options={}] - Optional configuration parameter.
  52806. */
  52807. updateTexture( texture, options ) {
  52808. this.textureUtils.updateTexture( texture, options );
  52809. }
  52810. /**
  52811. * Generates mipmaps for the given texture.
  52812. *
  52813. * @param {Texture} texture - The texture.
  52814. */
  52815. generateMipmaps( texture ) {
  52816. this.textureUtils.generateMipmaps( texture );
  52817. }
  52818. /**
  52819. * Destroys the GPU data for the given texture object.
  52820. *
  52821. * @param {Texture} texture - The texture.
  52822. */
  52823. destroyTexture( texture ) {
  52824. this.textureUtils.destroyTexture( texture );
  52825. }
  52826. /**
  52827. * Returns texture data as a typed array.
  52828. *
  52829. * @async
  52830. * @param {Texture} texture - The texture to copy.
  52831. * @param {number} x - The x coordinate of the copy origin.
  52832. * @param {number} y - The y coordinate of the copy origin.
  52833. * @param {number} width - The width of the copy.
  52834. * @param {number} height - The height of the copy.
  52835. * @param {number} faceIndex - The face index.
  52836. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  52837. */
  52838. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  52839. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  52840. }
  52841. /**
  52842. * Inits a time stamp query for the given render context.
  52843. *
  52844. * @param {RenderContext} renderContext - The render context.
  52845. * @param {Object} descriptor - The query descriptor.
  52846. */
  52847. initTimestampQuery( renderContext, descriptor ) {
  52848. if ( ! this.trackTimestamp ) return;
  52849. const type = renderContext.isComputeNode ? 'compute' : 'render';
  52850. if ( ! this.timestampQueryPool[ type ] ) {
  52851. // TODO: Variable maxQueries?
  52852. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  52853. }
  52854. const timestampQueryPool = this.timestampQueryPool[ type ];
  52855. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  52856. descriptor.timestampWrites = {
  52857. querySet: timestampQueryPool.querySet,
  52858. beginningOfPassWriteIndex: baseOffset,
  52859. endOfPassWriteIndex: baseOffset + 1,
  52860. };
  52861. }
  52862. // node builder
  52863. /**
  52864. * Returns a node builder for the given render object.
  52865. *
  52866. * @param {RenderObject} object - The render object.
  52867. * @param {Renderer} renderer - The renderer.
  52868. * @return {WGSLNodeBuilder} The node builder.
  52869. */
  52870. createNodeBuilder( object, renderer ) {
  52871. return new WGSLNodeBuilder( object, renderer );
  52872. }
  52873. // program
  52874. /**
  52875. * Creates a shader program from the given programmable stage.
  52876. *
  52877. * @param {ProgrammableStage} program - The programmable stage.
  52878. */
  52879. createProgram( program ) {
  52880. const programGPU = this.get( program );
  52881. programGPU.module = {
  52882. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  52883. entryPoint: 'main'
  52884. };
  52885. }
  52886. /**
  52887. * Destroys the shader program of the given programmable stage.
  52888. *
  52889. * @param {ProgrammableStage} program - The programmable stage.
  52890. */
  52891. destroyProgram( program ) {
  52892. this.delete( program );
  52893. }
  52894. // pipelines
  52895. /**
  52896. * Creates a render pipeline for the given render object.
  52897. *
  52898. * @param {RenderObject} renderObject - The render object.
  52899. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  52900. */
  52901. createRenderPipeline( renderObject, promises ) {
  52902. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  52903. }
  52904. /**
  52905. * Creates a compute pipeline for the given compute node.
  52906. *
  52907. * @param {ComputePipeline} computePipeline - The compute pipeline.
  52908. * @param {Array<BindGroup>} bindings - The bindings.
  52909. */
  52910. createComputePipeline( computePipeline, bindings ) {
  52911. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  52912. }
  52913. /**
  52914. * Prepares the state for encoding render bundles.
  52915. *
  52916. * @param {RenderContext} renderContext - The render context.
  52917. */
  52918. beginBundle( renderContext ) {
  52919. const renderContextData = this.get( renderContext );
  52920. renderContextData._currentPass = renderContextData.currentPass;
  52921. renderContextData._currentSets = renderContextData.currentSets;
  52922. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52923. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  52924. }
  52925. /**
  52926. * After processing render bundles this method finalizes related work.
  52927. *
  52928. * @param {RenderContext} renderContext - The render context.
  52929. * @param {RenderBundle} bundle - The render bundle.
  52930. */
  52931. finishBundle( renderContext, bundle ) {
  52932. const renderContextData = this.get( renderContext );
  52933. const bundleEncoder = renderContextData.currentPass;
  52934. const bundleGPU = bundleEncoder.finish();
  52935. this.get( bundle ).bundleGPU = bundleGPU;
  52936. // restore render pass state
  52937. renderContextData.currentSets = renderContextData._currentSets;
  52938. renderContextData.currentPass = renderContextData._currentPass;
  52939. }
  52940. /**
  52941. * Adds a render bundle to the render context data.
  52942. *
  52943. * @param {RenderContext} renderContext - The render context.
  52944. * @param {RenderBundle} bundle - The render bundle to add.
  52945. */
  52946. addBundle( renderContext, bundle ) {
  52947. const renderContextData = this.get( renderContext );
  52948. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  52949. }
  52950. // bindings
  52951. /**
  52952. * Creates bindings from the given bind group definition.
  52953. *
  52954. * @param {BindGroup} bindGroup - The bind group.
  52955. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52956. * @param {number} cacheIndex - The cache index.
  52957. * @param {number} version - The version.
  52958. */
  52959. createBindings( bindGroup, bindings, cacheIndex, version ) {
  52960. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  52961. }
  52962. /**
  52963. * Updates the given bind group definition.
  52964. *
  52965. * @param {BindGroup} bindGroup - The bind group.
  52966. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52967. * @param {number} cacheIndex - The cache index.
  52968. * @param {number} version - The version.
  52969. */
  52970. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  52971. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  52972. }
  52973. /**
  52974. * Updates a buffer binding.
  52975. *
  52976. * @param {Buffer} binding - The buffer binding to update.
  52977. */
  52978. updateBinding( binding ) {
  52979. this.bindingUtils.updateBinding( binding );
  52980. }
  52981. // attributes
  52982. /**
  52983. * Creates the buffer of an indexed shader attribute.
  52984. *
  52985. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  52986. */
  52987. createIndexAttribute( attribute ) {
  52988. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  52989. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  52990. usage |= GPUBufferUsage.STORAGE;
  52991. }
  52992. this.attributeUtils.createAttribute( attribute, usage );
  52993. }
  52994. /**
  52995. * Creates the GPU buffer of a shader attribute.
  52996. *
  52997. * @param {BufferAttribute} attribute - The buffer attribute.
  52998. */
  52999. createAttribute( attribute ) {
  53000. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  53001. }
  53002. /**
  53003. * Creates the GPU buffer of a storage attribute.
  53004. *
  53005. * @param {BufferAttribute} attribute - The buffer attribute.
  53006. */
  53007. createStorageAttribute( attribute ) {
  53008. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  53009. }
  53010. /**
  53011. * Creates the GPU buffer of an indirect storage attribute.
  53012. *
  53013. * @param {BufferAttribute} attribute - The buffer attribute.
  53014. */
  53015. createIndirectStorageAttribute( attribute ) {
  53016. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  53017. }
  53018. /**
  53019. * Updates the GPU buffer of a shader attribute.
  53020. *
  53021. * @param {BufferAttribute} attribute - The buffer attribute to update.
  53022. */
  53023. updateAttribute( attribute ) {
  53024. this.attributeUtils.updateAttribute( attribute );
  53025. }
  53026. /**
  53027. * Destroys the GPU buffer of a shader attribute.
  53028. *
  53029. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  53030. */
  53031. destroyAttribute( attribute ) {
  53032. this.attributeUtils.destroyAttribute( attribute );
  53033. }
  53034. // canvas
  53035. /**
  53036. * Triggers an update of the default render pass descriptor.
  53037. */
  53038. updateSize() {
  53039. this.colorBuffer = this.textureUtils.getColorBuffer();
  53040. this.defaultRenderPassdescriptor = null;
  53041. }
  53042. // utils public
  53043. /**
  53044. * Returns the maximum anisotropy texture filtering value.
  53045. *
  53046. * @return {number} The maximum anisotropy texture filtering value.
  53047. */
  53048. getMaxAnisotropy() {
  53049. return 16;
  53050. }
  53051. /**
  53052. * Checks if the given feature is supported by the backend.
  53053. *
  53054. * @param {string} name - The feature's name.
  53055. * @return {boolean} Whether the feature is supported or not.
  53056. */
  53057. hasFeature( name ) {
  53058. return this.device.features.has( name );
  53059. }
  53060. /**
  53061. * Copies data of the given source texture to the given destination texture.
  53062. *
  53063. * @param {Texture} srcTexture - The source texture.
  53064. * @param {Texture} dstTexture - The destination texture.
  53065. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  53066. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  53067. * @param {number} [srcLevel=0] - The mipmap level to copy.
  53068. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  53069. */
  53070. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  53071. let dstX = 0;
  53072. let dstY = 0;
  53073. let dstZ = 0;
  53074. let srcX = 0;
  53075. let srcY = 0;
  53076. let srcZ = 0;
  53077. let srcWidth = srcTexture.image.width;
  53078. let srcHeight = srcTexture.image.height;
  53079. let srcDepth = 1;
  53080. if ( srcRegion !== null ) {
  53081. if ( srcRegion.isBox3 === true ) {
  53082. srcX = srcRegion.min.x;
  53083. srcY = srcRegion.min.y;
  53084. srcZ = srcRegion.min.z;
  53085. srcWidth = srcRegion.max.x - srcRegion.min.x;
  53086. srcHeight = srcRegion.max.y - srcRegion.min.y;
  53087. srcDepth = srcRegion.max.z - srcRegion.min.z;
  53088. } else {
  53089. // Assume it's a Box2
  53090. srcX = srcRegion.min.x;
  53091. srcY = srcRegion.min.y;
  53092. srcWidth = srcRegion.max.x - srcRegion.min.x;
  53093. srcHeight = srcRegion.max.y - srcRegion.min.y;
  53094. srcDepth = 1;
  53095. }
  53096. }
  53097. if ( dstPosition !== null ) {
  53098. dstX = dstPosition.x;
  53099. dstY = dstPosition.y;
  53100. dstZ = dstPosition.z || 0;
  53101. }
  53102. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  53103. const sourceGPU = this.get( srcTexture ).texture;
  53104. const destinationGPU = this.get( dstTexture ).texture;
  53105. encoder.copyTextureToTexture(
  53106. {
  53107. texture: sourceGPU,
  53108. mipLevel: srcLevel,
  53109. origin: { x: srcX, y: srcY, z: srcZ }
  53110. },
  53111. {
  53112. texture: destinationGPU,
  53113. mipLevel: dstLevel,
  53114. origin: { x: dstX, y: dstY, z: dstZ }
  53115. },
  53116. [
  53117. srcWidth,
  53118. srcHeight,
  53119. srcDepth
  53120. ]
  53121. );
  53122. this.device.queue.submit( [ encoder.finish() ] );
  53123. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  53124. this.textureUtils.generateMipmaps( dstTexture );
  53125. }
  53126. }
  53127. /**
  53128. * Copies the current bound framebuffer to the given texture.
  53129. *
  53130. * @param {Texture} texture - The destination texture.
  53131. * @param {RenderContext} renderContext - The render context.
  53132. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  53133. */
  53134. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  53135. const renderContextData = this.get( renderContext );
  53136. let sourceGPU = null;
  53137. if ( renderContext.renderTarget ) {
  53138. if ( texture.isDepthTexture ) {
  53139. sourceGPU = this.get( renderContext.depthTexture ).texture;
  53140. } else {
  53141. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  53142. }
  53143. } else {
  53144. if ( texture.isDepthTexture ) {
  53145. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  53146. } else {
  53147. sourceGPU = this.context.getCurrentTexture();
  53148. }
  53149. }
  53150. const destinationGPU = this.get( texture ).texture;
  53151. if ( sourceGPU.format !== destinationGPU.format ) {
  53152. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  53153. return;
  53154. }
  53155. let encoder;
  53156. if ( renderContextData.currentPass ) {
  53157. renderContextData.currentPass.end();
  53158. encoder = renderContextData.encoder;
  53159. } else {
  53160. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  53161. }
  53162. encoder.copyTextureToTexture(
  53163. {
  53164. texture: sourceGPU,
  53165. origin: [ rectangle.x, rectangle.y, 0 ],
  53166. },
  53167. {
  53168. texture: destinationGPU
  53169. },
  53170. [
  53171. rectangle.z,
  53172. rectangle.w
  53173. ]
  53174. );
  53175. if ( renderContextData.currentPass ) {
  53176. const { descriptor } = renderContextData;
  53177. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  53178. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  53179. }
  53180. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53181. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53182. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  53183. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53184. if ( renderContext.viewport ) {
  53185. this.updateViewport( renderContext );
  53186. }
  53187. if ( renderContext.scissor ) {
  53188. const { x, y, width, height } = renderContext.scissorValue;
  53189. renderContextData.currentPass.setScissorRect( x, y, width, height );
  53190. }
  53191. } else {
  53192. this.device.queue.submit( [ encoder.finish() ] );
  53193. }
  53194. if ( texture.generateMipmaps ) {
  53195. this.textureUtils.generateMipmaps( texture );
  53196. }
  53197. }
  53198. }
  53199. /**
  53200. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  53201. *
  53202. * @augments SpotLight
  53203. */
  53204. class IESSpotLight extends SpotLight {
  53205. /**
  53206. * Constructs a new IES spot light.
  53207. *
  53208. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  53209. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  53210. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  53211. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  53212. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  53213. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  53214. */
  53215. constructor( color, intensity, distance, angle, penumbra, decay ) {
  53216. super( color, intensity, distance, angle, penumbra, decay );
  53217. /**
  53218. * TODO
  53219. *
  53220. * @type {?Texture}
  53221. * @default null
  53222. */
  53223. this.iesMap = null;
  53224. }
  53225. copy( source, recursive ) {
  53226. super.copy( source, recursive );
  53227. this.iesMap = source.iesMap;
  53228. return this;
  53229. }
  53230. }
  53231. /**
  53232. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  53233. *
  53234. * @augments SpotLight
  53235. */
  53236. class ProjectorLight extends SpotLight {
  53237. /**
  53238. * Constructs a new projector light.
  53239. *
  53240. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  53241. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  53242. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  53243. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  53244. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  53245. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  53246. */
  53247. constructor( color, intensity, distance, angle, penumbra, decay ) {
  53248. super( color, intensity, distance, angle, penumbra, decay );
  53249. /**
  53250. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  53251. *
  53252. * @type {number}
  53253. * @default null
  53254. */
  53255. this.aspect = null;
  53256. }
  53257. copy( source, recursive ) {
  53258. super.copy( source, recursive );
  53259. this.aspect = source.aspect;
  53260. return this;
  53261. }
  53262. }
  53263. /**
  53264. * This version of a node library represents the standard version
  53265. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  53266. * techniques and materials to node-based implementations.
  53267. *
  53268. * @private
  53269. * @augments NodeLibrary
  53270. */
  53271. class StandardNodeLibrary extends NodeLibrary {
  53272. /**
  53273. * Constructs a new standard node library.
  53274. */
  53275. constructor() {
  53276. super();
  53277. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  53278. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  53279. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  53280. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  53281. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  53282. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  53283. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  53284. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  53285. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  53286. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  53287. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  53288. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  53289. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  53290. this.addLight( PointLightNode, PointLight );
  53291. this.addLight( DirectionalLightNode, DirectionalLight );
  53292. this.addLight( RectAreaLightNode, RectAreaLight );
  53293. this.addLight( SpotLightNode, SpotLight );
  53294. this.addLight( AmbientLightNode, AmbientLight );
  53295. this.addLight( HemisphereLightNode, HemisphereLight );
  53296. this.addLight( LightProbeNode, LightProbe );
  53297. this.addLight( IESSpotLightNode, IESSpotLight );
  53298. this.addLight( ProjectorLightNode, ProjectorLight );
  53299. this.addToneMapping( linearToneMapping, LinearToneMapping );
  53300. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  53301. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  53302. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  53303. this.addToneMapping( agxToneMapping, AgXToneMapping );
  53304. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  53305. }
  53306. }
  53307. /*
  53308. const debugHandler = {
  53309. get: function ( target, name ) {
  53310. // Add |update
  53311. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  53312. return target[ name ];
  53313. }
  53314. };
  53315. */
  53316. /**
  53317. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  53318. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  53319. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  53320. *
  53321. * @augments Renderer
  53322. */
  53323. class WebGPURenderer extends Renderer {
  53324. /**
  53325. * WebGPURenderer options.
  53326. *
  53327. * @typedef {Object} WebGPURenderer~Options
  53328. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  53329. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  53330. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  53331. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  53332. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  53333. * @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.
  53334. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  53335. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  53336. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  53337. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  53338. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  53339. */
  53340. /**
  53341. * Constructs a new WebGPU renderer.
  53342. *
  53343. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  53344. */
  53345. constructor( parameters = {} ) {
  53346. let BackendClass;
  53347. if ( parameters.forceWebGL ) {
  53348. BackendClass = WebGLBackend;
  53349. } else {
  53350. BackendClass = WebGPUBackend;
  53351. parameters.getFallback = () => {
  53352. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  53353. return new WebGLBackend( parameters );
  53354. };
  53355. }
  53356. const backend = new BackendClass( parameters );
  53357. //super( new Proxy( backend, debugHandler ) );
  53358. super( backend, parameters );
  53359. /**
  53360. * The generic default value is overwritten with the
  53361. * standard node library for type mapping.
  53362. *
  53363. * @type {StandardNodeLibrary}
  53364. */
  53365. this.library = new StandardNodeLibrary();
  53366. /**
  53367. * This flag can be used for type testing.
  53368. *
  53369. * @type {boolean}
  53370. * @readonly
  53371. * @default true
  53372. */
  53373. this.isWebGPURenderer = true;
  53374. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  53375. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  53376. }
  53377. }
  53378. }
  53379. /**
  53380. * A specialized group which enables applications access to the
  53381. * Render Bundle API of WebGPU. The group with all its descendant nodes
  53382. * are considered as one render bundle and processed as such by
  53383. * the renderer.
  53384. *
  53385. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  53386. * With a WebGL backend, the group can technically be rendered but without
  53387. * any performance improvements.
  53388. *
  53389. * @augments Group
  53390. */
  53391. class BundleGroup extends Group {
  53392. /**
  53393. * Constructs a new bundle group.
  53394. */
  53395. constructor() {
  53396. super();
  53397. /**
  53398. * This flag can be used for type testing.
  53399. *
  53400. * @type {boolean}
  53401. * @readonly
  53402. * @default true
  53403. */
  53404. this.isBundleGroup = true;
  53405. /**
  53406. * This property is only relevant for detecting types
  53407. * during serialization/deserialization. It should always
  53408. * match the class name.
  53409. *
  53410. * @type {string}
  53411. * @readonly
  53412. * @default 'BundleGroup'
  53413. */
  53414. this.type = 'BundleGroup';
  53415. /**
  53416. * Whether the bundle is static or not. When set to `true`, the structure
  53417. * is assumed to be static and does not change. E.g. no new objects are
  53418. * added to the group
  53419. *
  53420. * If a change is required, an update can still be forced by setting the
  53421. * `needsUpdate` flag to `true`.
  53422. *
  53423. * @type {boolean}
  53424. * @default true
  53425. */
  53426. this.static = true;
  53427. /**
  53428. * The bundle group's version.
  53429. *
  53430. * @type {number}
  53431. * @readonly
  53432. * @default 0
  53433. */
  53434. this.version = 0;
  53435. }
  53436. /**
  53437. * Set this property to `true` when the bundle group has changed.
  53438. *
  53439. * @type {boolean}
  53440. * @default false
  53441. * @param {boolean} value
  53442. */
  53443. set needsUpdate( value ) {
  53444. if ( value === true ) this.version ++;
  53445. }
  53446. }
  53447. /**
  53448. * This module is responsible to manage the post processing setups in apps.
  53449. * You usually create a single instance of this class and use it to define
  53450. * the output of your post processing effect chain.
  53451. * ```js
  53452. * const postProcessing = new PostProcessing( renderer );
  53453. *
  53454. * const scenePass = pass( scene, camera );
  53455. *
  53456. * postProcessing.outputNode = scenePass;
  53457. * ```
  53458. *
  53459. * Note: This module can only be used with `WebGPURenderer`.
  53460. */
  53461. class PostProcessing {
  53462. /**
  53463. * Constructs a new post processing management module.
  53464. *
  53465. * @param {Renderer} renderer - A reference to the renderer.
  53466. * @param {Node<vec4>} outputNode - An optional output node.
  53467. */
  53468. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  53469. /**
  53470. * A reference to the renderer.
  53471. *
  53472. * @type {Renderer}
  53473. */
  53474. this.renderer = renderer;
  53475. /**
  53476. * A node which defines the final output of the post
  53477. * processing. This is usually the last node in a chain
  53478. * of effect nodes.
  53479. *
  53480. * @type {Node<vec4>}
  53481. */
  53482. this.outputNode = outputNode;
  53483. /**
  53484. * Whether the default output tone mapping and color
  53485. * space transformation should be enabled or not.
  53486. *
  53487. * It is enabled by default by it must be disabled when
  53488. * effects must be executed after tone mapping and color
  53489. * space conversion. A typical example is FXAA which
  53490. * requires sRGB input.
  53491. *
  53492. * When set to `false`, the app must control the output
  53493. * transformation with `RenderOutputNode`.
  53494. *
  53495. * ```js
  53496. * const outputPass = renderOutput( scenePass );
  53497. * ```
  53498. *
  53499. * @type {boolean}
  53500. */
  53501. this.outputColorTransform = true;
  53502. /**
  53503. * Must be set to `true` when the output node changes.
  53504. *
  53505. * @type {Node<vec4>}
  53506. */
  53507. this.needsUpdate = true;
  53508. const material = new NodeMaterial();
  53509. material.name = 'PostProcessing';
  53510. /**
  53511. * The full screen quad that is used to render
  53512. * the effects.
  53513. *
  53514. * @private
  53515. * @type {QuadMesh}
  53516. */
  53517. this._quadMesh = new QuadMesh( material );
  53518. /**
  53519. * The context of the post processing stack.
  53520. *
  53521. * @private
  53522. * @type {?Object}
  53523. * @default null
  53524. */
  53525. this._context = null;
  53526. }
  53527. /**
  53528. * When `PostProcessing` is used to apply post processing effects,
  53529. * the application must use this version of `render()` inside
  53530. * its animation loop (not the one from the renderer).
  53531. */
  53532. render() {
  53533. const renderer = this.renderer;
  53534. this._update();
  53535. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  53536. const toneMapping = renderer.toneMapping;
  53537. const outputColorSpace = renderer.outputColorSpace;
  53538. renderer.toneMapping = NoToneMapping;
  53539. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  53540. //
  53541. const currentXR = renderer.xr.enabled;
  53542. renderer.xr.enabled = false;
  53543. this._quadMesh.render( renderer );
  53544. renderer.xr.enabled = currentXR;
  53545. //
  53546. renderer.toneMapping = toneMapping;
  53547. renderer.outputColorSpace = outputColorSpace;
  53548. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  53549. }
  53550. /**
  53551. * Returns the current context of the post processing stack.
  53552. *
  53553. * @readonly
  53554. * @type {?Object}
  53555. */
  53556. get context() {
  53557. return this._context;
  53558. }
  53559. /**
  53560. * Frees internal resources.
  53561. */
  53562. dispose() {
  53563. this._quadMesh.material.dispose();
  53564. }
  53565. /**
  53566. * Updates the state of the module.
  53567. *
  53568. * @private
  53569. */
  53570. _update() {
  53571. if ( this.needsUpdate === true ) {
  53572. const renderer = this.renderer;
  53573. const toneMapping = renderer.toneMapping;
  53574. const outputColorSpace = renderer.outputColorSpace;
  53575. const context = {
  53576. postProcessing: this,
  53577. onBeforePostProcessing: null,
  53578. onAfterPostProcessing: null
  53579. };
  53580. let outputNode = this.outputNode;
  53581. if ( this.outputColorTransform === true ) {
  53582. outputNode = outputNode.context( context );
  53583. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  53584. } else {
  53585. context.toneMapping = toneMapping;
  53586. context.outputColorSpace = outputColorSpace;
  53587. outputNode = outputNode.context( context );
  53588. }
  53589. this._context = context;
  53590. this._quadMesh.material.fragmentNode = outputNode;
  53591. this._quadMesh.material.needsUpdate = true;
  53592. this.needsUpdate = false;
  53593. }
  53594. }
  53595. /**
  53596. * When `PostProcessing` is used to apply post processing effects,
  53597. * the application must use this version of `renderAsync()` inside
  53598. * its animation loop (not the one from the renderer).
  53599. *
  53600. * @async
  53601. * @return {Promise} A Promise that resolves when the render has been finished.
  53602. */
  53603. async renderAsync() {
  53604. this._update();
  53605. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  53606. const renderer = this.renderer;
  53607. const toneMapping = renderer.toneMapping;
  53608. const outputColorSpace = renderer.outputColorSpace;
  53609. renderer.toneMapping = NoToneMapping;
  53610. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  53611. //
  53612. const currentXR = renderer.xr.enabled;
  53613. renderer.xr.enabled = false;
  53614. await this._quadMesh.renderAsync( renderer );
  53615. renderer.xr.enabled = currentXR;
  53616. //
  53617. renderer.toneMapping = toneMapping;
  53618. renderer.outputColorSpace = outputColorSpace;
  53619. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  53620. }
  53621. }
  53622. /**
  53623. * This special type of texture is intended for compute shaders.
  53624. * It can be used to compute the data of a texture with a compute shader.
  53625. *
  53626. * Note: This type of texture can only be used with `WebGPURenderer`
  53627. * and a WebGPU backend.
  53628. *
  53629. * @augments Texture
  53630. */
  53631. class StorageTexture extends Texture {
  53632. /**
  53633. * Constructs a new storage texture.
  53634. *
  53635. * @param {number} [width=1] - The storage texture's width.
  53636. * @param {number} [height=1] - The storage texture's height.
  53637. */
  53638. constructor( width = 1, height = 1 ) {
  53639. super();
  53640. /**
  53641. * The image object which just represents the texture's dimension.
  53642. *
  53643. * @type {{width: number, height: number}}
  53644. */
  53645. this.image = { width, height };
  53646. /**
  53647. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  53648. *
  53649. * @type {number}
  53650. */
  53651. this.magFilter = LinearFilter;
  53652. /**
  53653. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  53654. *
  53655. * @type {number}
  53656. */
  53657. this.minFilter = LinearFilter;
  53658. /**
  53659. * This flag can be used for type testing.
  53660. *
  53661. * @type {boolean}
  53662. * @readonly
  53663. * @default true
  53664. */
  53665. this.isStorageTexture = true;
  53666. }
  53667. /**
  53668. * Sets the size of the storage texture.
  53669. *
  53670. * @param {number} width - The new width of the storage texture.
  53671. * @param {number} height - The new height of the storage texture.
  53672. */
  53673. setSize( width, height ) {
  53674. if ( this.image.width !== width || this.image.height !== height ) {
  53675. this.image.width = width;
  53676. this.image.height = height;
  53677. this.dispose();
  53678. }
  53679. }
  53680. }
  53681. /**
  53682. * This special type of texture is intended for compute shaders.
  53683. * It can be used to compute the data of a texture with a compute shader.
  53684. *
  53685. * Note: This type of texture can only be used with `WebGPURenderer`
  53686. * and a WebGPU backend.
  53687. *
  53688. * @augments Texture
  53689. */
  53690. class Storage3DTexture extends Texture {
  53691. /**
  53692. * Constructs a new storage texture.
  53693. *
  53694. * @param {number} [width=1] - The storage texture's width.
  53695. * @param {number} [height=1] - The storage texture's height.
  53696. * @param {number} [depth=1] - The storage texture's depth.
  53697. */
  53698. constructor( width = 1, height = 1, depth = 1 ) {
  53699. super();
  53700. //inherited from texture. Must be false for 3DTexture
  53701. this.isArrayTexture = false;
  53702. /**
  53703. * The image object which just represents the texture's dimension.
  53704. *
  53705. * @type {{width: number, height: number, depth: number}}
  53706. */
  53707. this.image = { width, height, depth };
  53708. /**
  53709. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  53710. *
  53711. * @type {number}
  53712. */
  53713. this.magFilter = LinearFilter;
  53714. /**
  53715. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  53716. *
  53717. * @type {number}
  53718. */
  53719. this.minFilter = LinearFilter;
  53720. /**
  53721. * This defines how the texture is wrapped in the depth direction and corresponds to
  53722. * *W* in UVW mapping.
  53723. *
  53724. * @type {number}
  53725. */
  53726. this.wrapR = ClampToEdgeWrapping;
  53727. /**
  53728. * This flag can be used for type testing.
  53729. *
  53730. * @type {boolean}
  53731. * @readonly
  53732. * @default true
  53733. */
  53734. this.isStorageTexture = true;
  53735. /**
  53736. * Indicates whether this texture is a 3D texture.
  53737. *
  53738. * @type {boolean}
  53739. *
  53740. */
  53741. this.is3DTexture = true;
  53742. }
  53743. /**
  53744. * Sets the size of the storage 3d texture.
  53745. *
  53746. * @param {number} width - The new width of the storage texture.
  53747. * @param {number} height - The new height of the storage texture.
  53748. * @param {number} depth - The new depth of the storage texture.
  53749. */
  53750. setSize( width, height, depth ) {
  53751. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  53752. this.image.width = width;
  53753. this.image.height = height;
  53754. this.image.depth = depth;
  53755. this.dispose();
  53756. }
  53757. }
  53758. }
  53759. /**
  53760. * This special type of texture is intended for compute shaders.
  53761. * It can be used to compute the data of a texture with a compute shader.
  53762. *
  53763. * Note: This type of texture can only be used with `WebGPURenderer`
  53764. * and a WebGPU backend.
  53765. *
  53766. * @augments Texture
  53767. */
  53768. class StorageArrayTexture extends Texture {
  53769. /**
  53770. * Constructs a new storage texture.
  53771. *
  53772. * @param {number} [width=1] - The storage texture's width.
  53773. * @param {number} [height=1] - The storage texture's height.
  53774. * @param {number} [depth=1] - The storage texture's depth.
  53775. */
  53776. constructor( width = 1, height = 1, depth = 1 ) {
  53777. super();
  53778. //inherited from texture
  53779. this.isArrayTexture = true;
  53780. /**
  53781. * The image object which just represents the texture's dimension.
  53782. *
  53783. * @type {{width: number, height: number, depth: number}}
  53784. */
  53785. this.image = { width, height, depth };
  53786. /**
  53787. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  53788. *
  53789. * @type {number}
  53790. */
  53791. this.magFilter = LinearFilter;
  53792. /**
  53793. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  53794. *
  53795. * @type {number}
  53796. */
  53797. this.minFilter = LinearFilter;
  53798. /**
  53799. * This flag can be used for type testing.
  53800. *
  53801. * @type {boolean}
  53802. * @readonly
  53803. * @default true
  53804. */
  53805. this.isStorageTexture = true;
  53806. }
  53807. /**
  53808. * Sets the size of the storage array texture.
  53809. *
  53810. * @param {number} width - The new width of the storage texture.
  53811. * @param {number} height - The new height of the storage texture.
  53812. * @param {number} depth - The new depth of the storage texture.
  53813. */
  53814. setSize( width, height, depth ) {
  53815. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  53816. this.image.width = width;
  53817. this.image.height = height;
  53818. this.image.depth = depth;
  53819. this.dispose();
  53820. }
  53821. }
  53822. }
  53823. /**
  53824. * This special type of buffer attribute is intended for compute shaders.
  53825. * It can be used to encode draw parameters for indirect draw calls.
  53826. *
  53827. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  53828. * and a WebGPU backend.
  53829. *
  53830. * @augments StorageBufferAttribute
  53831. */
  53832. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  53833. /**
  53834. * Constructs a new storage buffer attribute.
  53835. *
  53836. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  53837. * The subsequent parameter is then obsolete.
  53838. * @param {number} itemSize - The item size.
  53839. */
  53840. constructor( count, itemSize ) {
  53841. super( count, itemSize, Uint32Array );
  53842. /**
  53843. * This flag can be used for type testing.
  53844. *
  53845. * @type {boolean}
  53846. * @readonly
  53847. * @default true
  53848. */
  53849. this.isIndirectStorageBufferAttribute = true;
  53850. }
  53851. }
  53852. /**
  53853. * A loader for loading node objects in the three.js JSON Object/Scene format.
  53854. *
  53855. * @augments Loader
  53856. */
  53857. class NodeLoader extends Loader {
  53858. /**
  53859. * Constructs a new node loader.
  53860. *
  53861. * @param {LoadingManager} [manager] - A reference to a loading manager.
  53862. */
  53863. constructor( manager ) {
  53864. super( manager );
  53865. /**
  53866. * Represents a dictionary of textures.
  53867. *
  53868. * @type {Object<string,Texture>}
  53869. */
  53870. this.textures = {};
  53871. /**
  53872. * Represents a dictionary of node types.
  53873. *
  53874. * @type {Object<string,Node.constructor>}
  53875. */
  53876. this.nodes = {};
  53877. }
  53878. /**
  53879. * Loads the node definitions from the given URL.
  53880. *
  53881. * @param {string} url - The path/URL of the file to be loaded.
  53882. * @param {Function} onLoad - Will be called when load completes.
  53883. * @param {Function} onProgress - Will be called while load progresses.
  53884. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  53885. */
  53886. load( url, onLoad, onProgress, onError ) {
  53887. const loader = new FileLoader( this.manager );
  53888. loader.setPath( this.path );
  53889. loader.setRequestHeader( this.requestHeader );
  53890. loader.setWithCredentials( this.withCredentials );
  53891. loader.load( url, ( text ) => {
  53892. try {
  53893. onLoad( this.parse( JSON.parse( text ) ) );
  53894. } catch ( e ) {
  53895. if ( onError ) {
  53896. onError( e );
  53897. } else {
  53898. console.error( e );
  53899. }
  53900. this.manager.itemError( url );
  53901. }
  53902. }, onProgress, onError );
  53903. }
  53904. /**
  53905. * Parse the node dependencies for the loaded node.
  53906. *
  53907. * @param {Array<Object>} [json] - The JSON definition
  53908. * @return {Object<string,Node>} A dictionary with node dependencies.
  53909. */
  53910. parseNodes( json ) {
  53911. const nodes = {};
  53912. if ( json !== undefined ) {
  53913. for ( const nodeJSON of json ) {
  53914. const { uuid, type } = nodeJSON;
  53915. nodes[ uuid ] = this.createNodeFromType( type );
  53916. nodes[ uuid ].uuid = uuid;
  53917. }
  53918. const meta = { nodes, textures: this.textures };
  53919. for ( const nodeJSON of json ) {
  53920. nodeJSON.meta = meta;
  53921. const node = nodes[ nodeJSON.uuid ];
  53922. node.deserialize( nodeJSON );
  53923. delete nodeJSON.meta;
  53924. }
  53925. }
  53926. return nodes;
  53927. }
  53928. /**
  53929. * Parses the node from the given JSON.
  53930. *
  53931. * @param {Object} json - The JSON definition
  53932. * @param {string} json.type - The node type.
  53933. * @param {string} json.uuid - The node UUID.
  53934. * @param {Array<Object>} [json.nodes] - The node dependencies.
  53935. * @param {Object} [json.meta] - The meta data.
  53936. * @return {Node} The parsed node.
  53937. */
  53938. parse( json ) {
  53939. const node = this.createNodeFromType( json.type );
  53940. node.uuid = json.uuid;
  53941. const nodes = this.parseNodes( json.nodes );
  53942. const meta = { nodes, textures: this.textures };
  53943. json.meta = meta;
  53944. node.deserialize( json );
  53945. delete json.meta;
  53946. return node;
  53947. }
  53948. /**
  53949. * Defines the dictionary of textures.
  53950. *
  53951. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  53952. * @return {NodeLoader} A reference to this loader.
  53953. */
  53954. setTextures( value ) {
  53955. this.textures = value;
  53956. return this;
  53957. }
  53958. /**
  53959. * Defines the dictionary of node types.
  53960. *
  53961. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  53962. * @return {NodeLoader} A reference to this loader.
  53963. */
  53964. setNodes( value ) {
  53965. this.nodes = value;
  53966. return this;
  53967. }
  53968. /**
  53969. * Creates a node object from the given type.
  53970. *
  53971. * @param {string} type - The node type.
  53972. * @return {Node} The created node instance.
  53973. */
  53974. createNodeFromType( type ) {
  53975. if ( this.nodes[ type ] === undefined ) {
  53976. console.error( 'THREE.NodeLoader: Node type not found:', type );
  53977. return float();
  53978. }
  53979. return nodeObject( new this.nodes[ type ]() );
  53980. }
  53981. }
  53982. /**
  53983. * A special type of material loader for loading node materials.
  53984. *
  53985. * @augments MaterialLoader
  53986. */
  53987. class NodeMaterialLoader extends MaterialLoader {
  53988. /**
  53989. * Constructs a new node material loader.
  53990. *
  53991. * @param {LoadingManager} [manager] - A reference to a loading manager.
  53992. */
  53993. constructor( manager ) {
  53994. super( manager );
  53995. /**
  53996. * Represents a dictionary of node types.
  53997. *
  53998. * @type {Object<string,Node.constructor>}
  53999. */
  54000. this.nodes = {};
  54001. /**
  54002. * Represents a dictionary of node material types.
  54003. *
  54004. * @type {Object<string,NodeMaterial.constructor>}
  54005. */
  54006. this.nodeMaterials = {};
  54007. }
  54008. /**
  54009. * Parses the node material from the given JSON.
  54010. *
  54011. * @param {Object} json - The JSON definition
  54012. * @return {NodeMaterial}. The parsed material.
  54013. */
  54014. parse( json ) {
  54015. const material = super.parse( json );
  54016. const nodes = this.nodes;
  54017. const inputNodes = json.inputNodes;
  54018. for ( const property in inputNodes ) {
  54019. const uuid = inputNodes[ property ];
  54020. material[ property ] = nodes[ uuid ];
  54021. }
  54022. return material;
  54023. }
  54024. /**
  54025. * Defines the dictionary of node types.
  54026. *
  54027. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54028. * @return {NodeLoader} A reference to this loader.
  54029. */
  54030. setNodes( value ) {
  54031. this.nodes = value;
  54032. return this;
  54033. }
  54034. /**
  54035. * Defines the dictionary of node material types.
  54036. *
  54037. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  54038. * @return {NodeLoader} A reference to this loader.
  54039. */
  54040. setNodeMaterials( value ) {
  54041. this.nodeMaterials = value;
  54042. return this;
  54043. }
  54044. /**
  54045. * Creates a node material from the given type.
  54046. *
  54047. * @param {string} type - The node material type.
  54048. * @return {Node} The created node material instance.
  54049. */
  54050. createMaterialFromType( type ) {
  54051. const materialClass = this.nodeMaterials[ type ];
  54052. if ( materialClass !== undefined ) {
  54053. return new materialClass();
  54054. }
  54055. return super.createMaterialFromType( type );
  54056. }
  54057. }
  54058. /**
  54059. * A special type of object loader for loading 3D objects using
  54060. * node materials.
  54061. *
  54062. * @augments ObjectLoader
  54063. */
  54064. class NodeObjectLoader extends ObjectLoader {
  54065. /**
  54066. * Constructs a new node object loader.
  54067. *
  54068. * @param {LoadingManager} [manager] - A reference to a loading manager.
  54069. */
  54070. constructor( manager ) {
  54071. super( manager );
  54072. /**
  54073. * Represents a dictionary of node types.
  54074. *
  54075. * @type {Object<string,Node.constructor>}
  54076. */
  54077. this.nodes = {};
  54078. /**
  54079. * Represents a dictionary of node material types.
  54080. *
  54081. * @type {Object<string,NodeMaterial.constructor>}
  54082. */
  54083. this.nodeMaterials = {};
  54084. /**
  54085. * A reference to hold the `nodes` JSON property.
  54086. *
  54087. * @private
  54088. * @type {?Object[]}
  54089. */
  54090. this._nodesJSON = null;
  54091. }
  54092. /**
  54093. * Defines the dictionary of node types.
  54094. *
  54095. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54096. * @return {NodeObjectLoader} A reference to this loader.
  54097. */
  54098. setNodes( value ) {
  54099. this.nodes = value;
  54100. return this;
  54101. }
  54102. /**
  54103. * Defines the dictionary of node material types.
  54104. *
  54105. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  54106. * @return {NodeObjectLoader} A reference to this loader.
  54107. */
  54108. setNodeMaterials( value ) {
  54109. this.nodeMaterials = value;
  54110. return this;
  54111. }
  54112. /**
  54113. * Parses the node objects from the given JSON.
  54114. *
  54115. * @param {Object} json - The JSON definition
  54116. * @param {Function} onLoad - The onLoad callback function.
  54117. * @return {Object3D}. The parsed 3D object.
  54118. */
  54119. parse( json, onLoad ) {
  54120. this._nodesJSON = json.nodes;
  54121. const data = super.parse( json, onLoad );
  54122. this._nodesJSON = null; // dispose
  54123. return data;
  54124. }
  54125. /**
  54126. * Parses the node objects from the given JSON and textures.
  54127. *
  54128. * @param {Object[]} json - The JSON definition
  54129. * @param {Object<string,Texture>} textures - The texture library.
  54130. * @return {Object<string,Node>}. The parsed nodes.
  54131. */
  54132. parseNodes( json, textures ) {
  54133. if ( json !== undefined ) {
  54134. const loader = new NodeLoader();
  54135. loader.setNodes( this.nodes );
  54136. loader.setTextures( textures );
  54137. return loader.parseNodes( json );
  54138. }
  54139. return {};
  54140. }
  54141. /**
  54142. * Parses the node objects from the given JSON and textures.
  54143. *
  54144. * @param {Object} json - The JSON definition
  54145. * @param {Object<string,Texture>} textures - The texture library.
  54146. * @return {Object<string,NodeMaterial>}. The parsed materials.
  54147. */
  54148. parseMaterials( json, textures ) {
  54149. const materials = {};
  54150. if ( json !== undefined ) {
  54151. const nodes = this.parseNodes( this._nodesJSON, textures );
  54152. const loader = new NodeMaterialLoader();
  54153. loader.setTextures( textures );
  54154. loader.setNodes( nodes );
  54155. loader.setNodeMaterials( this.nodeMaterials );
  54156. for ( let i = 0, l = json.length; i < l; i ++ ) {
  54157. const data = json[ i ];
  54158. materials[ data.uuid ] = loader.parse( data );
  54159. }
  54160. }
  54161. return materials;
  54162. }
  54163. }
  54164. /**
  54165. * In earlier three.js versions, clipping was defined globally
  54166. * on the renderer or on material level. This special version of
  54167. * `THREE.Group` allows to encode the clipping state into the scene
  54168. * graph. Meaning if you create an instance of this group, all
  54169. * descendant 3D objects will be affected by the respective clipping
  54170. * planes.
  54171. *
  54172. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  54173. *
  54174. * @augments Group
  54175. */
  54176. class ClippingGroup extends Group {
  54177. /**
  54178. * Constructs a new clipping group.
  54179. */
  54180. constructor() {
  54181. super();
  54182. /**
  54183. * This flag can be used for type testing.
  54184. *
  54185. * @type {boolean}
  54186. * @readonly
  54187. * @default true
  54188. */
  54189. this.isClippingGroup = true;
  54190. /**
  54191. * An array with clipping planes.
  54192. *
  54193. * @type {Array<Plane>}
  54194. */
  54195. this.clippingPlanes = [];
  54196. /**
  54197. * Whether clipping should be enabled or not.
  54198. *
  54199. * @type {boolean}
  54200. * @default true
  54201. */
  54202. this.enabled = true;
  54203. /**
  54204. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  54205. *
  54206. * @type {boolean}
  54207. * @default false
  54208. */
  54209. this.clipIntersection = false;
  54210. /**
  54211. * Whether shadows should be clipped or not.
  54212. *
  54213. * @type {boolean}
  54214. * @default false
  54215. */
  54216. this.clipShadows = false;
  54217. }
  54218. }
  54219. 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号