three.webgpu.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905
  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, UnsignedIntType, IntType, NearestFilter, Sphere, BackSide, Euler, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, HalfFloatType, CubeUVReflectionMapping, BufferGeometry, BufferAttribute, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, warnOnce, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. /**
  61. * This class is used by {@link WebGPURenderer} as management component.
  62. * It's primary purpose is to determine whether render objects require a
  63. * refresh right before they are going to be rendered or not.
  64. */
  65. class NodeMaterialObserver {
  66. /**
  67. * Constructs a new node material observer.
  68. *
  69. * @param {NodeBuilder} builder - The node builder.
  70. */
  71. constructor( builder ) {
  72. /**
  73. * A node material can be used by more than one render object so the
  74. * monitor must maintain a list of render objects.
  75. *
  76. * @type {WeakMap<RenderObject,Object>}
  77. */
  78. this.renderObjects = new WeakMap();
  79. /**
  80. * Whether the material uses node objects or not.
  81. *
  82. * @type {boolean}
  83. */
  84. this.hasNode = this.containsNode( builder );
  85. /**
  86. * Whether the node builder's 3D object is animated or not.
  87. *
  88. * @type {boolean}
  89. */
  90. this.hasAnimation = builder.object.isSkinnedMesh === true;
  91. /**
  92. * A list of all possible material uniforms
  93. *
  94. * @type {Array<string>}
  95. */
  96. this.refreshUniforms = refreshUniforms;
  97. /**
  98. * Holds the current render ID from the node frame.
  99. *
  100. * @type {number}
  101. * @default 0
  102. */
  103. this.renderId = 0;
  104. }
  105. /**
  106. * Returns `true` if the given render object is verified for the first time of this observer.
  107. *
  108. * @param {RenderObject} renderObject - The render object.
  109. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  110. */
  111. firstInitialization( renderObject ) {
  112. const hasInitialized = this.renderObjects.has( renderObject );
  113. if ( hasInitialized === false ) {
  114. this.getRenderObjectData( renderObject );
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Returns `true` if the current rendering produces motion vectors.
  121. *
  122. * @param {Renderer} renderer - The renderer.
  123. * @return {boolean} Whether the current rendering produces motion vectors or not.
  124. */
  125. needsVelocity( renderer ) {
  126. const mrt = renderer.getMRT();
  127. return ( mrt !== null && mrt.has( 'velocity' ) );
  128. }
  129. /**
  130. * Returns monitoring data for the given render object.
  131. *
  132. * @param {RenderObject} renderObject - The render object.
  133. * @return {Object} The monitoring data.
  134. */
  135. getRenderObjectData( renderObject ) {
  136. let data = this.renderObjects.get( renderObject );
  137. if ( data === undefined ) {
  138. const { geometry, material, object } = renderObject;
  139. data = {
  140. material: this.getMaterialData( material ),
  141. geometry: {
  142. id: geometry.id,
  143. attributes: this.getAttributesData( geometry.attributes ),
  144. indexVersion: geometry.index ? geometry.index.version : null,
  145. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  146. },
  147. worldMatrix: object.matrixWorld.clone()
  148. };
  149. if ( object.center ) {
  150. data.center = object.center.clone();
  151. }
  152. if ( object.morphTargetInfluences ) {
  153. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  154. }
  155. if ( renderObject.bundle !== null ) {
  156. data.version = renderObject.bundle.version;
  157. }
  158. if ( data.material.transmission > 0 ) {
  159. const { width, height } = renderObject.context;
  160. data.bufferWidth = width;
  161. data.bufferHeight = height;
  162. }
  163. this.renderObjects.set( renderObject, data );
  164. }
  165. return data;
  166. }
  167. /**
  168. * Returns an attribute data structure holding the attributes versions for
  169. * monitoring.
  170. *
  171. * @param {Object} attributes - The geometry attributes.
  172. * @return {Object} An object for monitoring the versions of attributes.
  173. */
  174. getAttributesData( attributes ) {
  175. const attributesData = {};
  176. for ( const name in attributes ) {
  177. const attribute = attributes[ name ];
  178. attributesData[ name ] = {
  179. version: attribute.version
  180. };
  181. }
  182. return attributesData;
  183. }
  184. /**
  185. * Returns `true` if the node builder's material uses
  186. * node properties.
  187. *
  188. * @param {NodeBuilder} builder - The current node builder.
  189. * @return {boolean} Whether the node builder's material uses node properties or not.
  190. */
  191. containsNode( builder ) {
  192. const material = builder.material;
  193. for ( const property in material ) {
  194. if ( material[ property ] && material[ property ].isNode )
  195. return true;
  196. }
  197. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  198. return true;
  199. return false;
  200. }
  201. /**
  202. * Returns a material data structure holding the material property values for
  203. * monitoring.
  204. *
  205. * @param {Material} material - The material.
  206. * @return {Object} An object for monitoring material properties.
  207. */
  208. getMaterialData( material ) {
  209. const data = {};
  210. for ( const property of this.refreshUniforms ) {
  211. const value = material[ property ];
  212. if ( value === null || value === undefined ) continue;
  213. if ( typeof value === 'object' && value.clone !== undefined ) {
  214. if ( value.isTexture === true ) {
  215. data[ property ] = { id: value.id, version: value.version };
  216. } else {
  217. data[ property ] = value.clone();
  218. }
  219. } else {
  220. data[ property ] = value;
  221. }
  222. }
  223. return data;
  224. }
  225. /**
  226. * Returns `true` if the given render object has not changed its state.
  227. *
  228. * @param {RenderObject} renderObject - The render object.
  229. * @return {boolean} Whether the given render object has changed its state or not.
  230. */
  231. equals( renderObject ) {
  232. const { object, material, geometry } = renderObject;
  233. const renderObjectData = this.getRenderObjectData( renderObject );
  234. // world matrix
  235. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  236. renderObjectData.worldMatrix.copy( object.matrixWorld );
  237. return false;
  238. }
  239. // material
  240. const materialData = renderObjectData.material;
  241. for ( const property in materialData ) {
  242. const value = materialData[ property ];
  243. const mtlValue = material[ property ];
  244. if ( value.equals !== undefined ) {
  245. if ( value.equals( mtlValue ) === false ) {
  246. value.copy( mtlValue );
  247. return false;
  248. }
  249. } else if ( mtlValue.isTexture === true ) {
  250. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  251. value.id = mtlValue.id;
  252. value.version = mtlValue.version;
  253. return false;
  254. }
  255. } else if ( value !== mtlValue ) {
  256. materialData[ property ] = mtlValue;
  257. return false;
  258. }
  259. }
  260. if ( materialData.transmission > 0 ) {
  261. const { width, height } = renderObject.context;
  262. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  263. renderObjectData.bufferWidth = width;
  264. renderObjectData.bufferHeight = height;
  265. return false;
  266. }
  267. }
  268. // geometry
  269. const storedGeometryData = renderObjectData.geometry;
  270. const attributes = geometry.attributes;
  271. const storedAttributes = storedGeometryData.attributes;
  272. const storedAttributeNames = Object.keys( storedAttributes );
  273. const currentAttributeNames = Object.keys( attributes );
  274. if ( storedGeometryData.id !== geometry.id ) {
  275. storedGeometryData.id = geometry.id;
  276. return false;
  277. }
  278. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  279. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  280. return false;
  281. }
  282. // compare each attribute
  283. for ( const name of storedAttributeNames ) {
  284. const storedAttributeData = storedAttributes[ name ];
  285. const attribute = attributes[ name ];
  286. if ( attribute === undefined ) {
  287. // attribute was removed
  288. delete storedAttributes[ name ];
  289. return false;
  290. }
  291. if ( storedAttributeData.version !== attribute.version ) {
  292. storedAttributeData.version = attribute.version;
  293. return false;
  294. }
  295. }
  296. // check index
  297. const index = geometry.index;
  298. const storedIndexVersion = storedGeometryData.indexVersion;
  299. const currentIndexVersion = index ? index.version : null;
  300. if ( storedIndexVersion !== currentIndexVersion ) {
  301. storedGeometryData.indexVersion = currentIndexVersion;
  302. return false;
  303. }
  304. // check drawRange
  305. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  306. storedGeometryData.drawRange.start = geometry.drawRange.start;
  307. storedGeometryData.drawRange.count = geometry.drawRange.count;
  308. return false;
  309. }
  310. // morph targets
  311. if ( renderObjectData.morphTargetInfluences ) {
  312. let morphChanged = false;
  313. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  314. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  315. morphChanged = true;
  316. }
  317. }
  318. if ( morphChanged ) return true;
  319. }
  320. // center
  321. if ( renderObjectData.center ) {
  322. if ( renderObjectData.center.equals( object.center ) === false ) {
  323. renderObjectData.center.copy( object.center );
  324. return true;
  325. }
  326. }
  327. // bundle
  328. if ( renderObject.bundle !== null ) {
  329. renderObjectData.version = renderObject.bundle.version;
  330. }
  331. return true;
  332. }
  333. /**
  334. * Checks if the given render object requires a refresh.
  335. *
  336. * @param {RenderObject} renderObject - The render object.
  337. * @param {NodeFrame} nodeFrame - The current node frame.
  338. * @return {boolean} Whether the given render object requires a refresh or not.
  339. */
  340. needsRefresh( renderObject, nodeFrame ) {
  341. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  342. return true;
  343. const { renderId } = nodeFrame;
  344. if ( this.renderId !== renderId ) {
  345. this.renderId = renderId;
  346. return true;
  347. }
  348. const isStatic = renderObject.object.static === true;
  349. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  350. if ( isStatic || isBundle )
  351. return false;
  352. const notEqual = this.equals( renderObject ) !== true;
  353. return notEqual;
  354. }
  355. }
  356. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  357. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  358. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  359. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  360. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  361. function cyrb53( value, seed = 0 ) {
  362. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  363. if ( value instanceof Array ) {
  364. for ( let i = 0, val; i < value.length; i ++ ) {
  365. val = value[ i ];
  366. h1 = Math.imul( h1 ^ val, 2654435761 );
  367. h2 = Math.imul( h2 ^ val, 1597334677 );
  368. }
  369. } else {
  370. for ( let i = 0, ch; i < value.length; i ++ ) {
  371. ch = value.charCodeAt( i );
  372. h1 = Math.imul( h1 ^ ch, 2654435761 );
  373. h2 = Math.imul( h2 ^ ch, 1597334677 );
  374. }
  375. }
  376. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  377. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  378. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  379. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  380. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  381. }
  382. /**
  383. * Computes a hash for the given string.
  384. *
  385. * @method
  386. * @param {string} str - The string to be hashed.
  387. * @return {number} The hash.
  388. */
  389. const hashString = ( str ) => cyrb53( str );
  390. /**
  391. * Computes a hash for the given array.
  392. *
  393. * @method
  394. * @param {Array<number>} array - The array to be hashed.
  395. * @return {number} The hash.
  396. */
  397. const hashArray = ( array ) => cyrb53( array );
  398. /**
  399. * Computes a hash for the given list of parameters.
  400. *
  401. * @method
  402. * @param {...number} params - A list of parameters.
  403. * @return {number} The hash.
  404. */
  405. const hash$1 = ( ...params ) => cyrb53( params );
  406. /**
  407. * Computes a cache key for the given node.
  408. *
  409. * @method
  410. * @param {Object|Node} object - The object to be hashed.
  411. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  412. * @return {number} The hash.
  413. */
  414. function getCacheKey$1( object, force = false ) {
  415. const values = [];
  416. if ( object.isNode === true ) {
  417. values.push( object.id );
  418. object = object.getSelf();
  419. }
  420. for ( const { property, childNode } of getNodeChildren( object ) ) {
  421. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  422. }
  423. return cyrb53( values );
  424. }
  425. /**
  426. * This generator function can be used to iterate over the node children
  427. * of the given object.
  428. *
  429. * @generator
  430. * @param {Object} node - The object to be hashed.
  431. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  432. * @yields {Object} A result node holding the property, index (if available) and the child node.
  433. */
  434. function* getNodeChildren( node, toJSON = false ) {
  435. for ( const property in node ) {
  436. // Ignore private properties.
  437. if ( property.startsWith( '_' ) === true ) continue;
  438. const object = node[ property ];
  439. if ( Array.isArray( object ) === true ) {
  440. for ( let i = 0; i < object.length; i ++ ) {
  441. const child = object[ i ];
  442. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  443. yield { property, index: i, childNode: child };
  444. }
  445. }
  446. } else if ( object && object.isNode === true ) {
  447. yield { property, childNode: object };
  448. } else if ( typeof object === 'object' ) {
  449. for ( const subProperty in object ) {
  450. const child = object[ subProperty ];
  451. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  452. yield { property, index: subProperty, childNode: child };
  453. }
  454. }
  455. }
  456. }
  457. }
  458. const typeFromLength = /*@__PURE__*/ new Map( [
  459. [ 1, 'float' ],
  460. [ 2, 'vec2' ],
  461. [ 3, 'vec3' ],
  462. [ 4, 'vec4' ],
  463. [ 9, 'mat3' ],
  464. [ 16, 'mat4' ]
  465. ] );
  466. const dataFromObject = /*@__PURE__*/ new WeakMap();
  467. /**
  468. * Returns the data type for the given the length.
  469. *
  470. * @method
  471. * @param {number} length - The length.
  472. * @return {string} The data type.
  473. */
  474. function getTypeFromLength( length ) {
  475. return typeFromLength.get( length );
  476. }
  477. /**
  478. * Returns the typed array for the given data type.
  479. *
  480. * @method
  481. * @param {string} type - The data type.
  482. * @return {TypedArray} The typed array.
  483. */
  484. function getTypedArrayFromType( type ) {
  485. // Handle component type for vectors and matrices
  486. if ( /[iu]?vec\d/.test( type ) ) {
  487. // Handle int vectors
  488. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  489. // Handle uint vectors
  490. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  491. // Default to float vectors
  492. return Float32Array;
  493. }
  494. // Handle matrices (always float)
  495. if ( /mat\d/.test( type ) ) return Float32Array;
  496. // Basic types
  497. if ( /float/.test( type ) ) return Float32Array;
  498. if ( /uint/.test( type ) ) return Uint32Array;
  499. if ( /int/.test( type ) ) return Int32Array;
  500. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  501. }
  502. /**
  503. * Returns the length for the given data type.
  504. *
  505. * @method
  506. * @param {string} type - The data type.
  507. * @return {number} The length.
  508. */
  509. function getLengthFromType( type ) {
  510. if ( /float|int|uint/.test( type ) ) return 1;
  511. if ( /vec2/.test( type ) ) return 2;
  512. if ( /vec3/.test( type ) ) return 3;
  513. if ( /vec4/.test( type ) ) return 4;
  514. if ( /mat2/.test( type ) ) return 4;
  515. if ( /mat3/.test( type ) ) return 9;
  516. if ( /mat4/.test( type ) ) return 16;
  517. console.error( 'THREE.TSL: Unsupported type:', type );
  518. }
  519. /**
  520. * Returns the data type for the given value.
  521. *
  522. * @method
  523. * @param {any} value - The value.
  524. * @return {?string} The data type.
  525. */
  526. function getValueType( value ) {
  527. if ( value === undefined || value === null ) return null;
  528. const typeOf = typeof value;
  529. if ( value.isNode === true ) {
  530. return 'node';
  531. } else if ( typeOf === 'number' ) {
  532. return 'float';
  533. } else if ( typeOf === 'boolean' ) {
  534. return 'bool';
  535. } else if ( typeOf === 'string' ) {
  536. return 'string';
  537. } else if ( typeOf === 'function' ) {
  538. return 'shader';
  539. } else if ( value.isVector2 === true ) {
  540. return 'vec2';
  541. } else if ( value.isVector3 === true ) {
  542. return 'vec3';
  543. } else if ( value.isVector4 === true ) {
  544. return 'vec4';
  545. } else if ( value.isMatrix2 === true ) {
  546. return 'mat2';
  547. } else if ( value.isMatrix3 === true ) {
  548. return 'mat3';
  549. } else if ( value.isMatrix4 === true ) {
  550. return 'mat4';
  551. } else if ( value.isColor === true ) {
  552. return 'color';
  553. } else if ( value instanceof ArrayBuffer ) {
  554. return 'ArrayBuffer';
  555. }
  556. return null;
  557. }
  558. /**
  559. * Returns the value/object for the given data type and parameters.
  560. *
  561. * @method
  562. * @param {string} type - The given type.
  563. * @param {...any} params - A parameter list.
  564. * @return {any} The value/object.
  565. */
  566. function getValueFromType( type, ...params ) {
  567. const last4 = type ? type.slice( -4 ) : undefined;
  568. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  569. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  570. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  571. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  572. }
  573. if ( type === 'color' ) {
  574. return new Color( ...params );
  575. } else if ( last4 === 'vec2' ) {
  576. return new Vector2( ...params );
  577. } else if ( last4 === 'vec3' ) {
  578. return new Vector3( ...params );
  579. } else if ( last4 === 'vec4' ) {
  580. return new Vector4( ...params );
  581. } else if ( last4 === 'mat2' ) {
  582. return new Matrix2( ...params );
  583. } else if ( last4 === 'mat3' ) {
  584. return new Matrix3( ...params );
  585. } else if ( last4 === 'mat4' ) {
  586. return new Matrix4( ...params );
  587. } else if ( type === 'bool' ) {
  588. return params[ 0 ] || false;
  589. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  590. return params[ 0 ] || 0;
  591. } else if ( type === 'string' ) {
  592. return params[ 0 ] || '';
  593. } else if ( type === 'ArrayBuffer' ) {
  594. return base64ToArrayBuffer( params[ 0 ] );
  595. }
  596. return null;
  597. }
  598. /**
  599. * Gets the object data that can be shared between different rendering steps.
  600. *
  601. * @param {Object} object - The object to get the data for.
  602. * @return {Object} The object data.
  603. */
  604. function getDataFromObject( object ) {
  605. let data = dataFromObject.get( object );
  606. if ( data === undefined ) {
  607. data = {};
  608. dataFromObject.set( object, data );
  609. }
  610. return data;
  611. }
  612. /**
  613. * Converts the given array buffer to a Base64 string.
  614. *
  615. * @method
  616. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  617. * @return {string} The Base64 string.
  618. */
  619. function arrayBufferToBase64( arrayBuffer ) {
  620. let chars = '';
  621. const array = new Uint8Array( arrayBuffer );
  622. for ( let i = 0; i < array.length; i ++ ) {
  623. chars += String.fromCharCode( array[ i ] );
  624. }
  625. return btoa( chars );
  626. }
  627. /**
  628. * Converts the given Base64 string to an array buffer.
  629. *
  630. * @method
  631. * @param {string} base64 - The Base64 string.
  632. * @return {ArrayBuffer} The array buffer.
  633. */
  634. function base64ToArrayBuffer( base64 ) {
  635. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  636. }
  637. var NodeUtils = /*#__PURE__*/Object.freeze({
  638. __proto__: null,
  639. arrayBufferToBase64: arrayBufferToBase64,
  640. base64ToArrayBuffer: base64ToArrayBuffer,
  641. getCacheKey: getCacheKey$1,
  642. getDataFromObject: getDataFromObject,
  643. getLengthFromType: getLengthFromType,
  644. getNodeChildren: getNodeChildren,
  645. getTypeFromLength: getTypeFromLength,
  646. getTypedArrayFromType: getTypedArrayFromType,
  647. getValueFromType: getValueFromType,
  648. getValueType: getValueType,
  649. hash: hash$1,
  650. hashArray: hashArray,
  651. hashString: hashString
  652. });
  653. /**
  654. * Possible shader stages.
  655. *
  656. * @property {string} VERTEX The vertex shader stage.
  657. * @property {string} FRAGMENT The fragment shader stage.
  658. */
  659. const NodeShaderStage = {
  660. VERTEX: 'vertex',
  661. FRAGMENT: 'fragment'
  662. };
  663. /**
  664. * Update types of a node.
  665. *
  666. * @property {string} NONE The update method is not executed.
  667. * @property {string} FRAME The update method is executed per frame.
  668. * @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.
  669. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  670. */
  671. const NodeUpdateType = {
  672. NONE: 'none',
  673. FRAME: 'frame',
  674. RENDER: 'render',
  675. OBJECT: 'object'
  676. };
  677. /**
  678. * Data types of a node.
  679. *
  680. * @property {string} BOOLEAN Boolean type.
  681. * @property {string} INTEGER Integer type.
  682. * @property {string} FLOAT Float type.
  683. * @property {string} VECTOR2 Two-dimensional vector type.
  684. * @property {string} VECTOR3 Three-dimensional vector type.
  685. * @property {string} VECTOR4 Four-dimensional vector type.
  686. * @property {string} MATRIX2 2x2 matrix type.
  687. * @property {string} MATRIX3 3x3 matrix type.
  688. * @property {string} MATRIX4 4x4 matrix type.
  689. */
  690. const NodeType = {
  691. BOOLEAN: 'bool',
  692. INTEGER: 'int',
  693. FLOAT: 'float',
  694. VECTOR2: 'vec2',
  695. VECTOR3: 'vec3',
  696. VECTOR4: 'vec4',
  697. MATRIX2: 'mat2',
  698. MATRIX3: 'mat3',
  699. MATRIX4: 'mat4'
  700. };
  701. /**
  702. * Access types of a node. These are relevant for compute and storage usage.
  703. *
  704. * @property {string} READ_ONLY Read-only access
  705. * @property {string} WRITE_ONLY Write-only access.
  706. * @property {string} READ_WRITE Read and write access.
  707. */
  708. const NodeAccess = {
  709. READ_ONLY: 'readOnly',
  710. WRITE_ONLY: 'writeOnly',
  711. READ_WRITE: 'readWrite',
  712. };
  713. const defaultShaderStages = [ 'fragment', 'vertex' ];
  714. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  715. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  716. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  717. let _nodeId = 0;
  718. /**
  719. * Base class for all nodes.
  720. *
  721. * @augments EventDispatcher
  722. */
  723. class Node extends EventDispatcher {
  724. static get type() {
  725. return 'Node';
  726. }
  727. /**
  728. * Constructs a new node.
  729. *
  730. * @param {?string} nodeType - The node type.
  731. */
  732. constructor( nodeType = null ) {
  733. super();
  734. /**
  735. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  736. *
  737. * @type {?string}
  738. * @default null
  739. */
  740. this.nodeType = nodeType;
  741. /**
  742. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  743. *
  744. * @type {string}
  745. * @default 'none'
  746. */
  747. this.updateType = NodeUpdateType.NONE;
  748. /**
  749. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  750. *
  751. * @type {string}
  752. * @default 'none'
  753. */
  754. this.updateBeforeType = NodeUpdateType.NONE;
  755. /**
  756. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  757. *
  758. * @type {string}
  759. * @default 'none'
  760. */
  761. this.updateAfterType = NodeUpdateType.NONE;
  762. /**
  763. * The UUID of the node.
  764. *
  765. * @type {string}
  766. * @readonly
  767. */
  768. this.uuid = MathUtils.generateUUID();
  769. /**
  770. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  771. *
  772. * @type {number}
  773. * @readonly
  774. * @default 0
  775. */
  776. this.version = 0;
  777. /**
  778. * Whether this node is global or not. This property is relevant for the internal
  779. * node caching system. All nodes which should be declared just once should
  780. * set this flag to `true` (a typical example is {@link AttributeNode}).
  781. *
  782. * @type {boolean}
  783. * @default false
  784. */
  785. this.global = false;
  786. /**
  787. * Create a list of parents for this node during the build process.
  788. *
  789. * @type {boolean}
  790. * @default false
  791. */
  792. this.parents = false;
  793. /**
  794. * This flag can be used for type testing.
  795. *
  796. * @type {boolean}
  797. * @readonly
  798. * @default true
  799. */
  800. this.isNode = true;
  801. // private
  802. /**
  803. * The cache key of this node.
  804. *
  805. * @private
  806. * @type {?number}
  807. * @default null
  808. */
  809. this._cacheKey = null;
  810. /**
  811. * The cache key 's version.
  812. *
  813. * @private
  814. * @type {number}
  815. * @default 0
  816. */
  817. this._cacheKeyVersion = 0;
  818. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  819. }
  820. /**
  821. * Set this property to `true` when the node should be regenerated.
  822. *
  823. * @type {boolean}
  824. * @default false
  825. * @param {boolean} value
  826. */
  827. set needsUpdate( value ) {
  828. if ( value === true ) {
  829. this.version ++;
  830. }
  831. }
  832. /**
  833. * The type of the class. The value is usually the constructor name.
  834. *
  835. * @type {string}
  836. * @readonly
  837. */
  838. get type() {
  839. return this.constructor.type;
  840. }
  841. /**
  842. * Convenient method for defining {@link Node#update}.
  843. *
  844. * @param {Function} callback - The update method.
  845. * @param {string} updateType - The update type.
  846. * @return {Node} A reference to this node.
  847. */
  848. onUpdate( callback, updateType ) {
  849. this.updateType = updateType;
  850. this.update = callback.bind( this.getSelf() );
  851. return this;
  852. }
  853. /**
  854. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  855. * this method automatically sets the update type to `FRAME`.
  856. *
  857. * @param {Function} callback - The update method.
  858. * @return {Node} A reference to this node.
  859. */
  860. onFrameUpdate( callback ) {
  861. return this.onUpdate( callback, NodeUpdateType.FRAME );
  862. }
  863. /**
  864. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  865. * this method automatically sets the update type to `RENDER`.
  866. *
  867. * @param {Function} callback - The update method.
  868. * @return {Node} A reference to this node.
  869. */
  870. onRenderUpdate( callback ) {
  871. return this.onUpdate( callback, NodeUpdateType.RENDER );
  872. }
  873. /**
  874. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  875. * this method automatically sets the update type to `OBJECT`.
  876. *
  877. * @param {Function} callback - The update method.
  878. * @return {Node} A reference to this node.
  879. */
  880. onObjectUpdate( callback ) {
  881. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  882. }
  883. /**
  884. * Convenient method for defining {@link Node#updateReference}.
  885. *
  886. * @param {Function} callback - The update method.
  887. * @return {Node} A reference to this node.
  888. */
  889. onReference( callback ) {
  890. this.updateReference = callback.bind( this.getSelf() );
  891. return this;
  892. }
  893. /**
  894. * The `this` reference might point to a Proxy so this method can be used
  895. * to get the reference to the actual node instance.
  896. *
  897. * @return {Node} A reference to the node.
  898. */
  899. getSelf() {
  900. // Returns non-node object.
  901. return this.self || this;
  902. }
  903. /**
  904. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  905. * to such objects based on a given state (e.g. the current node frame or builder).
  906. *
  907. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  908. * @return {any} The updated reference.
  909. */
  910. updateReference( /*state*/ ) {
  911. return this;
  912. }
  913. /**
  914. * By default this method returns the value of the {@link Node#global} flag. This method
  915. * can be overwritten in derived classes if an analytical way is required to determine the
  916. * global status.
  917. *
  918. * @param {NodeBuilder} builder - The current node builder.
  919. * @return {boolean} Whether this node is global or not.
  920. */
  921. isGlobal( /*builder*/ ) {
  922. return this.global;
  923. }
  924. /**
  925. * Generator function that can be used to iterate over the child nodes.
  926. *
  927. * @generator
  928. * @yields {Node} A child node.
  929. */
  930. * getChildren() {
  931. for ( const { childNode } of getNodeChildren( this ) ) {
  932. yield childNode;
  933. }
  934. }
  935. /**
  936. * Calling this method dispatches the `dispose` event. This event can be used
  937. * to register event listeners for clean up tasks.
  938. */
  939. dispose() {
  940. this.dispatchEvent( { type: 'dispose' } );
  941. }
  942. /**
  943. * Callback for {@link Node#traverse}.
  944. *
  945. * @callback traverseCallback
  946. * @param {Node} node - The current node.
  947. */
  948. /**
  949. * Can be used to traverse through the node's hierarchy.
  950. *
  951. * @param {traverseCallback} callback - A callback that is executed per node.
  952. */
  953. traverse( callback ) {
  954. callback( this );
  955. for ( const childNode of this.getChildren() ) {
  956. childNode.traverse( callback );
  957. }
  958. }
  959. /**
  960. * Returns the cache key for this node.
  961. *
  962. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  963. * @return {number} The cache key of the node.
  964. */
  965. getCacheKey( force = false ) {
  966. force = force || this.version !== this._cacheKeyVersion;
  967. if ( force === true || this._cacheKey === null ) {
  968. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  969. this._cacheKeyVersion = this.version;
  970. }
  971. return this._cacheKey;
  972. }
  973. /**
  974. * Generate a custom cache key for this node.
  975. *
  976. * @return {number} The cache key of the node.
  977. */
  978. customCacheKey() {
  979. return 0;
  980. }
  981. /**
  982. * Returns the references to this node which is by default `this`.
  983. *
  984. * @return {Node} A reference to this node.
  985. */
  986. getScope() {
  987. return this;
  988. }
  989. /**
  990. * Returns the hash of the node which is used to identify the node. By default it's
  991. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  992. * depending on their implementation.
  993. *
  994. * @param {NodeBuilder} builder - The current node builder.
  995. * @return {string} The hash.
  996. */
  997. getHash( /*builder*/ ) {
  998. return this.uuid;
  999. }
  1000. /**
  1001. * Returns the update type of {@link Node#update}.
  1002. *
  1003. * @return {NodeUpdateType} The update type.
  1004. */
  1005. getUpdateType() {
  1006. return this.updateType;
  1007. }
  1008. /**
  1009. * Returns the update type of {@link Node#updateBefore}.
  1010. *
  1011. * @return {NodeUpdateType} The update type.
  1012. */
  1013. getUpdateBeforeType() {
  1014. return this.updateBeforeType;
  1015. }
  1016. /**
  1017. * Returns the update type of {@link Node#updateAfter}.
  1018. *
  1019. * @return {NodeUpdateType} The update type.
  1020. */
  1021. getUpdateAfterType() {
  1022. return this.updateAfterType;
  1023. }
  1024. /**
  1025. * Certain types are composed of multiple elements. For example a `vec3`
  1026. * is composed of three `float` values. This method returns the type of
  1027. * these elements.
  1028. *
  1029. * @param {NodeBuilder} builder - The current node builder.
  1030. * @return {string} The type of the node.
  1031. */
  1032. getElementType( builder ) {
  1033. const type = this.getNodeType( builder );
  1034. const elementType = builder.getElementType( type );
  1035. return elementType;
  1036. }
  1037. /**
  1038. * Returns the node member type for the given name.
  1039. *
  1040. * @param {NodeBuilder} builder - The current node builder.
  1041. * @param {string} name - The name of the member.
  1042. * @return {string} The type of the node.
  1043. */
  1044. getMemberType( /*builder, name*/ ) {
  1045. return 'void';
  1046. }
  1047. /**
  1048. * Returns the node's type.
  1049. *
  1050. * @param {NodeBuilder} builder - The current node builder.
  1051. * @return {string} The type of the node.
  1052. */
  1053. getNodeType( builder ) {
  1054. const nodeProperties = builder.getNodeProperties( this );
  1055. if ( nodeProperties.outputNode ) {
  1056. return nodeProperties.outputNode.getNodeType( builder );
  1057. }
  1058. return this.nodeType;
  1059. }
  1060. /**
  1061. * This method is used during the build process of a node and ensures
  1062. * equal nodes are not built multiple times but just once. For example if
  1063. * `attribute( 'uv' )` is used multiple times by the user, the build
  1064. * process makes sure to process just the first node.
  1065. *
  1066. * @param {NodeBuilder} builder - The current node builder.
  1067. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1068. */
  1069. getShared( builder ) {
  1070. const hash = this.getHash( builder );
  1071. const nodeFromHash = builder.getNodeFromHash( hash );
  1072. return nodeFromHash || this;
  1073. }
  1074. /**
  1075. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1076. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1077. * The output node must be returned in the `return` statement.
  1078. *
  1079. * @param {NodeBuilder} builder - The current node builder.
  1080. * @return {?Node} The output node.
  1081. */
  1082. setup( builder ) {
  1083. const nodeProperties = builder.getNodeProperties( this );
  1084. let index = 0;
  1085. for ( const childNode of this.getChildren() ) {
  1086. nodeProperties[ 'node' + index ++ ] = childNode;
  1087. }
  1088. // return a outputNode if exists or null
  1089. return nodeProperties.outputNode || null;
  1090. }
  1091. /**
  1092. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1093. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1094. *
  1095. * @param {NodeBuilder} builder - The current node builder.
  1096. */
  1097. analyze( builder ) {
  1098. const usageCount = builder.increaseUsage( this );
  1099. if ( usageCount === 1 ) {
  1100. // node flow children
  1101. const nodeProperties = builder.getNodeProperties( this );
  1102. for ( const childNode of Object.values( nodeProperties ) ) {
  1103. if ( childNode && childNode.isNode === true ) {
  1104. childNode.build( builder );
  1105. }
  1106. }
  1107. }
  1108. }
  1109. /**
  1110. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1111. * This state builds the output node and returns the resulting shader string.
  1112. *
  1113. * @param {NodeBuilder} builder - The current node builder.
  1114. * @param {?string} output - Can be used to define the output type.
  1115. * @return {?string} The generated shader string.
  1116. */
  1117. generate( builder, output ) {
  1118. const { outputNode } = builder.getNodeProperties( this );
  1119. if ( outputNode && outputNode.isNode === true ) {
  1120. return outputNode.build( builder, output );
  1121. }
  1122. }
  1123. /**
  1124. * The method can be implemented to update the node's internal state before it is used to render an object.
  1125. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1126. *
  1127. * @abstract
  1128. * @param {NodeFrame} frame - A reference to the current node frame.
  1129. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1130. */
  1131. updateBefore( /*frame*/ ) {
  1132. console.warn( 'Abstract function.' );
  1133. }
  1134. /**
  1135. * The method can be implemented to update the node's internal state after it was used to render an object.
  1136. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1137. *
  1138. * @abstract
  1139. * @param {NodeFrame} frame - A reference to the current node frame.
  1140. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1141. */
  1142. updateAfter( /*frame*/ ) {
  1143. console.warn( 'Abstract function.' );
  1144. }
  1145. /**
  1146. * The method can be implemented to update the node's internal state when it is used to render an object.
  1147. * The {@link Node#updateType} property defines how often the update is executed.
  1148. *
  1149. * @abstract
  1150. * @param {NodeFrame} frame - A reference to the current node frame.
  1151. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1152. */
  1153. update( /*frame*/ ) {
  1154. console.warn( 'Abstract function.' );
  1155. }
  1156. /**
  1157. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1158. * - **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.
  1159. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1160. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1161. *
  1162. * @param {NodeBuilder} builder - The current node builder.
  1163. * @param {?string} [output=null] - Can be used to define the output type.
  1164. * @return {Node|string|null} The result of the build process, depending on the build stage.
  1165. */
  1166. build( builder, output = null ) {
  1167. const refNode = this.getShared( builder );
  1168. if ( this !== refNode ) {
  1169. return refNode.build( builder, output );
  1170. }
  1171. builder.addNode( this );
  1172. builder.addChain( this );
  1173. /* Build stages expected results:
  1174. - "setup" -> Node
  1175. - "analyze" -> null
  1176. - "generate" -> String
  1177. */
  1178. let result = null;
  1179. const buildStage = builder.getBuildStage();
  1180. if ( buildStage === 'setup' ) {
  1181. this.updateReference( builder );
  1182. const properties = builder.getNodeProperties( this );
  1183. if ( properties.initialized !== true ) {
  1184. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1185. properties.initialized = true;
  1186. const outputNode = this.setup( builder ); // return a node or null
  1187. const isNodeOutput = outputNode && outputNode.isNode === true;
  1188. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1189. // !! no outputNode !!
  1190. //outputNode = builder.stack;
  1191. }*/
  1192. for ( const childNode of Object.values( properties ) ) {
  1193. if ( childNode && childNode.isNode === true ) {
  1194. if ( childNode.parents === true ) {
  1195. const childProperties = builder.getNodeProperties( childNode );
  1196. childProperties.parents = childProperties.parents || [];
  1197. childProperties.parents.push( this );
  1198. }
  1199. childNode.build( builder );
  1200. }
  1201. }
  1202. if ( isNodeOutput ) {
  1203. outputNode.build( builder );
  1204. }
  1205. properties.outputNode = outputNode;
  1206. }
  1207. result = properties.outputNode || null;
  1208. } else if ( buildStage === 'analyze' ) {
  1209. this.analyze( builder );
  1210. } else if ( buildStage === 'generate' ) {
  1211. const isGenerateOnce = this.generate.length === 1;
  1212. if ( isGenerateOnce ) {
  1213. const type = this.getNodeType( builder );
  1214. const nodeData = builder.getDataFromNode( this );
  1215. result = nodeData.snippet;
  1216. if ( result === undefined ) {
  1217. if ( nodeData.generated === undefined ) {
  1218. nodeData.generated = true;
  1219. result = this.generate( builder ) || '';
  1220. nodeData.snippet = result;
  1221. } else {
  1222. console.warn( 'THREE.Node: Recursion detected.', this );
  1223. result = '';
  1224. }
  1225. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1226. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1227. }
  1228. result = builder.format( result, type, output );
  1229. } else {
  1230. result = this.generate( builder, output ) || '';
  1231. }
  1232. }
  1233. builder.removeChain( this );
  1234. builder.addSequentialNode( this );
  1235. return result;
  1236. }
  1237. /**
  1238. * Returns the child nodes as a JSON object.
  1239. *
  1240. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1241. */
  1242. getSerializeChildren() {
  1243. return getNodeChildren( this );
  1244. }
  1245. /**
  1246. * Serializes the node to JSON.
  1247. *
  1248. * @param {Object} json - The output JSON object.
  1249. */
  1250. serialize( json ) {
  1251. const nodeChildren = this.getSerializeChildren();
  1252. const inputNodes = {};
  1253. for ( const { property, index, childNode } of nodeChildren ) {
  1254. if ( index !== undefined ) {
  1255. if ( inputNodes[ property ] === undefined ) {
  1256. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1257. }
  1258. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1259. } else {
  1260. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1261. }
  1262. }
  1263. if ( Object.keys( inputNodes ).length > 0 ) {
  1264. json.inputNodes = inputNodes;
  1265. }
  1266. }
  1267. /**
  1268. * Deserializes the node from the given JSON.
  1269. *
  1270. * @param {Object} json - The JSON object.
  1271. */
  1272. deserialize( json ) {
  1273. if ( json.inputNodes !== undefined ) {
  1274. const nodes = json.meta.nodes;
  1275. for ( const property in json.inputNodes ) {
  1276. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1277. const inputArray = [];
  1278. for ( const uuid of json.inputNodes[ property ] ) {
  1279. inputArray.push( nodes[ uuid ] );
  1280. }
  1281. this[ property ] = inputArray;
  1282. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1283. const inputObject = {};
  1284. for ( const subProperty in json.inputNodes[ property ] ) {
  1285. const uuid = json.inputNodes[ property ][ subProperty ];
  1286. inputObject[ subProperty ] = nodes[ uuid ];
  1287. }
  1288. this[ property ] = inputObject;
  1289. } else {
  1290. const uuid = json.inputNodes[ property ];
  1291. this[ property ] = nodes[ uuid ];
  1292. }
  1293. }
  1294. }
  1295. }
  1296. /**
  1297. * Serializes the node into the three.js JSON Object/Scene format.
  1298. *
  1299. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1300. * @return {Object} The serialized node.
  1301. */
  1302. toJSON( meta ) {
  1303. const { uuid, type } = this;
  1304. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1305. if ( isRoot ) {
  1306. meta = {
  1307. textures: {},
  1308. images: {},
  1309. nodes: {}
  1310. };
  1311. }
  1312. // serialize
  1313. let data = meta.nodes[ uuid ];
  1314. if ( data === undefined ) {
  1315. data = {
  1316. uuid,
  1317. type,
  1318. meta,
  1319. metadata: {
  1320. version: 4.6,
  1321. type: 'Node',
  1322. generator: 'Node.toJSON'
  1323. }
  1324. };
  1325. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1326. this.serialize( data );
  1327. delete data.meta;
  1328. }
  1329. // TODO: Copied from Object3D.toJSON
  1330. function extractFromCache( cache ) {
  1331. const values = [];
  1332. for ( const key in cache ) {
  1333. const data = cache[ key ];
  1334. delete data.metadata;
  1335. values.push( data );
  1336. }
  1337. return values;
  1338. }
  1339. if ( isRoot ) {
  1340. const textures = extractFromCache( meta.textures );
  1341. const images = extractFromCache( meta.images );
  1342. const nodes = extractFromCache( meta.nodes );
  1343. if ( textures.length > 0 ) data.textures = textures;
  1344. if ( images.length > 0 ) data.images = images;
  1345. if ( nodes.length > 0 ) data.nodes = nodes;
  1346. }
  1347. return data;
  1348. }
  1349. }
  1350. /**
  1351. * Base class for representing element access on an array-like
  1352. * node data structures.
  1353. *
  1354. * @augments Node
  1355. */
  1356. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1357. static get type() {
  1358. return 'ArrayElementNode';
  1359. }
  1360. /**
  1361. * Constructs an array element node.
  1362. *
  1363. * @param {Node} node - The array-like node.
  1364. * @param {Node} indexNode - The index node that defines the element access.
  1365. */
  1366. constructor( node, indexNode ) {
  1367. super();
  1368. /**
  1369. * The array-like node.
  1370. *
  1371. * @type {Node}
  1372. */
  1373. this.node = node;
  1374. /**
  1375. * The index node that defines the element access.
  1376. *
  1377. * @type {Node}
  1378. */
  1379. this.indexNode = indexNode;
  1380. /**
  1381. * This flag can be used for type testing.
  1382. *
  1383. * @type {boolean}
  1384. * @readonly
  1385. * @default true
  1386. */
  1387. this.isArrayElementNode = true;
  1388. }
  1389. /**
  1390. * This method is overwritten since the node type is inferred from the array-like node.
  1391. *
  1392. * @param {NodeBuilder} builder - The current node builder.
  1393. * @return {string} The node type.
  1394. */
  1395. getNodeType( builder ) {
  1396. return this.node.getElementType( builder );
  1397. }
  1398. generate( builder ) {
  1399. const indexType = this.indexNode.getNodeType( builder );
  1400. const nodeSnippet = this.node.build( builder );
  1401. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1402. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1403. }
  1404. }
  1405. /**
  1406. * This module is part of the TSL core and usually not used in app level code.
  1407. * It represents a convert operation during the shader generation process
  1408. * meaning it converts the data type of a node to a target data type.
  1409. *
  1410. * @augments Node
  1411. */
  1412. class ConvertNode extends Node {
  1413. static get type() {
  1414. return 'ConvertNode';
  1415. }
  1416. /**
  1417. * Constructs a new convert node.
  1418. *
  1419. * @param {Node} node - The node which type should be converted.
  1420. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1421. */
  1422. constructor( node, convertTo ) {
  1423. super();
  1424. /**
  1425. * The node which type should be converted.
  1426. *
  1427. * @type {Node}
  1428. */
  1429. this.node = node;
  1430. /**
  1431. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1432. *
  1433. * @type {string}
  1434. */
  1435. this.convertTo = convertTo;
  1436. }
  1437. /**
  1438. * This method is overwritten since the implementation tries to infer the best
  1439. * matching type from the {@link ConvertNode#convertTo} property.
  1440. *
  1441. * @param {NodeBuilder} builder - The current node builder.
  1442. * @return {string} The node type.
  1443. */
  1444. getNodeType( builder ) {
  1445. const requestType = this.node.getNodeType( builder );
  1446. let convertTo = null;
  1447. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1448. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1449. convertTo = overloadingType;
  1450. }
  1451. }
  1452. return convertTo;
  1453. }
  1454. serialize( data ) {
  1455. super.serialize( data );
  1456. data.convertTo = this.convertTo;
  1457. }
  1458. deserialize( data ) {
  1459. super.deserialize( data );
  1460. this.convertTo = data.convertTo;
  1461. }
  1462. generate( builder, output ) {
  1463. const node = this.node;
  1464. const type = this.getNodeType( builder );
  1465. const snippet = node.build( builder, type );
  1466. return builder.format( snippet, type, output );
  1467. }
  1468. }
  1469. /**
  1470. * This module uses cache management to create temporary variables
  1471. * if the node is used more than once to prevent duplicate calculations.
  1472. *
  1473. * The class acts as a base class for many other nodes types.
  1474. *
  1475. * @augments Node
  1476. */
  1477. class TempNode extends Node {
  1478. static get type() {
  1479. return 'TempNode';
  1480. }
  1481. /**
  1482. * Constructs a temp node.
  1483. *
  1484. * @param {?string} nodeType - The node type.
  1485. */
  1486. constructor( nodeType = null ) {
  1487. super( nodeType );
  1488. /**
  1489. * This flag can be used for type testing.
  1490. *
  1491. * @type {boolean}
  1492. * @readonly
  1493. * @default true
  1494. */
  1495. this.isTempNode = true;
  1496. }
  1497. /**
  1498. * Whether this node is used more than once in context of other nodes.
  1499. *
  1500. * @param {NodeBuilder} builder - The node builder.
  1501. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1502. */
  1503. hasDependencies( builder ) {
  1504. return builder.getDataFromNode( this ).usageCount > 1;
  1505. }
  1506. build( builder, output ) {
  1507. const buildStage = builder.getBuildStage();
  1508. if ( buildStage === 'generate' ) {
  1509. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1510. const nodeData = builder.getDataFromNode( this );
  1511. if ( nodeData.propertyName !== undefined ) {
  1512. return builder.format( nodeData.propertyName, type, output );
  1513. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1514. const snippet = super.build( builder, type );
  1515. const nodeVar = builder.getVarFromNode( this, null, type );
  1516. const propertyName = builder.getPropertyName( nodeVar );
  1517. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1518. nodeData.snippet = snippet;
  1519. nodeData.propertyName = propertyName;
  1520. return builder.format( nodeData.propertyName, type, output );
  1521. }
  1522. }
  1523. return super.build( builder, output );
  1524. }
  1525. }
  1526. /**
  1527. * This module is part of the TSL core and usually not used in app level code.
  1528. * It represents a join operation during the shader generation process.
  1529. * For example in can compose/join two single floats into a `vec2` type.
  1530. *
  1531. * @augments TempNode
  1532. */
  1533. class JoinNode extends TempNode {
  1534. static get type() {
  1535. return 'JoinNode';
  1536. }
  1537. /**
  1538. * Constructs a new join node.
  1539. *
  1540. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1541. * @param {?string} [nodeType=null] - The node type.
  1542. */
  1543. constructor( nodes = [], nodeType = null ) {
  1544. super( nodeType );
  1545. /**
  1546. * An array of nodes that should be joined.
  1547. *
  1548. * @type {Array<Node>}
  1549. */
  1550. this.nodes = nodes;
  1551. }
  1552. /**
  1553. * This method is overwritten since the node type must be inferred from the
  1554. * joined data length if not explicitly defined.
  1555. *
  1556. * @param {NodeBuilder} builder - The current node builder.
  1557. * @return {string} The node type.
  1558. */
  1559. getNodeType( builder ) {
  1560. if ( this.nodeType !== null ) {
  1561. return builder.getVectorType( this.nodeType );
  1562. }
  1563. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1564. }
  1565. generate( builder, output ) {
  1566. const type = this.getNodeType( builder );
  1567. const maxLength = builder.getTypeLength( type );
  1568. const nodes = this.nodes;
  1569. const primitiveType = builder.getComponentType( type );
  1570. const snippetValues = [];
  1571. let length = 0;
  1572. for ( const input of nodes ) {
  1573. if ( length >= maxLength ) {
  1574. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1575. break;
  1576. }
  1577. let inputType = input.getNodeType( builder );
  1578. let inputTypeLength = builder.getTypeLength( inputType );
  1579. let inputSnippet;
  1580. if ( length + inputTypeLength > maxLength ) {
  1581. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1582. inputTypeLength = maxLength - length;
  1583. inputType = builder.getTypeFromLength( inputTypeLength );
  1584. }
  1585. length += inputTypeLength;
  1586. inputSnippet = input.build( builder, inputType );
  1587. const inputPrimitiveType = builder.getComponentType( inputType );
  1588. if ( inputPrimitiveType !== primitiveType ) {
  1589. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1590. }
  1591. snippetValues.push( inputSnippet );
  1592. }
  1593. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1594. return builder.format( snippet, type, output );
  1595. }
  1596. }
  1597. const _stringVectorComponents = vectorComponents.join( '' );
  1598. /**
  1599. * This module is part of the TSL core and usually not used in app level code.
  1600. * `SplitNode` represents a property access operation which means it is
  1601. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1602. * For example:
  1603. * ```js
  1604. * const redValue = color.r;
  1605. * ```
  1606. *
  1607. * @augments Node
  1608. */
  1609. class SplitNode extends Node {
  1610. static get type() {
  1611. return 'SplitNode';
  1612. }
  1613. /**
  1614. * Constructs a new split node.
  1615. *
  1616. * @param {Node} node - The node that should be accessed.
  1617. * @param {string} [components='x'] - The components that should be accessed.
  1618. */
  1619. constructor( node, components = 'x' ) {
  1620. super();
  1621. /**
  1622. * The node that should be accessed.
  1623. *
  1624. * @type {Node}
  1625. */
  1626. this.node = node;
  1627. /**
  1628. * The components that should be accessed.
  1629. *
  1630. * @type {string}
  1631. */
  1632. this.components = components;
  1633. /**
  1634. * This flag can be used for type testing.
  1635. *
  1636. * @type {boolean}
  1637. * @readonly
  1638. * @default true
  1639. */
  1640. this.isSplitNode = true;
  1641. }
  1642. /**
  1643. * Returns the vector length which is computed based on the requested components.
  1644. *
  1645. * @return {number} The vector length.
  1646. */
  1647. getVectorLength() {
  1648. let vectorLength = this.components.length;
  1649. for ( const c of this.components ) {
  1650. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1651. }
  1652. return vectorLength;
  1653. }
  1654. /**
  1655. * Returns the component type of the node's type.
  1656. *
  1657. * @param {NodeBuilder} builder - The current node builder.
  1658. * @return {string} The component type.
  1659. */
  1660. getComponentType( builder ) {
  1661. return builder.getComponentType( this.node.getNodeType( builder ) );
  1662. }
  1663. /**
  1664. * This method is overwritten since the node type is inferred from requested components.
  1665. *
  1666. * @param {NodeBuilder} builder - The current node builder.
  1667. * @return {string} The node type.
  1668. */
  1669. getNodeType( builder ) {
  1670. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1671. }
  1672. generate( builder, output ) {
  1673. const node = this.node;
  1674. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1675. let snippet = null;
  1676. if ( nodeTypeLength > 1 ) {
  1677. let type = null;
  1678. const componentsLength = this.getVectorLength();
  1679. if ( componentsLength >= nodeTypeLength ) {
  1680. // needed expand the input node
  1681. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1682. }
  1683. const nodeSnippet = node.build( builder, type );
  1684. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1685. // unnecessary swizzle
  1686. snippet = builder.format( nodeSnippet, type, output );
  1687. } else {
  1688. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1689. }
  1690. } else {
  1691. // ignore .components if .node returns float/integer
  1692. snippet = node.build( builder, output );
  1693. }
  1694. return snippet;
  1695. }
  1696. serialize( data ) {
  1697. super.serialize( data );
  1698. data.components = this.components;
  1699. }
  1700. deserialize( data ) {
  1701. super.deserialize( data );
  1702. this.components = data.components;
  1703. }
  1704. }
  1705. /**
  1706. * This module is part of the TSL core and usually not used in app level code.
  1707. * `SetNode` represents a set operation which means it is used to implement any
  1708. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1709. * For example:
  1710. * ```js
  1711. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1712. * ```
  1713. *
  1714. * @augments TempNode
  1715. */
  1716. class SetNode extends TempNode {
  1717. static get type() {
  1718. return 'SetNode';
  1719. }
  1720. /**
  1721. * Constructs a new set node.
  1722. *
  1723. * @param {Node} sourceNode - The node that should be updated.
  1724. * @param {string} components - The components that should be updated.
  1725. * @param {Node} targetNode - The value node.
  1726. */
  1727. constructor( sourceNode, components, targetNode ) {
  1728. super();
  1729. /**
  1730. * The node that should be updated.
  1731. *
  1732. * @type {Node}
  1733. */
  1734. this.sourceNode = sourceNode;
  1735. /**
  1736. * The components that should be updated.
  1737. *
  1738. * @type {string}
  1739. */
  1740. this.components = components;
  1741. /**
  1742. * The value node.
  1743. *
  1744. * @type {Node}
  1745. */
  1746. this.targetNode = targetNode;
  1747. }
  1748. /**
  1749. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1750. *
  1751. * @param {NodeBuilder} builder - The current node builder.
  1752. * @return {string} The node type.
  1753. */
  1754. getNodeType( builder ) {
  1755. return this.sourceNode.getNodeType( builder );
  1756. }
  1757. generate( builder ) {
  1758. const { sourceNode, components, targetNode } = this;
  1759. const sourceType = this.getNodeType( builder );
  1760. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1761. const targetType = builder.getTypeFromLength( components.length, componentType );
  1762. const targetSnippet = targetNode.build( builder, targetType );
  1763. const sourceSnippet = sourceNode.build( builder, sourceType );
  1764. const length = builder.getTypeLength( sourceType );
  1765. const snippetValues = [];
  1766. for ( let i = 0; i < length; i ++ ) {
  1767. const component = vectorComponents[ i ];
  1768. if ( component === components[ 0 ] ) {
  1769. snippetValues.push( targetSnippet );
  1770. i += components.length - 1;
  1771. } else {
  1772. snippetValues.push( sourceSnippet + '.' + component );
  1773. }
  1774. }
  1775. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1776. }
  1777. }
  1778. /**
  1779. * This module is part of the TSL core and usually not used in app level code.
  1780. * It represents a flip operation during the shader generation process
  1781. * meaning it flips normalized values with the following formula:
  1782. * ```
  1783. * x = 1 - x;
  1784. * ```
  1785. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1786. * `flipSTPQ()` method invocations on node objects. For example:
  1787. * ```js
  1788. * uvNode = uvNode.flipY();
  1789. * ```
  1790. *
  1791. * @augments TempNode
  1792. */
  1793. class FlipNode extends TempNode {
  1794. static get type() {
  1795. return 'FlipNode';
  1796. }
  1797. /**
  1798. * Constructs a new flip node.
  1799. *
  1800. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1801. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1802. */
  1803. constructor( sourceNode, components ) {
  1804. super();
  1805. /**
  1806. * The node which component(s) should be flipped.
  1807. *
  1808. * @type {Node}
  1809. */
  1810. this.sourceNode = sourceNode;
  1811. /**
  1812. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1813. *
  1814. * @type {string}
  1815. */
  1816. this.components = components;
  1817. }
  1818. /**
  1819. * This method is overwritten since the node type is inferred from the source node.
  1820. *
  1821. * @param {NodeBuilder} builder - The current node builder.
  1822. * @return {string} The node type.
  1823. */
  1824. getNodeType( builder ) {
  1825. return this.sourceNode.getNodeType( builder );
  1826. }
  1827. generate( builder ) {
  1828. const { components, sourceNode } = this;
  1829. const sourceType = this.getNodeType( builder );
  1830. const sourceSnippet = sourceNode.build( builder );
  1831. const sourceCache = builder.getVarFromNode( this );
  1832. const sourceProperty = builder.getPropertyName( sourceCache );
  1833. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1834. const length = builder.getTypeLength( sourceType );
  1835. const snippetValues = [];
  1836. let componentIndex = 0;
  1837. for ( let i = 0; i < length; i ++ ) {
  1838. const component = vectorComponents[ i ];
  1839. if ( component === components[ componentIndex ] ) {
  1840. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1841. componentIndex ++;
  1842. } else {
  1843. snippetValues.push( sourceProperty + '.' + component );
  1844. }
  1845. }
  1846. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1847. }
  1848. }
  1849. /**
  1850. * Base class for representing data input nodes.
  1851. *
  1852. * @augments Node
  1853. */
  1854. class InputNode extends Node {
  1855. static get type() {
  1856. return 'InputNode';
  1857. }
  1858. /**
  1859. * Constructs a new input node.
  1860. *
  1861. * @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).
  1862. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1863. */
  1864. constructor( value, nodeType = null ) {
  1865. super( nodeType );
  1866. /**
  1867. * This flag can be used for type testing.
  1868. *
  1869. * @type {boolean}
  1870. * @readonly
  1871. * @default true
  1872. */
  1873. this.isInputNode = true;
  1874. /**
  1875. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1876. *
  1877. * @type {any}
  1878. */
  1879. this.value = value;
  1880. /**
  1881. * The precision of the value in the shader.
  1882. *
  1883. * @type {?('low'|'medium'|'high')}
  1884. * @default null
  1885. */
  1886. this.precision = null;
  1887. }
  1888. getNodeType( /*builder*/ ) {
  1889. if ( this.nodeType === null ) {
  1890. return getValueType( this.value );
  1891. }
  1892. return this.nodeType;
  1893. }
  1894. /**
  1895. * Returns the input type of the node which is by default the node type. Derived modules
  1896. * might overwrite this method and use a fixed type or compute one analytically.
  1897. *
  1898. * A typical example for different input and node types are textures. The input type of a
  1899. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1900. *
  1901. * @param {NodeBuilder} builder - The current node builder.
  1902. * @return {string} The input type.
  1903. */
  1904. getInputType( builder ) {
  1905. return this.getNodeType( builder );
  1906. }
  1907. /**
  1908. * Sets the precision to the given value. The method can be
  1909. * overwritten in derived classes if the final precision must be computed
  1910. * analytically.
  1911. *
  1912. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1913. * @return {InputNode} A reference to this node.
  1914. */
  1915. setPrecision( precision ) {
  1916. this.precision = precision;
  1917. return this;
  1918. }
  1919. serialize( data ) {
  1920. super.serialize( data );
  1921. data.value = this.value;
  1922. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1923. data.valueType = getValueType( this.value );
  1924. data.nodeType = this.nodeType;
  1925. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1926. data.precision = this.precision;
  1927. }
  1928. deserialize( data ) {
  1929. super.deserialize( data );
  1930. this.nodeType = data.nodeType;
  1931. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1932. this.precision = data.precision || null;
  1933. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1934. }
  1935. generate( /*builder, output*/ ) {
  1936. console.warn( 'Abstract function.' );
  1937. }
  1938. }
  1939. const _regNum = /float|u?int/;
  1940. /**
  1941. * Class for representing a constant value in the shader.
  1942. *
  1943. * @augments InputNode
  1944. */
  1945. class ConstNode extends InputNode {
  1946. static get type() {
  1947. return 'ConstNode';
  1948. }
  1949. /**
  1950. * Constructs a new input node.
  1951. *
  1952. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1953. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1954. */
  1955. constructor( value, nodeType = null ) {
  1956. super( value, nodeType );
  1957. /**
  1958. * This flag can be used for type testing.
  1959. *
  1960. * @type {boolean}
  1961. * @readonly
  1962. * @default true
  1963. */
  1964. this.isConstNode = true;
  1965. }
  1966. /**
  1967. * Generates the shader string of the value with the current node builder.
  1968. *
  1969. * @param {NodeBuilder} builder - The current node builder.
  1970. * @return {string} The generated value as a shader string.
  1971. */
  1972. generateConst( builder ) {
  1973. return builder.generateConst( this.getNodeType( builder ), this.value );
  1974. }
  1975. generate( builder, output ) {
  1976. const type = this.getNodeType( builder );
  1977. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  1978. return builder.generateConst( output, this.value );
  1979. }
  1980. return builder.format( this.generateConst( builder ), type, output );
  1981. }
  1982. }
  1983. /**
  1984. * Base class for representing member access on an object-like
  1985. * node data structures.
  1986. *
  1987. * @augments Node
  1988. */
  1989. class MemberNode extends Node {
  1990. static get type() {
  1991. return 'MemberNode';
  1992. }
  1993. /**
  1994. * Constructs an array element node.
  1995. *
  1996. * @param {Node} node - The array-like node.
  1997. * @param {string} property - The property name.
  1998. */
  1999. constructor( node, property ) {
  2000. super();
  2001. /**
  2002. * The array-like node.
  2003. *
  2004. * @type {Node}
  2005. */
  2006. this.node = node;
  2007. /**
  2008. * The property name.
  2009. *
  2010. * @type {Node}
  2011. */
  2012. this.property = property;
  2013. /**
  2014. * This flag can be used for type testing.
  2015. *
  2016. * @type {boolean}
  2017. * @readonly
  2018. * @default true
  2019. */
  2020. this.isMemberNode = true;
  2021. }
  2022. getNodeType( builder ) {
  2023. return this.node.getMemberType( builder, this.property );
  2024. }
  2025. generate( builder ) {
  2026. const propertyName = this.node.build( builder );
  2027. return propertyName + '.' + this.property;
  2028. }
  2029. }
  2030. let currentStack = null;
  2031. const NodeElements = new Map();
  2032. function addMethodChaining( name, nodeElement ) {
  2033. if ( NodeElements.has( name ) ) {
  2034. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2035. return;
  2036. }
  2037. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2038. NodeElements.set( name, nodeElement );
  2039. }
  2040. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2041. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2042. const shaderNodeHandler = {
  2043. setup( NodeClosure, params ) {
  2044. const inputs = params.shift();
  2045. return NodeClosure( nodeObjects( inputs ), ...params );
  2046. },
  2047. get( node, prop, nodeObj ) {
  2048. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2049. if ( node.isStackNode !== true && prop === 'assign' ) {
  2050. return ( ...params ) => {
  2051. currentStack.assign( nodeObj, ...params );
  2052. return nodeObj;
  2053. };
  2054. } else if ( NodeElements.has( prop ) ) {
  2055. const nodeElement = NodeElements.get( prop );
  2056. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2057. } else if ( prop === 'self' ) {
  2058. return node;
  2059. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2060. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2061. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2062. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2063. // accessing properties ( swizzle )
  2064. prop = parseSwizzle( prop );
  2065. return nodeObject( new SplitNode( nodeObj, prop ) );
  2066. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2067. // set properties ( swizzle ) and sort to xyzw sequence
  2068. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2069. return ( value ) => nodeObject( new SetNode( node, prop, nodeObject( value ) ) );
  2070. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2071. // set properties ( swizzle ) and sort to xyzw sequence
  2072. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2073. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2074. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2075. // accessing property
  2076. if ( prop === 'width' ) prop = 'x';
  2077. else if ( prop === 'height' ) prop = 'y';
  2078. else if ( prop === 'depth' ) prop = 'z';
  2079. return nodeObject( new SplitNode( node, prop ) );
  2080. } else if ( /^\d+$/.test( prop ) === true ) {
  2081. // accessing array
  2082. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2083. } else if ( /^get$/.test( prop ) === true ) {
  2084. // accessing properties
  2085. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2086. }
  2087. }
  2088. return Reflect.get( node, prop, nodeObj );
  2089. },
  2090. set( node, prop, value, nodeObj ) {
  2091. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2092. // setting properties
  2093. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2094. nodeObj[ prop ].assign( value );
  2095. return true;
  2096. }
  2097. }
  2098. return Reflect.set( node, prop, value, nodeObj );
  2099. }
  2100. };
  2101. const nodeObjectsCacheMap = new WeakMap();
  2102. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2103. const ShaderNodeObject = function ( obj, altType = null ) {
  2104. const type = getValueType( obj );
  2105. if ( type === 'node' ) {
  2106. let nodeObject = nodeObjectsCacheMap.get( obj );
  2107. if ( nodeObject === undefined ) {
  2108. nodeObject = new Proxy( obj, shaderNodeHandler );
  2109. nodeObjectsCacheMap.set( obj, nodeObject );
  2110. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2111. }
  2112. return nodeObject;
  2113. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2114. return nodeObject( getConstNode( obj, altType ) );
  2115. } else if ( type === 'shader' ) {
  2116. return Fn( obj );
  2117. }
  2118. return obj;
  2119. };
  2120. const ShaderNodeObjects = function ( objects, altType = null ) {
  2121. for ( const name in objects ) {
  2122. objects[ name ] = nodeObject( objects[ name ], altType );
  2123. }
  2124. return objects;
  2125. };
  2126. const ShaderNodeArray = function ( array, altType = null ) {
  2127. const len = array.length;
  2128. for ( let i = 0; i < len; i ++ ) {
  2129. array[ i ] = nodeObject( array[ i ], altType );
  2130. }
  2131. return array;
  2132. };
  2133. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2134. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2135. let fn, name = scope, minParams, maxParams;
  2136. function verifyParamsLimit( params ) {
  2137. let tslName;
  2138. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2139. else tslName = NodeClass.type;
  2140. if ( minParams !== undefined && params.length < minParams ) {
  2141. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2142. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2143. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2144. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2145. return params.slice( 0, maxParams );
  2146. }
  2147. return params;
  2148. }
  2149. if ( scope === null ) {
  2150. fn = ( ...params ) => {
  2151. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2152. };
  2153. } else if ( factor !== null ) {
  2154. factor = nodeObject( factor );
  2155. fn = ( ...params ) => {
  2156. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2157. };
  2158. } else {
  2159. fn = ( ...params ) => {
  2160. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2161. };
  2162. }
  2163. fn.setParameterLength = ( ...params ) => {
  2164. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2165. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2166. return fn;
  2167. };
  2168. fn.setName = ( value ) => {
  2169. name = value;
  2170. return fn;
  2171. };
  2172. return fn;
  2173. };
  2174. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2175. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2176. };
  2177. class ShaderCallNodeInternal extends Node {
  2178. constructor( shaderNode, inputNodes ) {
  2179. super();
  2180. this.shaderNode = shaderNode;
  2181. this.inputNodes = inputNodes;
  2182. this.isShaderCallNodeInternal = true;
  2183. }
  2184. getNodeType( builder ) {
  2185. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2186. }
  2187. getMemberType( builder, name ) {
  2188. return this.getOutputNode( builder ).getMemberType( builder, name );
  2189. }
  2190. call( builder ) {
  2191. const { shaderNode, inputNodes } = this;
  2192. const properties = builder.getNodeProperties( shaderNode );
  2193. if ( properties.onceOutput ) return properties.onceOutput;
  2194. //
  2195. let result = null;
  2196. if ( shaderNode.layout ) {
  2197. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2198. if ( functionNodesCacheMap === undefined ) {
  2199. functionNodesCacheMap = new WeakMap();
  2200. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2201. }
  2202. let functionNode = functionNodesCacheMap.get( shaderNode );
  2203. if ( functionNode === undefined ) {
  2204. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2205. functionNodesCacheMap.set( shaderNode, functionNode );
  2206. }
  2207. builder.addInclude( functionNode );
  2208. result = nodeObject( functionNode.call( inputNodes ) );
  2209. } else {
  2210. const jsFunc = shaderNode.jsFunc;
  2211. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2212. result = nodeObject( outputNode );
  2213. }
  2214. if ( shaderNode.once ) {
  2215. properties.onceOutput = result;
  2216. }
  2217. return result;
  2218. }
  2219. getOutputNode( builder ) {
  2220. const properties = builder.getNodeProperties( this );
  2221. if ( properties.outputNode === null ) {
  2222. properties.outputNode = this.setupOutput( builder );
  2223. }
  2224. return properties.outputNode;
  2225. }
  2226. setup( builder ) {
  2227. return this.getOutputNode( builder );
  2228. }
  2229. setupOutput( builder ) {
  2230. builder.addStack();
  2231. builder.stack.outputNode = this.call( builder );
  2232. return builder.removeStack();
  2233. }
  2234. generate( builder, output ) {
  2235. const outputNode = this.getOutputNode( builder );
  2236. return outputNode.build( builder, output );
  2237. }
  2238. }
  2239. class ShaderNodeInternal extends Node {
  2240. constructor( jsFunc, nodeType ) {
  2241. super( nodeType );
  2242. this.jsFunc = jsFunc;
  2243. this.layout = null;
  2244. this.global = true;
  2245. this.once = false;
  2246. }
  2247. setLayout( layout ) {
  2248. this.layout = layout;
  2249. return this;
  2250. }
  2251. call( inputs = null ) {
  2252. nodeObjects( inputs );
  2253. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2254. }
  2255. setup() {
  2256. return this.call();
  2257. }
  2258. }
  2259. const bools = [ false, true ];
  2260. const uints = [ 0, 1, 2, 3 ];
  2261. const ints = [ -1, -2 ];
  2262. 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 ];
  2263. const boolsCacheMap = new Map();
  2264. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2265. const uintsCacheMap = new Map();
  2266. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2267. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2268. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2269. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2270. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2271. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2272. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2273. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2274. const getConstNode = ( value, type ) => {
  2275. if ( constNodesCacheMap.has( value ) ) {
  2276. return constNodesCacheMap.get( value );
  2277. } else if ( value.isNode === true ) {
  2278. return value;
  2279. } else {
  2280. return new ConstNode( value, type );
  2281. }
  2282. };
  2283. const safeGetNodeType = ( node ) => {
  2284. try {
  2285. return node.getNodeType();
  2286. } catch ( _ ) {
  2287. return undefined;
  2288. }
  2289. };
  2290. const ConvertType = function ( type, cacheMap = null ) {
  2291. return ( ...params ) => {
  2292. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2293. params = [ getValueFromType( type, ...params ) ];
  2294. }
  2295. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2296. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2297. }
  2298. if ( params.length === 1 ) {
  2299. const node = getConstNode( params[ 0 ], type );
  2300. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2301. return nodeObject( new ConvertNode( node, type ) );
  2302. }
  2303. const nodes = params.map( param => getConstNode( param ) );
  2304. return nodeObject( new JoinNode( nodes, type ) );
  2305. };
  2306. };
  2307. // exports
  2308. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2309. // utils
  2310. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2311. // shader node base
  2312. function ShaderNode( jsFunc, nodeType ) {
  2313. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2314. }
  2315. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2316. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2317. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2318. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2319. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2320. let fnId = 0;
  2321. const Fn = ( jsFunc, layout = null ) => {
  2322. let nodeType = null;
  2323. if ( layout !== null ) {
  2324. if ( typeof layout === 'object' ) {
  2325. nodeType = layout.return;
  2326. } else {
  2327. if ( typeof layout === 'string' ) {
  2328. nodeType = layout;
  2329. } else {
  2330. console.error( 'THREE.TSL: Invalid layout type.' );
  2331. }
  2332. layout = null;
  2333. }
  2334. }
  2335. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2336. const fn = ( ...params ) => {
  2337. let inputs;
  2338. nodeObjects( params );
  2339. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2340. inputs = [ ...params ];
  2341. } else {
  2342. inputs = params[ 0 ];
  2343. }
  2344. const fnCall = shaderNode.call( inputs );
  2345. if ( nodeType === 'void' ) fnCall.toStack();
  2346. return fnCall;
  2347. };
  2348. fn.shaderNode = shaderNode;
  2349. fn.id = shaderNode.id;
  2350. fn.getNodeType = ( ...params ) => shaderNode.getNodeType( ...params );
  2351. fn.getCacheKey = ( ...params ) => shaderNode.getCacheKey( ...params );
  2352. fn.setLayout = ( layout ) => {
  2353. shaderNode.setLayout( layout );
  2354. return fn;
  2355. };
  2356. fn.once = () => {
  2357. shaderNode.once = true;
  2358. return fn;
  2359. };
  2360. if ( layout !== null ) {
  2361. if ( typeof layout.inputs !== 'object' ) {
  2362. const fullLayout = {
  2363. name: 'fn' + fnId ++,
  2364. type: nodeType,
  2365. inputs: []
  2366. };
  2367. for ( const name in layout ) {
  2368. if ( name === 'return' ) continue;
  2369. fullLayout.inputs.push( {
  2370. name: name,
  2371. type: layout[ name ]
  2372. } );
  2373. }
  2374. layout = fullLayout;
  2375. }
  2376. fn.setLayout( layout );
  2377. }
  2378. return fn;
  2379. };
  2380. //
  2381. addMethodChaining( 'toGlobal', ( node ) => {
  2382. node.global = true;
  2383. return node;
  2384. } );
  2385. //
  2386. const setCurrentStack = ( stack ) => {
  2387. currentStack = stack;
  2388. };
  2389. const getCurrentStack = () => currentStack;
  2390. /**
  2391. * Represent a conditional node using if/else statements.
  2392. *
  2393. * ```js
  2394. * If( condition, function )
  2395. * .ElseIf( condition, function )
  2396. * .Else( function )
  2397. * ```
  2398. * @tsl
  2399. * @function
  2400. * @param {...any} params - The parameters for the conditional node.
  2401. * @returns {StackNode} The conditional node.
  2402. */
  2403. const If = ( ...params ) => currentStack.If( ...params );
  2404. /**
  2405. * Represent a conditional node using switch/case statements.
  2406. *
  2407. * ```js
  2408. * Switch( value )
  2409. * .Case( 1, function )
  2410. * .Case( 2, 3, 4, function )
  2411. * .Default( function )
  2412. * ```
  2413. * @tsl
  2414. * @function
  2415. * @param {...any} params - The parameters for the conditional node.
  2416. * @returns {StackNode} The conditional node.
  2417. */
  2418. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2419. /**
  2420. * Add the given node to the current stack.
  2421. *
  2422. * @param {Node} node - The node to add.
  2423. * @returns {Node} The node that was added to the stack.
  2424. */
  2425. function Stack( node ) {
  2426. if ( currentStack ) currentStack.add( node );
  2427. return node;
  2428. }
  2429. addMethodChaining( 'toStack', Stack );
  2430. // types
  2431. const color = new ConvertType( 'color' );
  2432. const float = new ConvertType( 'float', cacheMaps.float );
  2433. const int = new ConvertType( 'int', cacheMaps.ints );
  2434. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2435. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2436. const vec2 = new ConvertType( 'vec2' );
  2437. const ivec2 = new ConvertType( 'ivec2' );
  2438. const uvec2 = new ConvertType( 'uvec2' );
  2439. const bvec2 = new ConvertType( 'bvec2' );
  2440. const vec3 = new ConvertType( 'vec3' );
  2441. const ivec3 = new ConvertType( 'ivec3' );
  2442. const uvec3 = new ConvertType( 'uvec3' );
  2443. const bvec3 = new ConvertType( 'bvec3' );
  2444. const vec4 = new ConvertType( 'vec4' );
  2445. const ivec4 = new ConvertType( 'ivec4' );
  2446. const uvec4 = new ConvertType( 'uvec4' );
  2447. const bvec4 = new ConvertType( 'bvec4' );
  2448. const mat2 = new ConvertType( 'mat2' );
  2449. const mat3 = new ConvertType( 'mat3' );
  2450. const mat4 = new ConvertType( 'mat4' );
  2451. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2452. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2453. addMethodChaining( 'toColor', color );
  2454. addMethodChaining( 'toFloat', float );
  2455. addMethodChaining( 'toInt', int );
  2456. addMethodChaining( 'toUint', uint );
  2457. addMethodChaining( 'toBool', bool );
  2458. addMethodChaining( 'toVec2', vec2 );
  2459. addMethodChaining( 'toIVec2', ivec2 );
  2460. addMethodChaining( 'toUVec2', uvec2 );
  2461. addMethodChaining( 'toBVec2', bvec2 );
  2462. addMethodChaining( 'toVec3', vec3 );
  2463. addMethodChaining( 'toIVec3', ivec3 );
  2464. addMethodChaining( 'toUVec3', uvec3 );
  2465. addMethodChaining( 'toBVec3', bvec3 );
  2466. addMethodChaining( 'toVec4', vec4 );
  2467. addMethodChaining( 'toIVec4', ivec4 );
  2468. addMethodChaining( 'toUVec4', uvec4 );
  2469. addMethodChaining( 'toBVec4', bvec4 );
  2470. addMethodChaining( 'toMat2', mat2 );
  2471. addMethodChaining( 'toMat3', mat3 );
  2472. addMethodChaining( 'toMat4', mat4 );
  2473. // basic nodes
  2474. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2475. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2476. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2477. addMethodChaining( 'element', element );
  2478. addMethodChaining( 'convert', convert );
  2479. // deprecated
  2480. /**
  2481. * @tsl
  2482. * @function
  2483. * @deprecated since r176. Use {@link Stack} instead.
  2484. *
  2485. * @param {Node} node - The node to add.
  2486. * @returns {Function}
  2487. */
  2488. const append = ( node ) => { // @deprecated, r176
  2489. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2490. return Stack( node );
  2491. };
  2492. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2493. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2494. return Stack( node );
  2495. } );
  2496. /**
  2497. * @tsl
  2498. * @function
  2499. * @deprecated since r168. Use {@link Fn} instead.
  2500. *
  2501. * @param {...any} params
  2502. * @returns {Function}
  2503. */
  2504. const tslFn = ( ...params ) => { // @deprecated, r168
  2505. console.warn( 'THREE.TSL: tslFn() has been renamed to Fn().' );
  2506. return Fn( ...params );
  2507. };
  2508. /**
  2509. * This class represents a shader property. It can be used
  2510. * to explicitly define a property and assign a value to it.
  2511. *
  2512. * ```js
  2513. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2514. *```
  2515. * `PropertyNode` is used by the engine to predefined common material properties
  2516. * for TSL code.
  2517. *
  2518. * @augments Node
  2519. */
  2520. class PropertyNode extends Node {
  2521. static get type() {
  2522. return 'PropertyNode';
  2523. }
  2524. /**
  2525. * Constructs a new property node.
  2526. *
  2527. * @param {string} nodeType - The type of the node.
  2528. * @param {?string} [name=null] - The name of the property in the shader.
  2529. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2530. */
  2531. constructor( nodeType, name = null, varying = false ) {
  2532. super( nodeType );
  2533. /**
  2534. * The name of the property in the shader. If no name is defined,
  2535. * the node system auto-generates one.
  2536. *
  2537. * @type {?string}
  2538. * @default null
  2539. */
  2540. this.name = name;
  2541. /**
  2542. * Whether this property is a varying or not.
  2543. *
  2544. * @type {boolean}
  2545. * @default false
  2546. */
  2547. this.varying = varying;
  2548. /**
  2549. * This flag can be used for type testing.
  2550. *
  2551. * @type {boolean}
  2552. * @readonly
  2553. * @default true
  2554. */
  2555. this.isPropertyNode = true;
  2556. }
  2557. getHash( builder ) {
  2558. return this.name || super.getHash( builder );
  2559. }
  2560. /**
  2561. * The method is overwritten so it always returns `true`.
  2562. *
  2563. * @param {NodeBuilder} builder - The current node builder.
  2564. * @return {boolean} Whether this node is global or not.
  2565. */
  2566. isGlobal( /*builder*/ ) {
  2567. return true;
  2568. }
  2569. generate( builder ) {
  2570. let nodeVar;
  2571. if ( this.varying === true ) {
  2572. nodeVar = builder.getVaryingFromNode( this, this.name );
  2573. nodeVar.needsInterpolation = true;
  2574. } else {
  2575. nodeVar = builder.getVarFromNode( this, this.name );
  2576. }
  2577. return builder.getPropertyName( nodeVar );
  2578. }
  2579. }
  2580. /**
  2581. * TSL function for creating a property node.
  2582. *
  2583. * @tsl
  2584. * @function
  2585. * @param {string} type - The type of the node.
  2586. * @param {?string} [name=null] - The name of the property in the shader.
  2587. * @returns {PropertyNode}
  2588. */
  2589. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2590. /**
  2591. * TSL function for creating a varying property node.
  2592. *
  2593. * @tsl
  2594. * @function
  2595. * @param {string} type - The type of the node.
  2596. * @param {?string} [name=null] - The name of the varying in the shader.
  2597. * @returns {PropertyNode}
  2598. */
  2599. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2600. /**
  2601. * TSL object that represents the shader variable `DiffuseColor`.
  2602. *
  2603. * @tsl
  2604. * @type {PropertyNode<vec4>}
  2605. */
  2606. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2607. /**
  2608. * TSL object that represents the shader variable `EmissiveColor`.
  2609. *
  2610. * @tsl
  2611. * @type {PropertyNode<vec3>}
  2612. */
  2613. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2614. /**
  2615. * TSL object that represents the shader variable `Roughness`.
  2616. *
  2617. * @tsl
  2618. * @type {PropertyNode<float>}
  2619. */
  2620. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2621. /**
  2622. * TSL object that represents the shader variable `Metalness`.
  2623. *
  2624. * @tsl
  2625. * @type {PropertyNode<float>}
  2626. */
  2627. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2628. /**
  2629. * TSL object that represents the shader variable `Clearcoat`.
  2630. *
  2631. * @tsl
  2632. * @type {PropertyNode<float>}
  2633. */
  2634. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2635. /**
  2636. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2637. *
  2638. * @tsl
  2639. * @type {PropertyNode<float>}
  2640. */
  2641. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2642. /**
  2643. * TSL object that represents the shader variable `Sheen`.
  2644. *
  2645. * @tsl
  2646. * @type {PropertyNode<vec3>}
  2647. */
  2648. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2649. /**
  2650. * TSL object that represents the shader variable `SheenRoughness`.
  2651. *
  2652. * @tsl
  2653. * @type {PropertyNode<float>}
  2654. */
  2655. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2656. /**
  2657. * TSL object that represents the shader variable `Iridescence`.
  2658. *
  2659. * @tsl
  2660. * @type {PropertyNode<float>}
  2661. */
  2662. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2663. /**
  2664. * TSL object that represents the shader variable `IridescenceIOR`.
  2665. *
  2666. * @tsl
  2667. * @type {PropertyNode<float>}
  2668. */
  2669. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2670. /**
  2671. * TSL object that represents the shader variable `IridescenceThickness`.
  2672. *
  2673. * @tsl
  2674. * @type {PropertyNode<float>}
  2675. */
  2676. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2677. /**
  2678. * TSL object that represents the shader variable `AlphaT`.
  2679. *
  2680. * @tsl
  2681. * @type {PropertyNode<float>}
  2682. */
  2683. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2684. /**
  2685. * TSL object that represents the shader variable `Anisotropy`.
  2686. *
  2687. * @tsl
  2688. * @type {PropertyNode<float>}
  2689. */
  2690. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2691. /**
  2692. * TSL object that represents the shader variable `AnisotropyT`.
  2693. *
  2694. * @tsl
  2695. * @type {PropertyNode<vec3>}
  2696. */
  2697. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2698. /**
  2699. * TSL object that represents the shader variable `AnisotropyB`.
  2700. *
  2701. * @tsl
  2702. * @type {PropertyNode<vec3>}
  2703. */
  2704. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2705. /**
  2706. * TSL object that represents the shader variable `SpecularColor`.
  2707. *
  2708. * @tsl
  2709. * @type {PropertyNode<color>}
  2710. */
  2711. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2712. /**
  2713. * TSL object that represents the shader variable `SpecularF90`.
  2714. *
  2715. * @tsl
  2716. * @type {PropertyNode<float>}
  2717. */
  2718. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2719. /**
  2720. * TSL object that represents the shader variable `Shininess`.
  2721. *
  2722. * @tsl
  2723. * @type {PropertyNode<float>}
  2724. */
  2725. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2726. /**
  2727. * TSL object that represents the shader variable `Output`.
  2728. *
  2729. * @tsl
  2730. * @type {PropertyNode<vec4>}
  2731. */
  2732. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2733. /**
  2734. * TSL object that represents the shader variable `dashSize`.
  2735. *
  2736. * @tsl
  2737. * @type {PropertyNode<float>}
  2738. */
  2739. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2740. /**
  2741. * TSL object that represents the shader variable `gapSize`.
  2742. *
  2743. * @tsl
  2744. * @type {PropertyNode<float>}
  2745. */
  2746. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2747. /**
  2748. * TSL object that represents the shader variable `pointWidth`.
  2749. *
  2750. * @tsl
  2751. * @type {PropertyNode<float>}
  2752. */
  2753. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2754. /**
  2755. * TSL object that represents the shader variable `IOR`.
  2756. *
  2757. * @tsl
  2758. * @type {PropertyNode<float>}
  2759. */
  2760. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2761. /**
  2762. * TSL object that represents the shader variable `Transmission`.
  2763. *
  2764. * @tsl
  2765. * @type {PropertyNode<float>}
  2766. */
  2767. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2768. /**
  2769. * TSL object that represents the shader variable `Thickness`.
  2770. *
  2771. * @tsl
  2772. * @type {PropertyNode<float>}
  2773. */
  2774. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2775. /**
  2776. * TSL object that represents the shader variable `AttenuationDistance`.
  2777. *
  2778. * @tsl
  2779. * @type {PropertyNode<float>}
  2780. */
  2781. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2782. /**
  2783. * TSL object that represents the shader variable `AttenuationColor`.
  2784. *
  2785. * @tsl
  2786. * @type {PropertyNode<color>}
  2787. */
  2788. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2789. /**
  2790. * TSL object that represents the shader variable `Dispersion`.
  2791. *
  2792. * @tsl
  2793. * @type {PropertyNode<float>}
  2794. */
  2795. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2796. /**
  2797. * This node can be used to group single instances of {@link UniformNode}
  2798. * and manage them as a uniform buffer.
  2799. *
  2800. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2801. * will be used when defining the {@link UniformNode#groupNode} property.
  2802. *
  2803. * - `objectGroup`: Uniform buffer per object.
  2804. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2805. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2806. *
  2807. * @augments Node
  2808. */
  2809. class UniformGroupNode extends Node {
  2810. static get type() {
  2811. return 'UniformGroupNode';
  2812. }
  2813. /**
  2814. * Constructs a new uniform group node.
  2815. *
  2816. * @param {string} name - The name of the uniform group node.
  2817. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2818. * @param {number} [order=1] - Influences the internal sorting.
  2819. */
  2820. constructor( name, shared = false, order = 1 ) {
  2821. super( 'string' );
  2822. /**
  2823. * The name of the uniform group node.
  2824. *
  2825. * @type {string}
  2826. */
  2827. this.name = name;
  2828. /**
  2829. * Whether this uniform group node is shared or not.
  2830. *
  2831. * @type {boolean}
  2832. * @default false
  2833. */
  2834. this.shared = shared;
  2835. /**
  2836. * Influences the internal sorting.
  2837. * TODO: Add details when this property should be changed.
  2838. *
  2839. * @type {number}
  2840. * @default 1
  2841. */
  2842. this.order = order;
  2843. /**
  2844. * This flag can be used for type testing.
  2845. *
  2846. * @type {boolean}
  2847. * @readonly
  2848. * @default true
  2849. */
  2850. this.isUniformGroup = true;
  2851. }
  2852. serialize( data ) {
  2853. super.serialize( data );
  2854. data.name = this.name;
  2855. data.version = this.version;
  2856. data.shared = this.shared;
  2857. }
  2858. deserialize( data ) {
  2859. super.deserialize( data );
  2860. this.name = data.name;
  2861. this.version = data.version;
  2862. this.shared = data.shared;
  2863. }
  2864. }
  2865. /**
  2866. * TSL function for creating a uniform group node with the given name.
  2867. *
  2868. * @tsl
  2869. * @function
  2870. * @param {string} name - The name of the uniform group node.
  2871. * @returns {UniformGroupNode}
  2872. */
  2873. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2874. /**
  2875. * TSL function for creating a shared uniform group node with the given name and order.
  2876. *
  2877. * @tsl
  2878. * @function
  2879. * @param {string} name - The name of the uniform group node.
  2880. * @param {number} [order=0] - Influences the internal sorting.
  2881. * @returns {UniformGroupNode}
  2882. */
  2883. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2884. /**
  2885. * TSL object that represents a shared uniform group node which is updated once per frame.
  2886. *
  2887. * @tsl
  2888. * @type {UniformGroupNode}
  2889. */
  2890. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2891. /**
  2892. * TSL object that represents a shared uniform group node which is updated once per render.
  2893. *
  2894. * @tsl
  2895. * @type {UniformGroupNode}
  2896. */
  2897. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2898. /**
  2899. * TSL object that represents a uniform group node which is updated once per object.
  2900. *
  2901. * @tsl
  2902. * @type {UniformGroupNode}
  2903. */
  2904. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2905. /**
  2906. * Class for representing a uniform.
  2907. *
  2908. * @augments InputNode
  2909. */
  2910. class UniformNode extends InputNode {
  2911. static get type() {
  2912. return 'UniformNode';
  2913. }
  2914. /**
  2915. * Constructs a new uniform node.
  2916. *
  2917. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2918. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2919. */
  2920. constructor( value, nodeType = null ) {
  2921. super( value, nodeType );
  2922. /**
  2923. * This flag can be used for type testing.
  2924. *
  2925. * @type {boolean}
  2926. * @readonly
  2927. * @default true
  2928. */
  2929. this.isUniformNode = true;
  2930. /**
  2931. * The name or label of the uniform.
  2932. *
  2933. * @type {string}
  2934. * @default ''
  2935. */
  2936. this.name = '';
  2937. /**
  2938. * The uniform group of this uniform. By default, uniforms are
  2939. * managed per object but they might belong to a shared group
  2940. * which is updated per frame or render call.
  2941. *
  2942. * @type {UniformGroupNode}
  2943. */
  2944. this.groupNode = objectGroup;
  2945. }
  2946. /**
  2947. * Sets the {@link UniformNode#name} property.
  2948. *
  2949. * @param {string} name - The name of the uniform.
  2950. * @return {UniformNode} A reference to this node.
  2951. */
  2952. label( name ) {
  2953. this.name = name;
  2954. return this;
  2955. }
  2956. /**
  2957. * Sets the {@link UniformNode#groupNode} property.
  2958. *
  2959. * @param {UniformGroupNode} group - The uniform group.
  2960. * @return {UniformNode} A reference to this node.
  2961. */
  2962. setGroup( group ) {
  2963. this.groupNode = group;
  2964. return this;
  2965. }
  2966. /**
  2967. * Returns the {@link UniformNode#groupNode}.
  2968. *
  2969. * @return {UniformGroupNode} The uniform group.
  2970. */
  2971. getGroup() {
  2972. return this.groupNode;
  2973. }
  2974. /**
  2975. * By default, this method returns the result of {@link Node#getHash} but derived
  2976. * classes might overwrite this method with a different implementation.
  2977. *
  2978. * @param {NodeBuilder} builder - The current node builder.
  2979. * @return {string} The uniform hash.
  2980. */
  2981. getUniformHash( builder ) {
  2982. return this.getHash( builder );
  2983. }
  2984. onUpdate( callback, updateType ) {
  2985. const self = this.getSelf();
  2986. callback = callback.bind( self );
  2987. return super.onUpdate( ( frame ) => {
  2988. const value = callback( frame, self );
  2989. if ( value !== undefined ) {
  2990. this.value = value;
  2991. }
  2992. }, updateType );
  2993. }
  2994. generate( builder, output ) {
  2995. const type = this.getNodeType( builder );
  2996. const hash = this.getUniformHash( builder );
  2997. let sharedNode = builder.getNodeFromHash( hash );
  2998. if ( sharedNode === undefined ) {
  2999. builder.setHashNode( this, hash );
  3000. sharedNode = this;
  3001. }
  3002. const sharedNodeType = sharedNode.getInputType( builder );
  3003. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  3004. const propertyName = builder.getPropertyName( nodeUniform );
  3005. if ( builder.context.label !== undefined ) delete builder.context.label;
  3006. return builder.format( propertyName, type, output );
  3007. }
  3008. }
  3009. /**
  3010. * TSL function for creating a uniform node.
  3011. *
  3012. * @tsl
  3013. * @function
  3014. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3015. * @param {string} [arg2] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3016. * @returns {UniformNode}
  3017. */
  3018. const uniform = ( arg1, arg2 ) => {
  3019. const nodeType = getConstNodeType( arg2 || arg1 );
  3020. // @TODO: get ConstNode from .traverse() in the future
  3021. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  3022. return nodeObject( new UniformNode( value, nodeType ) );
  3023. };
  3024. /**
  3025. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3026. * ```js
  3027. * const colors = array( [
  3028. * vec3( 1, 0, 0 ),
  3029. * vec3( 0, 1, 0 ),
  3030. * vec3( 0, 0, 1 )
  3031. * ] );
  3032. *
  3033. * const redColor = tintColors.element( 0 );
  3034. *
  3035. * @augments TempNode
  3036. */
  3037. class ArrayNode extends TempNode {
  3038. static get type() {
  3039. return 'ArrayNode';
  3040. }
  3041. /**
  3042. * Constructs a new array node.
  3043. *
  3044. * @param {?string} nodeType - The data type of the elements.
  3045. * @param {number} count - Size of the array.
  3046. * @param {?Array<Node>} [values=null] - Array default values.
  3047. */
  3048. constructor( nodeType, count, values = null ) {
  3049. super( nodeType );
  3050. /**
  3051. * Array size.
  3052. *
  3053. * @type {number}
  3054. */
  3055. this.count = count;
  3056. /**
  3057. * Array default values.
  3058. *
  3059. * @type {?Array<Node>}
  3060. */
  3061. this.values = values;
  3062. /**
  3063. * This flag can be used for type testing.
  3064. *
  3065. * @type {boolean}
  3066. * @readonly
  3067. * @default true
  3068. */
  3069. this.isArrayNode = true;
  3070. }
  3071. /**
  3072. * Returns the node's type.
  3073. *
  3074. * @param {NodeBuilder} builder - The current node builder.
  3075. * @return {string} The type of the node.
  3076. */
  3077. getNodeType( builder ) {
  3078. if ( this.nodeType === null ) {
  3079. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3080. }
  3081. return this.nodeType;
  3082. }
  3083. /**
  3084. * Returns the node's type.
  3085. *
  3086. * @param {NodeBuilder} builder - The current node builder.
  3087. * @return {string} The type of the node.
  3088. */
  3089. getElementType( builder ) {
  3090. return this.getNodeType( builder );
  3091. }
  3092. /**
  3093. * This method builds the output node and returns the resulting array as a shader string.
  3094. *
  3095. * @param {NodeBuilder} builder - The current node builder.
  3096. * @return {string} The generated shader string.
  3097. */
  3098. generate( builder ) {
  3099. const type = this.getNodeType( builder );
  3100. return builder.generateArray( type, this.count, this.values );
  3101. }
  3102. }
  3103. /**
  3104. * TSL function for creating an array node.
  3105. *
  3106. * @tsl
  3107. * @function
  3108. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3109. * or an array containing the default values (e.g., [ vec3() ]).
  3110. * @param {?number} [count] - Size of the array.
  3111. * @returns {ArrayNode}
  3112. */
  3113. const array = ( ...params ) => {
  3114. let node;
  3115. if ( params.length === 1 ) {
  3116. const values = params[ 0 ];
  3117. node = new ArrayNode( null, values.length, values );
  3118. } else {
  3119. const nodeType = params[ 0 ];
  3120. const count = params[ 1 ];
  3121. node = new ArrayNode( nodeType, count );
  3122. }
  3123. return nodeObject( node );
  3124. };
  3125. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3126. /**
  3127. * These node represents an assign operation. Meaning a node is assigned
  3128. * to another node.
  3129. *
  3130. * @augments TempNode
  3131. */
  3132. class AssignNode extends TempNode {
  3133. static get type() {
  3134. return 'AssignNode';
  3135. }
  3136. /**
  3137. * Constructs a new assign node.
  3138. *
  3139. * @param {Node} targetNode - The target node.
  3140. * @param {Node} sourceNode - The source type.
  3141. */
  3142. constructor( targetNode, sourceNode ) {
  3143. super();
  3144. /**
  3145. * The target node.
  3146. *
  3147. * @type {Node}
  3148. */
  3149. this.targetNode = targetNode;
  3150. /**
  3151. * The source node.
  3152. *
  3153. * @type {Node}
  3154. */
  3155. this.sourceNode = sourceNode;
  3156. }
  3157. /**
  3158. * Whether this node is used more than once in context of other nodes. This method
  3159. * is overwritten since it always returns `false` (assigns are unique).
  3160. *
  3161. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3162. */
  3163. hasDependencies() {
  3164. return false;
  3165. }
  3166. getNodeType( builder, output ) {
  3167. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3168. }
  3169. /**
  3170. * Whether a split is required when assigning source to target. This can happen when the component length of
  3171. * target and source data type does not match.
  3172. *
  3173. * @param {NodeBuilder} builder - The current node builder.
  3174. * @return {boolean} Whether a split is required when assigning source to target.
  3175. */
  3176. needsSplitAssign( builder ) {
  3177. const { targetNode } = this;
  3178. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3179. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3180. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3181. return assignDifferentVector;
  3182. }
  3183. return false;
  3184. }
  3185. generate( builder, output ) {
  3186. const { targetNode, sourceNode } = this;
  3187. const needsSplitAssign = this.needsSplitAssign( builder );
  3188. const targetType = targetNode.getNodeType( builder );
  3189. const target = targetNode.context( { assign: true } ).build( builder );
  3190. const source = sourceNode.build( builder, targetType );
  3191. const sourceType = sourceNode.getNodeType( builder );
  3192. const nodeData = builder.getDataFromNode( this );
  3193. //
  3194. let snippet;
  3195. if ( nodeData.initialized === true ) {
  3196. if ( output !== 'void' ) {
  3197. snippet = target;
  3198. }
  3199. } else if ( needsSplitAssign ) {
  3200. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3201. const sourceProperty = builder.getPropertyName( sourceVar );
  3202. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3203. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  3204. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  3205. const component = targetNode.components[ i ];
  3206. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3207. }
  3208. if ( output !== 'void' ) {
  3209. snippet = target;
  3210. }
  3211. } else {
  3212. snippet = `${ target } = ${ source }`;
  3213. if ( output === 'void' || sourceType === 'void' ) {
  3214. builder.addLineFlowCode( snippet, this );
  3215. if ( output !== 'void' ) {
  3216. snippet = target;
  3217. }
  3218. }
  3219. }
  3220. nodeData.initialized = true;
  3221. return builder.format( snippet, targetType, output );
  3222. }
  3223. }
  3224. /**
  3225. * TSL function for creating an assign node.
  3226. *
  3227. * @tsl
  3228. * @function
  3229. * @param {Node} targetNode - The target node.
  3230. * @param {Node} sourceNode - The source type.
  3231. * @returns {AssignNode}
  3232. */
  3233. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3234. addMethodChaining( 'assign', assign );
  3235. /**
  3236. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3237. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3238. * this logic.
  3239. *
  3240. * @augments TempNode
  3241. */
  3242. class FunctionCallNode extends TempNode {
  3243. static get type() {
  3244. return 'FunctionCallNode';
  3245. }
  3246. /**
  3247. * Constructs a new function call node.
  3248. *
  3249. * @param {?FunctionNode} functionNode - The function node.
  3250. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3251. */
  3252. constructor( functionNode = null, parameters = {} ) {
  3253. super();
  3254. /**
  3255. * The function node.
  3256. *
  3257. * @type {?FunctionNode}
  3258. * @default null
  3259. */
  3260. this.functionNode = functionNode;
  3261. /**
  3262. * The parameters of the function call.
  3263. *
  3264. * @type {Object<string, Node>}
  3265. * @default {}
  3266. */
  3267. this.parameters = parameters;
  3268. }
  3269. /**
  3270. * Sets the parameters of the function call node.
  3271. *
  3272. * @param {Object<string, Node>} parameters - The parameters to set.
  3273. * @return {FunctionCallNode} A reference to this node.
  3274. */
  3275. setParameters( parameters ) {
  3276. this.parameters = parameters;
  3277. return this;
  3278. }
  3279. /**
  3280. * Returns the parameters of the function call node.
  3281. *
  3282. * @return {Object<string, Node>} The parameters of this node.
  3283. */
  3284. getParameters() {
  3285. return this.parameters;
  3286. }
  3287. getNodeType( builder ) {
  3288. return this.functionNode.getNodeType( builder );
  3289. }
  3290. generate( builder ) {
  3291. const params = [];
  3292. const functionNode = this.functionNode;
  3293. const inputs = functionNode.getInputs( builder );
  3294. const parameters = this.parameters;
  3295. const generateInput = ( node, inputNode ) => {
  3296. const type = inputNode.type;
  3297. const pointer = type === 'pointer';
  3298. let output;
  3299. if ( pointer ) output = '&' + node.build( builder );
  3300. else output = node.build( builder, type );
  3301. return output;
  3302. };
  3303. if ( Array.isArray( parameters ) ) {
  3304. if ( parameters.length > inputs.length ) {
  3305. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3306. parameters.length = inputs.length;
  3307. } else if ( parameters.length < inputs.length ) {
  3308. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3309. while ( parameters.length < inputs.length ) {
  3310. parameters.push( float( 0 ) );
  3311. }
  3312. }
  3313. for ( let i = 0; i < parameters.length; i ++ ) {
  3314. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3315. }
  3316. } else {
  3317. for ( const inputNode of inputs ) {
  3318. const node = parameters[ inputNode.name ];
  3319. if ( node !== undefined ) {
  3320. params.push( generateInput( node, inputNode ) );
  3321. } else {
  3322. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3323. params.push( generateInput( float( 0 ), inputNode ) );
  3324. }
  3325. }
  3326. }
  3327. const functionName = functionNode.build( builder, 'property' );
  3328. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3329. }
  3330. }
  3331. const call = ( func, ...params ) => {
  3332. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3333. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3334. };
  3335. addMethodChaining( 'call', call );
  3336. const _vectorOperators = {
  3337. '==': 'equal',
  3338. '!=': 'notEqual',
  3339. '<': 'lessThan',
  3340. '>': 'greaterThan',
  3341. '<=': 'lessThanEqual',
  3342. '>=': 'greaterThanEqual',
  3343. '%': 'mod'
  3344. };
  3345. /**
  3346. * This node represents basic mathematical and logical operations like addition,
  3347. * subtraction or comparisons (e.g. `equal()`).
  3348. *
  3349. * @augments TempNode
  3350. */
  3351. class OperatorNode extends TempNode {
  3352. static get type() {
  3353. return 'OperatorNode';
  3354. }
  3355. /**
  3356. * Constructs a new operator node.
  3357. *
  3358. * @param {string} op - The operator.
  3359. * @param {Node} aNode - The first input.
  3360. * @param {Node} bNode - The second input.
  3361. * @param {...Node} params - Additional input parameters.
  3362. */
  3363. constructor( op, aNode, bNode, ...params ) {
  3364. super();
  3365. if ( params.length > 0 ) {
  3366. let finalOp = new OperatorNode( op, aNode, bNode );
  3367. for ( let i = 0; i < params.length - 1; i ++ ) {
  3368. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3369. }
  3370. aNode = finalOp;
  3371. bNode = params[ params.length - 1 ];
  3372. }
  3373. /**
  3374. * The operator.
  3375. *
  3376. * @type {string}
  3377. */
  3378. this.op = op;
  3379. /**
  3380. * The first input.
  3381. *
  3382. * @type {Node}
  3383. */
  3384. this.aNode = aNode;
  3385. /**
  3386. * The second input.
  3387. *
  3388. * @type {Node}
  3389. */
  3390. this.bNode = bNode;
  3391. /**
  3392. * This flag can be used for type testing.
  3393. *
  3394. * @type {boolean}
  3395. * @readonly
  3396. * @default true
  3397. */
  3398. this.isOperatorNode = true;
  3399. }
  3400. /**
  3401. * Returns the operator method name.
  3402. *
  3403. * @param {NodeBuilder} builder - The current node builder.
  3404. * @param {string} output - The output type.
  3405. * @returns {string} The operator method name.
  3406. */
  3407. getOperatorMethod( builder, output ) {
  3408. return builder.getMethod( _vectorOperators[ this.op ], output );
  3409. }
  3410. /**
  3411. * This method is overwritten since the node type is inferred from the operator
  3412. * and the input node types.
  3413. *
  3414. * @param {NodeBuilder} builder - The current node builder.
  3415. * @return {string} The node type.
  3416. */
  3417. getNodeType( builder ) {
  3418. const op = this.op;
  3419. const aNode = this.aNode;
  3420. const bNode = this.bNode;
  3421. const typeA = aNode.getNodeType( builder );
  3422. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3423. if ( typeA === 'void' || typeB === 'void' ) {
  3424. return 'void';
  3425. } else if ( op === '%' ) {
  3426. return typeA;
  3427. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3428. return builder.getIntegerType( typeA );
  3429. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3430. return 'bool';
  3431. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3432. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3433. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3434. } else {
  3435. // Handle matrix operations
  3436. if ( builder.isMatrix( typeA ) ) {
  3437. if ( typeB === 'float' ) {
  3438. return typeA; // matrix * scalar = matrix
  3439. } else if ( builder.isVector( typeB ) ) {
  3440. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3441. } else if ( builder.isMatrix( typeB ) ) {
  3442. return typeA; // matrix * matrix
  3443. }
  3444. } else if ( builder.isMatrix( typeB ) ) {
  3445. if ( typeA === 'float' ) {
  3446. return typeB; // scalar * matrix = matrix
  3447. } else if ( builder.isVector( typeA ) ) {
  3448. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3449. }
  3450. }
  3451. // Handle non-matrix cases
  3452. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3453. // anytype x anytype: use the greater length vector
  3454. return typeB;
  3455. }
  3456. return typeA;
  3457. }
  3458. }
  3459. generate( builder, output ) {
  3460. const op = this.op;
  3461. const aNode = this.aNode;
  3462. const bNode = this.bNode;
  3463. const type = this.getNodeType( builder );
  3464. let typeA = null;
  3465. let typeB = null;
  3466. if ( type !== 'void' ) {
  3467. typeA = aNode.getNodeType( builder );
  3468. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3469. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3470. if ( builder.isVector( typeA ) ) {
  3471. typeB = typeA;
  3472. } else if ( builder.isVector( typeB ) ) {
  3473. typeA = typeB;
  3474. } else if ( typeA !== typeB ) {
  3475. typeA = typeB = 'float';
  3476. }
  3477. } else if ( op === '>>' || op === '<<' ) {
  3478. typeA = type;
  3479. typeB = builder.changeComponentType( typeB, 'uint' );
  3480. } else if ( op === '%' ) {
  3481. typeA = type;
  3482. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3483. } else if ( builder.isMatrix( typeA ) ) {
  3484. if ( typeB === 'float' ) {
  3485. // Keep matrix type for typeA, but ensure typeB stays float
  3486. typeB = 'float';
  3487. } else if ( builder.isVector( typeB ) ) {
  3488. // matrix x vector
  3489. typeB = builder.getVectorFromMatrix( typeA );
  3490. } else if ( builder.isMatrix( typeB ) ) ; else {
  3491. typeA = typeB = type;
  3492. }
  3493. } else if ( builder.isMatrix( typeB ) ) {
  3494. if ( typeA === 'float' ) {
  3495. // Keep matrix type for typeB, but ensure typeA stays float
  3496. typeA = 'float';
  3497. } else if ( builder.isVector( typeA ) ) {
  3498. // vector x matrix
  3499. typeA = builder.getVectorFromMatrix( typeB );
  3500. } else {
  3501. typeA = typeB = type;
  3502. }
  3503. } else {
  3504. // anytype x anytype
  3505. typeA = typeB = type;
  3506. }
  3507. } else {
  3508. typeA = typeB = type;
  3509. }
  3510. const a = aNode.build( builder, typeA );
  3511. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3512. const fnOpSnippet = builder.getFunctionOperator( op );
  3513. if ( output !== 'void' ) {
  3514. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3515. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3516. if ( isGLSL ) {
  3517. if ( builder.isVector( typeA ) ) {
  3518. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3519. } else {
  3520. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3521. }
  3522. } else {
  3523. // WGSL
  3524. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3525. }
  3526. } else if ( op === '%' ) {
  3527. if ( builder.isInteger( typeB ) ) {
  3528. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3529. } else {
  3530. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3531. }
  3532. } else if ( op === '!' || op === '~' ) {
  3533. return builder.format( `(${op}${a})`, typeA, output );
  3534. } else if ( fnOpSnippet ) {
  3535. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3536. } else {
  3537. // Handle matrix operations
  3538. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3539. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3540. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3541. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3542. } else {
  3543. let snippet = `( ${ a } ${ op } ${ b } )`;
  3544. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3545. snippet = `all${ snippet }`;
  3546. }
  3547. return builder.format( snippet, type, output );
  3548. }
  3549. }
  3550. } else if ( typeA !== 'void' ) {
  3551. if ( fnOpSnippet ) {
  3552. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3553. } else {
  3554. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3555. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3556. } else {
  3557. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3558. }
  3559. }
  3560. }
  3561. }
  3562. serialize( data ) {
  3563. super.serialize( data );
  3564. data.op = this.op;
  3565. }
  3566. deserialize( data ) {
  3567. super.deserialize( data );
  3568. this.op = data.op;
  3569. }
  3570. }
  3571. /**
  3572. * Returns the addition of two or more value.
  3573. *
  3574. * @tsl
  3575. * @function
  3576. * @param {Node} a - The first input.
  3577. * @param {Node} b - The second input.
  3578. * @param {...Node} params - Additional input parameters.
  3579. * @returns {OperatorNode}
  3580. */
  3581. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3582. /**
  3583. * Returns the subtraction of two or more value.
  3584. *
  3585. * @tsl
  3586. * @function
  3587. * @param {Node} a - The first input.
  3588. * @param {Node} b - The second input.
  3589. * @param {...Node} params - Additional input parameters.
  3590. * @returns {OperatorNode}
  3591. */
  3592. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3593. /**
  3594. * Returns the multiplication of two or more value.
  3595. *
  3596. * @tsl
  3597. * @function
  3598. * @param {Node} a - The first input.
  3599. * @param {Node} b - The second input.
  3600. * @param {...Node} params - Additional input parameters.
  3601. * @returns {OperatorNode}
  3602. */
  3603. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3604. /**
  3605. * Returns the division of two or more value.
  3606. *
  3607. * @tsl
  3608. * @function
  3609. * @param {Node} a - The first input.
  3610. * @param {Node} b - The second input.
  3611. * @param {...Node} params - Additional input parameters.
  3612. * @returns {OperatorNode}
  3613. */
  3614. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3615. /**
  3616. * Computes the remainder of dividing the first node by the second one.
  3617. *
  3618. * @tsl
  3619. * @function
  3620. * @param {Node} a - The first input.
  3621. * @param {Node} b - The second input.
  3622. * @returns {OperatorNode}
  3623. */
  3624. const mod = /*@__PURE__*/ nodeProxy( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3625. /**
  3626. * Checks if two nodes are equal.
  3627. *
  3628. * @tsl
  3629. * @function
  3630. * @param {Node} a - The first input.
  3631. * @param {Node} b - The second input.
  3632. * @returns {OperatorNode}
  3633. */
  3634. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3635. /**
  3636. * Checks if two nodes are not equal.
  3637. *
  3638. * @tsl
  3639. * @function
  3640. * @param {Node} a - The first input.
  3641. * @param {Node} b - The second input.
  3642. * @returns {OperatorNode}
  3643. */
  3644. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3645. /**
  3646. * Checks if the first node is less than the second.
  3647. *
  3648. * @tsl
  3649. * @function
  3650. * @param {Node} a - The first input.
  3651. * @param {Node} b - The second input.
  3652. * @returns {OperatorNode}
  3653. */
  3654. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3655. /**
  3656. * Checks if the first node is greater than the second.
  3657. *
  3658. * @tsl
  3659. * @function
  3660. * @param {Node} a - The first input.
  3661. * @param {Node} b - The second input.
  3662. * @returns {OperatorNode}
  3663. */
  3664. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3665. /**
  3666. * Checks if the first node is less than or equal to the second.
  3667. *
  3668. * @tsl
  3669. * @function
  3670. * @param {Node} a - The first input.
  3671. * @param {Node} b - The second input.
  3672. * @returns {OperatorNode}
  3673. */
  3674. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  3675. /**
  3676. * Checks if the first node is greater than or equal to the second.
  3677. *
  3678. * @tsl
  3679. * @function
  3680. * @param {Node} a - The first input.
  3681. * @param {Node} b - The second input.
  3682. * @returns {OperatorNode}
  3683. */
  3684. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  3685. /**
  3686. * Performs a logical AND operation on multiple nodes.
  3687. *
  3688. * @tsl
  3689. * @function
  3690. * @param {...Node} nodes - The input nodes to be combined using AND.
  3691. * @returns {OperatorNode}
  3692. */
  3693. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  3694. /**
  3695. * Performs a logical OR operation on multiple nodes.
  3696. *
  3697. * @tsl
  3698. * @function
  3699. * @param {...Node} nodes - The input nodes to be combined using OR.
  3700. * @returns {OperatorNode}
  3701. */
  3702. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  3703. /**
  3704. * Performs logical NOT on a node.
  3705. *
  3706. * @tsl
  3707. * @function
  3708. * @param {Node} value - The value.
  3709. * @returns {OperatorNode}
  3710. */
  3711. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  3712. /**
  3713. * Performs logical XOR on two nodes.
  3714. *
  3715. * @tsl
  3716. * @function
  3717. * @param {Node} a - The first input.
  3718. * @param {Node} b - The second input.
  3719. * @returns {OperatorNode}
  3720. */
  3721. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  3722. /**
  3723. * Performs bitwise AND on two nodes.
  3724. *
  3725. * @tsl
  3726. * @function
  3727. * @param {Node} a - The first input.
  3728. * @param {Node} b - The second input.
  3729. * @returns {OperatorNode}
  3730. */
  3731. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  3732. /**
  3733. * Performs bitwise NOT on a node.
  3734. *
  3735. * @tsl
  3736. * @function
  3737. * @param {Node} a - The first input.
  3738. * @param {Node} b - The second input.
  3739. * @returns {OperatorNode}
  3740. */
  3741. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  3742. /**
  3743. * Performs bitwise OR on two nodes.
  3744. *
  3745. * @tsl
  3746. * @function
  3747. * @param {Node} a - The first input.
  3748. * @param {Node} b - The second input.
  3749. * @returns {OperatorNode}
  3750. */
  3751. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  3752. /**
  3753. * Performs bitwise XOR on two nodes.
  3754. *
  3755. * @tsl
  3756. * @function
  3757. * @param {Node} a - The first input.
  3758. * @param {Node} b - The second input.
  3759. * @returns {OperatorNode}
  3760. */
  3761. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  3762. /**
  3763. * Shifts a node to the left.
  3764. *
  3765. * @tsl
  3766. * @function
  3767. * @param {Node} a - The node to shift.
  3768. * @param {Node} b - The value to shift.
  3769. * @returns {OperatorNode}
  3770. */
  3771. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  3772. /**
  3773. * Shifts a node to the right.
  3774. *
  3775. * @tsl
  3776. * @function
  3777. * @param {Node} a - The node to shift.
  3778. * @param {Node} b - The value to shift.
  3779. * @returns {OperatorNode}
  3780. */
  3781. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  3782. /**
  3783. * Increments a node by 1.
  3784. *
  3785. * @tsl
  3786. * @function
  3787. * @param {Node} a - The node to increment.
  3788. * @returns {OperatorNode}
  3789. */
  3790. const incrementBefore = Fn( ( [ a ] ) => {
  3791. a.addAssign( 1 );
  3792. return a;
  3793. } );
  3794. /**
  3795. * Decrements a node by 1.
  3796. *
  3797. * @tsl
  3798. * @function
  3799. * @param {Node} a - The node to decrement.
  3800. * @returns {OperatorNode}
  3801. */
  3802. const decrementBefore = Fn( ( [ a ] ) => {
  3803. a.subAssign( 1 );
  3804. return a;
  3805. } );
  3806. /**
  3807. * Increments a node by 1 and returns the previous value.
  3808. *
  3809. * @tsl
  3810. * @function
  3811. * @param {Node} a - The node to increment.
  3812. * @returns {OperatorNode}
  3813. */
  3814. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3815. const temp = int( a ).toConst();
  3816. a.addAssign( 1 );
  3817. return temp;
  3818. } );
  3819. /**
  3820. * Decrements a node by 1 and returns the previous value.
  3821. *
  3822. * @tsl
  3823. * @function
  3824. * @param {Node} a - The node to decrement.
  3825. * @returns {OperatorNode}
  3826. */
  3827. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3828. const temp = int( a ).toConst();
  3829. a.subAssign( 1 );
  3830. return temp;
  3831. } );
  3832. addMethodChaining( 'add', add );
  3833. addMethodChaining( 'sub', sub );
  3834. addMethodChaining( 'mul', mul );
  3835. addMethodChaining( 'div', div );
  3836. addMethodChaining( 'mod', mod );
  3837. addMethodChaining( 'equal', equal );
  3838. addMethodChaining( 'notEqual', notEqual );
  3839. addMethodChaining( 'lessThan', lessThan );
  3840. addMethodChaining( 'greaterThan', greaterThan );
  3841. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3842. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3843. addMethodChaining( 'and', and );
  3844. addMethodChaining( 'or', or );
  3845. addMethodChaining( 'not', not );
  3846. addMethodChaining( 'xor', xor );
  3847. addMethodChaining( 'bitAnd', bitAnd );
  3848. addMethodChaining( 'bitNot', bitNot );
  3849. addMethodChaining( 'bitOr', bitOr );
  3850. addMethodChaining( 'bitXor', bitXor );
  3851. addMethodChaining( 'shiftLeft', shiftLeft );
  3852. addMethodChaining( 'shiftRight', shiftRight );
  3853. addMethodChaining( 'incrementBefore', incrementBefore );
  3854. addMethodChaining( 'decrementBefore', decrementBefore );
  3855. addMethodChaining( 'increment', increment );
  3856. addMethodChaining( 'decrement', decrement );
  3857. /**
  3858. * @tsl
  3859. * @function
  3860. * @deprecated since r168. Use {@link mod} instead.
  3861. *
  3862. * @param {Node} a - The first input.
  3863. * @param {Node} b - The second input.
  3864. * @returns {OperatorNode}
  3865. */
  3866. const remainder = ( a, b ) => { // @deprecated, r168
  3867. console.warn( 'THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3868. return mod( a, b );
  3869. };
  3870. /**
  3871. * @tsl
  3872. * @function
  3873. * @deprecated since r175. Use {@link mod} instead.
  3874. *
  3875. * @param {Node} a - The first input.
  3876. * @param {Node} b - The second input.
  3877. * @returns {OperatorNode}
  3878. */
  3879. const modInt = ( a, b ) => { // @deprecated, r175
  3880. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3881. return mod( int( a ), int( b ) );
  3882. };
  3883. addMethodChaining( 'remainder', remainder );
  3884. addMethodChaining( 'modInt', modInt );
  3885. /**
  3886. * This node represents a variety of mathematical methods available in shaders.
  3887. * They are divided into three categories:
  3888. *
  3889. * - Methods with one input like `sin`, `cos` or `normalize`.
  3890. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3891. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3892. *
  3893. * @augments TempNode
  3894. */
  3895. class MathNode extends TempNode {
  3896. static get type() {
  3897. return 'MathNode';
  3898. }
  3899. /**
  3900. * Constructs a new math node.
  3901. *
  3902. * @param {string} method - The method name.
  3903. * @param {Node} aNode - The first input.
  3904. * @param {?Node} [bNode=null] - The second input.
  3905. * @param {?Node} [cNode=null] - The third input.
  3906. */
  3907. constructor( method, aNode, bNode = null, cNode = null ) {
  3908. super();
  3909. // Allow the max() and min() functions to take an arbitrary number of arguments.
  3910. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  3911. let finalOp = new MathNode( method, aNode, bNode );
  3912. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  3913. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  3914. }
  3915. aNode = finalOp;
  3916. bNode = arguments[ arguments.length - 1 ];
  3917. cNode = null;
  3918. }
  3919. /**
  3920. * The method name.
  3921. *
  3922. * @type {string}
  3923. */
  3924. this.method = method;
  3925. /**
  3926. * The first input.
  3927. *
  3928. * @type {Node}
  3929. */
  3930. this.aNode = aNode;
  3931. /**
  3932. * The second input.
  3933. *
  3934. * @type {?Node}
  3935. * @default null
  3936. */
  3937. this.bNode = bNode;
  3938. /**
  3939. * The third input.
  3940. *
  3941. * @type {?Node}
  3942. * @default null
  3943. */
  3944. this.cNode = cNode;
  3945. /**
  3946. * This flag can be used for type testing.
  3947. *
  3948. * @type {boolean}
  3949. * @readonly
  3950. * @default true
  3951. */
  3952. this.isMathNode = true;
  3953. }
  3954. /**
  3955. * The input type is inferred from the node types of the input nodes.
  3956. *
  3957. * @param {NodeBuilder} builder - The current node builder.
  3958. * @return {string} The input type.
  3959. */
  3960. getInputType( builder ) {
  3961. const aType = this.aNode.getNodeType( builder );
  3962. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3963. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3964. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3965. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3966. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3967. if ( aLen > bLen && aLen > cLen ) {
  3968. return aType;
  3969. } else if ( bLen > cLen ) {
  3970. return bType;
  3971. } else if ( cLen > aLen ) {
  3972. return cType;
  3973. }
  3974. return aType;
  3975. }
  3976. /**
  3977. * The selected method as well as the input type determine the node type of this node.
  3978. *
  3979. * @param {NodeBuilder} builder - The current node builder.
  3980. * @return {string} The node type.
  3981. */
  3982. getNodeType( builder ) {
  3983. const method = this.method;
  3984. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3985. return 'float';
  3986. } else if ( method === MathNode.CROSS ) {
  3987. return 'vec3';
  3988. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  3989. return 'bool';
  3990. } else if ( method === MathNode.EQUALS ) {
  3991. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3992. } else {
  3993. return this.getInputType( builder );
  3994. }
  3995. }
  3996. generate( builder, output ) {
  3997. let method = this.method;
  3998. const type = this.getNodeType( builder );
  3999. const inputType = this.getInputType( builder );
  4000. const a = this.aNode;
  4001. const b = this.bNode;
  4002. const c = this.cNode;
  4003. const coordinateSystem = builder.renderer.coordinateSystem;
  4004. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4005. // dir can be either a direction vector or a normal vector
  4006. // upper-left 3x3 of matrix is assumed to be orthogonal
  4007. let tA = a;
  4008. let tB = b;
  4009. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4010. tB = vec4( vec3( tB ), 0.0 );
  4011. } else {
  4012. tA = vec4( vec3( tA ), 0.0 );
  4013. }
  4014. const mulNode = mul( tA, tB ).xyz;
  4015. return normalize( mulNode ).build( builder, output );
  4016. } else if ( method === MathNode.NEGATE ) {
  4017. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4018. } else if ( method === MathNode.ONE_MINUS ) {
  4019. return sub( 1.0, a ).build( builder, output );
  4020. } else if ( method === MathNode.RECIPROCAL ) {
  4021. return div( 1.0, a ).build( builder, output );
  4022. } else if ( method === MathNode.DIFFERENCE ) {
  4023. return abs( sub( a, b ) ).build( builder, output );
  4024. } else {
  4025. const params = [];
  4026. if ( method === MathNode.CROSS ) {
  4027. params.push(
  4028. a.build( builder, type ),
  4029. b.build( builder, type )
  4030. );
  4031. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4032. params.push(
  4033. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4034. b.build( builder, inputType )
  4035. );
  4036. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4037. params.push(
  4038. a.build( builder, inputType ),
  4039. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4040. );
  4041. } else if ( method === MathNode.REFRACT ) {
  4042. params.push(
  4043. a.build( builder, inputType ),
  4044. b.build( builder, inputType ),
  4045. c.build( builder, 'float' )
  4046. );
  4047. } else if ( method === MathNode.MIX ) {
  4048. params.push(
  4049. a.build( builder, inputType ),
  4050. b.build( builder, inputType ),
  4051. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4052. );
  4053. } else {
  4054. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4055. method = 'atan2';
  4056. }
  4057. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4058. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4059. method = '/*' + method + '*/';
  4060. }
  4061. params.push( a.build( builder, inputType ) );
  4062. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4063. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4064. }
  4065. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4066. }
  4067. }
  4068. serialize( data ) {
  4069. super.serialize( data );
  4070. data.method = this.method;
  4071. }
  4072. deserialize( data ) {
  4073. super.deserialize( data );
  4074. this.method = data.method;
  4075. }
  4076. }
  4077. // 1 input
  4078. MathNode.ALL = 'all';
  4079. MathNode.ANY = 'any';
  4080. MathNode.RADIANS = 'radians';
  4081. MathNode.DEGREES = 'degrees';
  4082. MathNode.EXP = 'exp';
  4083. MathNode.EXP2 = 'exp2';
  4084. MathNode.LOG = 'log';
  4085. MathNode.LOG2 = 'log2';
  4086. MathNode.SQRT = 'sqrt';
  4087. MathNode.INVERSE_SQRT = 'inversesqrt';
  4088. MathNode.FLOOR = 'floor';
  4089. MathNode.CEIL = 'ceil';
  4090. MathNode.NORMALIZE = 'normalize';
  4091. MathNode.FRACT = 'fract';
  4092. MathNode.SIN = 'sin';
  4093. MathNode.COS = 'cos';
  4094. MathNode.TAN = 'tan';
  4095. MathNode.ASIN = 'asin';
  4096. MathNode.ACOS = 'acos';
  4097. MathNode.ATAN = 'atan';
  4098. MathNode.ABS = 'abs';
  4099. MathNode.SIGN = 'sign';
  4100. MathNode.LENGTH = 'length';
  4101. MathNode.NEGATE = 'negate';
  4102. MathNode.ONE_MINUS = 'oneMinus';
  4103. MathNode.DFDX = 'dFdx';
  4104. MathNode.DFDY = 'dFdy';
  4105. MathNode.ROUND = 'round';
  4106. MathNode.RECIPROCAL = 'reciprocal';
  4107. MathNode.TRUNC = 'trunc';
  4108. MathNode.FWIDTH = 'fwidth';
  4109. MathNode.TRANSPOSE = 'transpose';
  4110. // 2 inputs
  4111. MathNode.BITCAST = 'bitcast';
  4112. MathNode.EQUALS = 'equals';
  4113. MathNode.MIN = 'min';
  4114. MathNode.MAX = 'max';
  4115. MathNode.STEP = 'step';
  4116. MathNode.REFLECT = 'reflect';
  4117. MathNode.DISTANCE = 'distance';
  4118. MathNode.DIFFERENCE = 'difference';
  4119. MathNode.DOT = 'dot';
  4120. MathNode.CROSS = 'cross';
  4121. MathNode.POW = 'pow';
  4122. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4123. // 3 inputs
  4124. MathNode.MIX = 'mix';
  4125. MathNode.CLAMP = 'clamp';
  4126. MathNode.REFRACT = 'refract';
  4127. MathNode.SMOOTHSTEP = 'smoothstep';
  4128. MathNode.FACEFORWARD = 'faceforward';
  4129. // 1 inputs
  4130. /**
  4131. * A small value used to handle floating-point precision errors.
  4132. *
  4133. * @tsl
  4134. * @type {Node<float>}
  4135. */
  4136. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4137. /**
  4138. * Represents infinity.
  4139. *
  4140. * @tsl
  4141. * @type {Node<float>}
  4142. */
  4143. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4144. /**
  4145. * Represents PI.
  4146. *
  4147. * @tsl
  4148. * @type {Node<float>}
  4149. */
  4150. const PI = /*@__PURE__*/ float( Math.PI );
  4151. /**
  4152. * Represents PI * 2.
  4153. *
  4154. * @tsl
  4155. * @type {Node<float>}
  4156. */
  4157. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4158. /**
  4159. * Returns `true` if all components of `x` are `true`.
  4160. *
  4161. * @tsl
  4162. * @function
  4163. * @param {Node | number} x - The parameter.
  4164. * @returns {Node<bool>}
  4165. */
  4166. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4167. /**
  4168. * Returns `true` if any components of `x` are `true`.
  4169. *
  4170. * @tsl
  4171. * @function
  4172. * @param {Node | number} x - The parameter.
  4173. * @returns {Node<bool>}
  4174. */
  4175. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4176. /**
  4177. * Converts a quantity in degrees to radians.
  4178. *
  4179. * @tsl
  4180. * @function
  4181. * @param {Node | number} x - The input in degrees.
  4182. * @returns {Node}
  4183. */
  4184. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4185. /**
  4186. * Convert a quantity in radians to degrees.
  4187. *
  4188. * @tsl
  4189. * @function
  4190. * @param {Node | number} x - The input in radians.
  4191. * @returns {Node}
  4192. */
  4193. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4194. /**
  4195. * Returns the natural exponentiation of the parameter.
  4196. *
  4197. * @tsl
  4198. * @function
  4199. * @param {Node | number} x - The parameter.
  4200. * @returns {Node}
  4201. */
  4202. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4203. /**
  4204. * Returns 2 raised to the power of the parameter.
  4205. *
  4206. * @tsl
  4207. * @function
  4208. * @param {Node | number} x - The parameter.
  4209. * @returns {Node}
  4210. */
  4211. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4212. /**
  4213. * Returns the natural logarithm of the parameter.
  4214. *
  4215. * @tsl
  4216. * @function
  4217. * @param {Node | number} x - The parameter.
  4218. * @returns {Node}
  4219. */
  4220. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4221. /**
  4222. * Returns the base 2 logarithm of the parameter.
  4223. *
  4224. * @tsl
  4225. * @function
  4226. * @param {Node | number} x - The parameter.
  4227. * @returns {Node}
  4228. */
  4229. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4230. /**
  4231. * Returns the square root of the parameter.
  4232. *
  4233. * @tsl
  4234. * @function
  4235. * @param {Node | number} x - The parameter.
  4236. * @returns {Node}
  4237. */
  4238. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4239. /**
  4240. * Returns the inverse of the square root of the parameter.
  4241. *
  4242. * @tsl
  4243. * @function
  4244. * @param {Node | number} x - The parameter.
  4245. * @returns {Node}
  4246. */
  4247. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4248. /**
  4249. * Finds the nearest integer less than or equal to the parameter.
  4250. *
  4251. * @tsl
  4252. * @function
  4253. * @param {Node | number} x - The parameter.
  4254. * @returns {Node}
  4255. */
  4256. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4257. /**
  4258. * Finds the nearest integer that is greater than or equal to the parameter.
  4259. *
  4260. * @tsl
  4261. * @function
  4262. * @param {Node | number} x - The parameter.
  4263. * @returns {Node}
  4264. */
  4265. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4266. /**
  4267. * Calculates the unit vector in the same direction as the original vector.
  4268. *
  4269. * @tsl
  4270. * @function
  4271. * @param {Node} x - The input vector.
  4272. * @returns {Node}
  4273. */
  4274. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4275. /**
  4276. * Computes the fractional part of the parameter.
  4277. *
  4278. * @tsl
  4279. * @function
  4280. * @param {Node | number} x - The parameter.
  4281. * @returns {Node}
  4282. */
  4283. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4284. /**
  4285. * Returns the sine of the parameter.
  4286. *
  4287. * @tsl
  4288. * @function
  4289. * @param {Node | number} x - The parameter.
  4290. * @returns {Node}
  4291. */
  4292. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4293. /**
  4294. * Returns the cosine of the parameter.
  4295. *
  4296. * @tsl
  4297. * @function
  4298. * @param {Node | number} x - The parameter.
  4299. * @returns {Node}
  4300. */
  4301. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS ).setParameterLength( 1 );
  4302. /**
  4303. * Returns the tangent of the parameter.
  4304. *
  4305. * @tsl
  4306. * @function
  4307. * @param {Node | number} x - The parameter.
  4308. * @returns {Node}
  4309. */
  4310. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4311. /**
  4312. * Returns the arcsine of the parameter.
  4313. *
  4314. * @tsl
  4315. * @function
  4316. * @param {Node | number} x - The parameter.
  4317. * @returns {Node}
  4318. */
  4319. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4320. /**
  4321. * Returns the arccosine of the parameter.
  4322. *
  4323. * @tsl
  4324. * @function
  4325. * @param {Node | number} x - The parameter.
  4326. * @returns {Node}
  4327. */
  4328. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4329. /**
  4330. * Returns the arc-tangent of the parameter.
  4331. * If two parameters are provided, the result is `atan2(y/x)`.
  4332. *
  4333. * @tsl
  4334. * @function
  4335. * @param {Node | number} y - The y parameter.
  4336. * @param {?(Node | number)} x - The x parameter.
  4337. * @returns {Node}
  4338. */
  4339. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4340. /**
  4341. * Returns the absolute value of the parameter.
  4342. *
  4343. * @tsl
  4344. * @function
  4345. * @param {Node | number} x - The parameter.
  4346. * @returns {Node}
  4347. */
  4348. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4349. /**
  4350. * Extracts the sign of the parameter.
  4351. *
  4352. * @tsl
  4353. * @function
  4354. * @param {Node | number} x - The parameter.
  4355. * @returns {Node}
  4356. */
  4357. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4358. /**
  4359. * Calculates the length of a vector.
  4360. *
  4361. * @tsl
  4362. * @function
  4363. * @param {Node} x - The parameter.
  4364. * @returns {Node<float>}
  4365. */
  4366. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4367. /**
  4368. * Negates the value of the parameter (-x).
  4369. *
  4370. * @tsl
  4371. * @function
  4372. * @param {Node | number} x - The parameter.
  4373. * @returns {Node}
  4374. */
  4375. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4376. /**
  4377. * Return `1` minus the parameter.
  4378. *
  4379. * @tsl
  4380. * @function
  4381. * @param {Node | number} x - The parameter.
  4382. * @returns {Node}
  4383. */
  4384. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4385. /**
  4386. * Returns the partial derivative of the parameter with respect to x.
  4387. *
  4388. * @tsl
  4389. * @function
  4390. * @param {Node | number} x - The parameter.
  4391. * @returns {Node}
  4392. */
  4393. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4394. /**
  4395. * Returns the partial derivative of the parameter with respect to y.
  4396. *
  4397. * @tsl
  4398. * @function
  4399. * @param {Node | number} x - The parameter.
  4400. * @returns {Node}
  4401. */
  4402. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4403. /**
  4404. * Rounds the parameter to the nearest integer.
  4405. *
  4406. * @tsl
  4407. * @function
  4408. * @param {Node | number} x - The parameter.
  4409. * @returns {Node}
  4410. */
  4411. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4412. /**
  4413. * Returns the reciprocal of the parameter `(1/x)`.
  4414. *
  4415. * @tsl
  4416. * @function
  4417. * @param {Node | number} x - The parameter.
  4418. * @returns {Node}
  4419. */
  4420. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4421. /**
  4422. * Truncates the parameter, removing the fractional part.
  4423. *
  4424. * @tsl
  4425. * @function
  4426. * @param {Node | number} x - The parameter.
  4427. * @returns {Node}
  4428. */
  4429. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4430. /**
  4431. * Returns the sum of the absolute derivatives in x and y.
  4432. *
  4433. * @tsl
  4434. * @function
  4435. * @param {Node | number} x - The parameter.
  4436. * @returns {Node}
  4437. */
  4438. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4439. /**
  4440. * Returns the transpose of a matrix.
  4441. *
  4442. * @tsl
  4443. * @function
  4444. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4445. * @returns {Node}
  4446. */
  4447. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4448. // 2 inputs
  4449. /**
  4450. * Reinterpret the bit representation of a value in one type as a value in another type.
  4451. *
  4452. * @tsl
  4453. * @function
  4454. * @param {Node | number} x - The parameter.
  4455. * @param {string} y - The new type.
  4456. * @returns {Node}
  4457. */
  4458. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4459. /**
  4460. * Returns `true` if `x` equals `y`.
  4461. *
  4462. * @tsl
  4463. * @function
  4464. * @param {Node | number} x - The first parameter.
  4465. * @param {Node | number} y - The second parameter.
  4466. * @deprecated since r175. Use {@link equal} instead.
  4467. * @returns {Node<bool>}
  4468. */
  4469. const equals = ( x, y ) => { // @deprecated, r172
  4470. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4471. return equal( x, y );
  4472. };
  4473. /**
  4474. * Returns the least of the given values.
  4475. *
  4476. * @tsl
  4477. * @function
  4478. * @param {...(Node | number)} values - The values to compare.
  4479. * @returns {Node}
  4480. */
  4481. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4482. /**
  4483. * Returns the greatest of the given values.
  4484. *
  4485. * @tsl
  4486. * @function
  4487. * @param {...(Node | number)} values - The values to compare.
  4488. * @returns {Node}
  4489. */
  4490. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4491. /**
  4492. * Generate a step function by comparing two values.
  4493. *
  4494. * @tsl
  4495. * @function
  4496. * @param {Node | number} x - The y parameter.
  4497. * @param {Node | number} y - The x parameter.
  4498. * @returns {Node}
  4499. */
  4500. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4501. /**
  4502. * Calculates the reflection direction for an incident vector.
  4503. *
  4504. * @tsl
  4505. * @function
  4506. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4507. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4508. * @returns {Node<vec2|vec3|vec4>}
  4509. */
  4510. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4511. /**
  4512. * Calculates the distance between two points.
  4513. *
  4514. * @tsl
  4515. * @function
  4516. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4517. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4518. * @returns {Node<float>}
  4519. */
  4520. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4521. /**
  4522. * Calculates the absolute difference between two values.
  4523. *
  4524. * @tsl
  4525. * @function
  4526. * @param {Node | number} x - The first parameter.
  4527. * @param {Node | number} y - The second parameter.
  4528. * @returns {Node}
  4529. */
  4530. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4531. /**
  4532. * Calculates the dot product of two vectors.
  4533. *
  4534. * @tsl
  4535. * @function
  4536. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4537. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4538. * @returns {Node<float>}
  4539. */
  4540. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4541. /**
  4542. * Calculates the cross product of two vectors.
  4543. *
  4544. * @tsl
  4545. * @function
  4546. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4547. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4548. * @returns {Node<vec2|vec3|vec4>}
  4549. */
  4550. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4551. /**
  4552. * Return the value of the first parameter raised to the power of the second one.
  4553. *
  4554. * @tsl
  4555. * @function
  4556. * @param {Node | number} x - The first parameter.
  4557. * @param {Node | number} y - The second parameter.
  4558. * @returns {Node}
  4559. */
  4560. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW ).setParameterLength( 2 );
  4561. /**
  4562. * Returns the square of the parameter.
  4563. *
  4564. * @tsl
  4565. * @function
  4566. * @param {Node | number} x - The first parameter.
  4567. * @returns {Node}
  4568. */
  4569. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4570. /**
  4571. * Returns the cube of the parameter.
  4572. *
  4573. * @tsl
  4574. * @function
  4575. * @param {Node | number} x - The first parameter.
  4576. * @returns {Node}
  4577. */
  4578. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4579. /**
  4580. * Returns the fourth power of the parameter.
  4581. *
  4582. * @tsl
  4583. * @function
  4584. * @param {Node | number} x - The first parameter.
  4585. * @returns {Node}
  4586. */
  4587. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4588. /**
  4589. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4590. *
  4591. * @tsl
  4592. * @function
  4593. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4594. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4595. * @returns {Node}
  4596. */
  4597. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4598. /**
  4599. * Returns the cube root of a number.
  4600. *
  4601. * @tsl
  4602. * @function
  4603. * @param {Node | number} a - The first parameter.
  4604. * @returns {Node}
  4605. */
  4606. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4607. /**
  4608. * Calculate the squared length of a vector.
  4609. *
  4610. * @tsl
  4611. * @function
  4612. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4613. * @returns {Node<float>}
  4614. */
  4615. const lengthSq = ( a ) => dot( a, a );
  4616. /**
  4617. * Linearly interpolates between two values.
  4618. *
  4619. * @tsl
  4620. * @function
  4621. * @param {Node | number} a - The first parameter.
  4622. * @param {Node | number} b - The second parameter.
  4623. * @param {Node | number} t - The interpolation value.
  4624. * @returns {Node}
  4625. */
  4626. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4627. /**
  4628. * Constrains a value to lie between two further values.
  4629. *
  4630. * @tsl
  4631. * @function
  4632. * @param {Node | number} value - The value to constrain.
  4633. * @param {Node | number} [low=0] - The lower bound.
  4634. * @param {Node | number} [high=1] - The upper bound.
  4635. * @returns {Node}
  4636. */
  4637. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4638. /**
  4639. * Constrains a value between `0` and `1`.
  4640. *
  4641. * @tsl
  4642. * @function
  4643. * @param {Node | number} value - The value to constrain.
  4644. * @returns {Node}
  4645. */
  4646. const saturate = ( value ) => clamp( value );
  4647. /**
  4648. * Calculates the refraction direction for an incident vector.
  4649. *
  4650. * @tsl
  4651. * @function
  4652. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4653. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4654. * @param {Node<float>} eta - The ratio of indices of refraction.
  4655. * @returns {Node<vec2|vec3|vec4>}
  4656. */
  4657. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  4658. /**
  4659. * Performs a Hermite interpolation between two values.
  4660. *
  4661. * @tsl
  4662. * @function
  4663. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4664. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4665. * @param {Node | number} x - The source value for interpolation.
  4666. * @returns {Node}
  4667. */
  4668. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  4669. /**
  4670. * Returns a vector pointing in the same direction as another.
  4671. *
  4672. * @tsl
  4673. * @function
  4674. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4675. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4676. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4677. * @returns {Node<vec2|vec3|vec4>}
  4678. */
  4679. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  4680. /**
  4681. * Returns a random value for the given uv.
  4682. *
  4683. * @tsl
  4684. * @function
  4685. * @param {Node<vec2>} uv - The uv node.
  4686. * @returns {Node<float>}
  4687. */
  4688. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4689. const a = 12.9898, b = 78.233, c = 43758.5453;
  4690. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4691. return fract( sin( sn ).mul( c ) );
  4692. } );
  4693. /**
  4694. * Alias for `mix()` with a different parameter order.
  4695. *
  4696. * @tsl
  4697. * @function
  4698. * @param {Node | number} t - The interpolation value.
  4699. * @param {Node | number} e1 - The first parameter.
  4700. * @param {Node | number} e2 - The second parameter.
  4701. * @returns {Node}
  4702. */
  4703. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4704. /**
  4705. * Alias for `smoothstep()` with a different parameter order.
  4706. *
  4707. * @tsl
  4708. * @function
  4709. * @param {Node | number} x - The source value for interpolation.
  4710. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4711. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4712. * @returns {Node}
  4713. */
  4714. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4715. /**
  4716. * Returns the arc-tangent of the quotient of its parameters.
  4717. *
  4718. * @tsl
  4719. * @function
  4720. * @deprecated since r172. Use {@link atan} instead.
  4721. *
  4722. * @param {Node | number} y - The y parameter.
  4723. * @param {Node | number} x - The x parameter.
  4724. * @returns {Node}
  4725. */
  4726. const atan2 = ( y, x ) => { // @deprecated, r172
  4727. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4728. return atan( y, x );
  4729. };
  4730. // GLSL alias function
  4731. const faceforward = faceForward;
  4732. const inversesqrt = inverseSqrt;
  4733. // Method chaining
  4734. addMethodChaining( 'all', all );
  4735. addMethodChaining( 'any', any );
  4736. addMethodChaining( 'equals', equals );
  4737. addMethodChaining( 'radians', radians );
  4738. addMethodChaining( 'degrees', degrees );
  4739. addMethodChaining( 'exp', exp );
  4740. addMethodChaining( 'exp2', exp2 );
  4741. addMethodChaining( 'log', log );
  4742. addMethodChaining( 'log2', log2 );
  4743. addMethodChaining( 'sqrt', sqrt );
  4744. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4745. addMethodChaining( 'floor', floor );
  4746. addMethodChaining( 'ceil', ceil );
  4747. addMethodChaining( 'normalize', normalize );
  4748. addMethodChaining( 'fract', fract );
  4749. addMethodChaining( 'sin', sin );
  4750. addMethodChaining( 'cos', cos );
  4751. addMethodChaining( 'tan', tan );
  4752. addMethodChaining( 'asin', asin );
  4753. addMethodChaining( 'acos', acos );
  4754. addMethodChaining( 'atan', atan );
  4755. addMethodChaining( 'abs', abs );
  4756. addMethodChaining( 'sign', sign );
  4757. addMethodChaining( 'length', length );
  4758. addMethodChaining( 'lengthSq', lengthSq );
  4759. addMethodChaining( 'negate', negate );
  4760. addMethodChaining( 'oneMinus', oneMinus );
  4761. addMethodChaining( 'dFdx', dFdx );
  4762. addMethodChaining( 'dFdy', dFdy );
  4763. addMethodChaining( 'round', round );
  4764. addMethodChaining( 'reciprocal', reciprocal );
  4765. addMethodChaining( 'trunc', trunc );
  4766. addMethodChaining( 'fwidth', fwidth );
  4767. addMethodChaining( 'atan2', atan2 );
  4768. addMethodChaining( 'min', min$1 );
  4769. addMethodChaining( 'max', max$1 );
  4770. addMethodChaining( 'step', step );
  4771. addMethodChaining( 'reflect', reflect );
  4772. addMethodChaining( 'distance', distance );
  4773. addMethodChaining( 'dot', dot );
  4774. addMethodChaining( 'cross', cross );
  4775. addMethodChaining( 'pow', pow );
  4776. addMethodChaining( 'pow2', pow2 );
  4777. addMethodChaining( 'pow3', pow3 );
  4778. addMethodChaining( 'pow4', pow4 );
  4779. addMethodChaining( 'transformDirection', transformDirection );
  4780. addMethodChaining( 'mix', mixElement );
  4781. addMethodChaining( 'clamp', clamp );
  4782. addMethodChaining( 'refract', refract );
  4783. addMethodChaining( 'smoothstep', smoothstepElement );
  4784. addMethodChaining( 'faceForward', faceForward );
  4785. addMethodChaining( 'difference', difference );
  4786. addMethodChaining( 'saturate', saturate );
  4787. addMethodChaining( 'cbrt', cbrt );
  4788. addMethodChaining( 'transpose', transpose );
  4789. addMethodChaining( 'rand', rand );
  4790. /**
  4791. * Represents a logical `if/else` statement. Can be used as an alternative
  4792. * to the `If()`/`Else()` syntax.
  4793. *
  4794. * The corresponding TSL `select()` looks like so:
  4795. * ```js
  4796. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4797. * ```
  4798. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4799. * determine the outcome of the entire statement.
  4800. *
  4801. * @augments Node
  4802. */
  4803. class ConditionalNode extends Node {
  4804. static get type() {
  4805. return 'ConditionalNode';
  4806. }
  4807. /**
  4808. * Constructs a new conditional node.
  4809. *
  4810. * @param {Node} condNode - The node that defines the condition.
  4811. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4812. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4813. */
  4814. constructor( condNode, ifNode, elseNode = null ) {
  4815. super();
  4816. /**
  4817. * The node that defines the condition.
  4818. *
  4819. * @type {Node}
  4820. */
  4821. this.condNode = condNode;
  4822. /**
  4823. * The node that is evaluate when the condition ends up `true`.
  4824. *
  4825. * @type {Node}
  4826. */
  4827. this.ifNode = ifNode;
  4828. /**
  4829. * The node that is evaluate when the condition ends up `false`.
  4830. *
  4831. * @type {?Node}
  4832. * @default null
  4833. */
  4834. this.elseNode = elseNode;
  4835. }
  4836. /**
  4837. * This method is overwritten since the node type is inferred from the if/else
  4838. * nodes.
  4839. *
  4840. * @param {NodeBuilder} builder - The current node builder.
  4841. * @return {string} The node type.
  4842. */
  4843. getNodeType( builder ) {
  4844. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4845. if ( ifNode === undefined ) {
  4846. // fallback setup
  4847. this.setup( builder );
  4848. return this.getNodeType( builder );
  4849. }
  4850. const ifType = ifNode.getNodeType( builder );
  4851. if ( elseNode !== null ) {
  4852. const elseType = elseNode.getNodeType( builder );
  4853. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4854. return elseType;
  4855. }
  4856. }
  4857. return ifType;
  4858. }
  4859. setup( builder ) {
  4860. const condNode = this.condNode.cache();
  4861. const ifNode = this.ifNode.cache();
  4862. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4863. //
  4864. const currentNodeBlock = builder.context.nodeBlock;
  4865. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4866. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4867. //
  4868. const properties = builder.getNodeProperties( this );
  4869. properties.condNode = condNode;
  4870. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4871. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4872. }
  4873. generate( builder, output ) {
  4874. const type = this.getNodeType( builder );
  4875. const nodeData = builder.getDataFromNode( this );
  4876. if ( nodeData.nodeProperty !== undefined ) {
  4877. return nodeData.nodeProperty;
  4878. }
  4879. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4880. const functionNode = builder.currentFunctionNode;
  4881. const needsOutput = output !== 'void';
  4882. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4883. nodeData.nodeProperty = nodeProperty;
  4884. const nodeSnippet = condNode.build( builder, 'bool' );
  4885. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4886. let ifSnippet = ifNode.build( builder, type );
  4887. if ( ifSnippet ) {
  4888. if ( needsOutput ) {
  4889. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4890. } else {
  4891. ifSnippet = 'return ' + ifSnippet + ';';
  4892. if ( functionNode === null ) {
  4893. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  4894. ifSnippet = '// ' + ifSnippet;
  4895. }
  4896. }
  4897. }
  4898. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4899. if ( elseNode !== null ) {
  4900. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4901. let elseSnippet = elseNode.build( builder, type );
  4902. if ( elseSnippet ) {
  4903. if ( needsOutput ) {
  4904. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4905. } else {
  4906. elseSnippet = 'return ' + elseSnippet + ';';
  4907. if ( functionNode === null ) {
  4908. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  4909. elseSnippet = '// ' + elseSnippet;
  4910. }
  4911. }
  4912. }
  4913. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4914. } else {
  4915. builder.addFlowCode( '\n\n' );
  4916. }
  4917. return builder.format( nodeProperty, type, output );
  4918. }
  4919. }
  4920. /**
  4921. * TSL function for creating a conditional node.
  4922. *
  4923. * @tsl
  4924. * @function
  4925. * @param {Node} condNode - The node that defines the condition.
  4926. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4927. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4928. * @returns {ConditionalNode}
  4929. */
  4930. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  4931. addMethodChaining( 'select', select );
  4932. // Deprecated
  4933. /**
  4934. * @tsl
  4935. * @function
  4936. * @deprecated since r168. Use {@link select} instead.
  4937. *
  4938. * @param {...any} params
  4939. * @returns {ConditionalNode}
  4940. */
  4941. const cond = ( ...params ) => { // @deprecated, r168
  4942. console.warn( 'THREE.TSL: cond() has been renamed to select().' );
  4943. return select( ...params );
  4944. };
  4945. addMethodChaining( 'cond', cond );
  4946. /**
  4947. * This node can be used as a context management component for another node.
  4948. * {@link NodeBuilder} performs its node building process in a specific context and
  4949. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4950. *
  4951. * ```js
  4952. *node.context( { getUV: () => customCoord } );
  4953. *```
  4954. * @augments Node
  4955. */
  4956. class ContextNode extends Node {
  4957. static get type() {
  4958. return 'ContextNode';
  4959. }
  4960. /**
  4961. * Constructs a new context node.
  4962. *
  4963. * @param {Node} node - The node whose context should be modified.
  4964. * @param {Object} [value={}] - The modified context data.
  4965. */
  4966. constructor( node, value = {} ) {
  4967. super();
  4968. /**
  4969. * This flag can be used for type testing.
  4970. *
  4971. * @type {boolean}
  4972. * @readonly
  4973. * @default true
  4974. */
  4975. this.isContextNode = true;
  4976. /**
  4977. * The node whose context should be modified.
  4978. *
  4979. * @type {Node}
  4980. */
  4981. this.node = node;
  4982. /**
  4983. * The modified context data.
  4984. *
  4985. * @type {Object}
  4986. * @default {}
  4987. */
  4988. this.value = value;
  4989. }
  4990. /**
  4991. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  4992. *
  4993. * @return {Node} A reference to {@link ContextNode#node}.
  4994. */
  4995. getScope() {
  4996. return this.node.getScope();
  4997. }
  4998. /**
  4999. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5000. *
  5001. * @param {NodeBuilder} builder - The current node builder.
  5002. * @return {string} The node type.
  5003. */
  5004. getNodeType( builder ) {
  5005. return this.node.getNodeType( builder );
  5006. }
  5007. analyze( builder ) {
  5008. this.node.build( builder );
  5009. }
  5010. setup( builder ) {
  5011. const previousContext = builder.getContext();
  5012. builder.setContext( { ...builder.context, ...this.value } );
  5013. const node = this.node.build( builder );
  5014. builder.setContext( previousContext );
  5015. return node;
  5016. }
  5017. generate( builder, output ) {
  5018. const previousContext = builder.getContext();
  5019. builder.setContext( { ...builder.context, ...this.value } );
  5020. const snippet = this.node.build( builder, output );
  5021. builder.setContext( previousContext );
  5022. return snippet;
  5023. }
  5024. }
  5025. /**
  5026. * TSL function for creating a context node.
  5027. *
  5028. * @tsl
  5029. * @function
  5030. * @param {Node} node - The node whose context should be modified.
  5031. * @param {Object} [value={}] - The modified context data.
  5032. * @returns {ContextNode}
  5033. */
  5034. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5035. /**
  5036. * TSL function for defining a label context value for a given node.
  5037. *
  5038. * @tsl
  5039. * @function
  5040. * @param {Node} node - The node whose context should be modified.
  5041. * @param {string} name - The name/label to set.
  5042. * @returns {ContextNode}
  5043. */
  5044. const label = ( node, name ) => context( node, { label: name } );
  5045. addMethodChaining( 'context', context );
  5046. addMethodChaining( 'label', label );
  5047. /**
  5048. * Class for representing shader variables as nodes. Variables are created from
  5049. * existing nodes like the following:
  5050. *
  5051. * ```js
  5052. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5053. * ```
  5054. *
  5055. * @augments Node
  5056. */
  5057. class VarNode extends Node {
  5058. static get type() {
  5059. return 'VarNode';
  5060. }
  5061. /**
  5062. * Constructs a new variable node.
  5063. *
  5064. * @param {Node} node - The node for which a variable should be created.
  5065. * @param {?string} [name=null] - The name of the variable in the shader.
  5066. * @param {boolean} [readOnly=false] - The read-only flag.
  5067. */
  5068. constructor( node, name = null, readOnly = false ) {
  5069. super();
  5070. /**
  5071. * The node for which a variable should be created.
  5072. *
  5073. * @type {Node}
  5074. */
  5075. this.node = node;
  5076. /**
  5077. * The name of the variable in the shader. If no name is defined,
  5078. * the node system auto-generates one.
  5079. *
  5080. * @type {?string}
  5081. * @default null
  5082. */
  5083. this.name = name;
  5084. /**
  5085. * `VarNode` sets this property to `true` by default.
  5086. *
  5087. * @type {boolean}
  5088. * @default true
  5089. */
  5090. this.global = true;
  5091. /**
  5092. * This flag can be used for type testing.
  5093. *
  5094. * @type {boolean}
  5095. * @readonly
  5096. * @default true
  5097. */
  5098. this.isVarNode = true;
  5099. /**
  5100. *
  5101. * The read-only flag.
  5102. *
  5103. * @type {boolean}
  5104. * @default false
  5105. */
  5106. this.readOnly = readOnly;
  5107. }
  5108. getMemberType( builder, name ) {
  5109. return this.node.getMemberType( builder, name );
  5110. }
  5111. getElementType( builder ) {
  5112. return this.node.getElementType( builder );
  5113. }
  5114. getNodeType( builder ) {
  5115. return this.node.getNodeType( builder );
  5116. }
  5117. generate( builder ) {
  5118. const { node, name, readOnly } = this;
  5119. const { renderer } = builder;
  5120. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5121. let isDeterministic = false;
  5122. let shouldTreatAsReadOnly = false;
  5123. if ( readOnly ) {
  5124. isDeterministic = builder.isDeterministic( node );
  5125. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5126. }
  5127. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5128. const snippet = node.build( builder, vectorType );
  5129. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5130. const propertyName = builder.getPropertyName( nodeVar );
  5131. let declarationPrefix = propertyName;
  5132. if ( shouldTreatAsReadOnly ) {
  5133. if ( isWebGPUBackend ) {
  5134. declarationPrefix = isDeterministic
  5135. ? `const ${ propertyName }`
  5136. : `let ${ propertyName }`;
  5137. } else {
  5138. const count = builder.getArrayCount( node );
  5139. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5140. }
  5141. }
  5142. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5143. return propertyName;
  5144. }
  5145. }
  5146. /**
  5147. * TSL function for creating a var node.
  5148. *
  5149. * @tsl
  5150. * @function
  5151. * @param {Node} node - The node for which a variable should be created.
  5152. * @param {?string} name - The name of the variable in the shader.
  5153. * @returns {VarNode}
  5154. */
  5155. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5156. /**
  5157. * TSL function for creating a var node.
  5158. *
  5159. * @tsl
  5160. * @function
  5161. * @param {Node} node - The node for which a variable should be created.
  5162. * @param {?string} name - The name of the variable in the shader.
  5163. * @returns {VarNode}
  5164. */
  5165. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5166. /**
  5167. * TSL function for creating a const node.
  5168. *
  5169. * @tsl
  5170. * @function
  5171. * @param {Node} node - The node for which a constant should be created.
  5172. * @param {?string} name - The name of the constant in the shader.
  5173. * @returns {VarNode}
  5174. */
  5175. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5176. // Method chaining
  5177. addMethodChaining( 'toVar', Var );
  5178. addMethodChaining( 'toConst', Const );
  5179. // Deprecated
  5180. /**
  5181. * @tsl
  5182. * @function
  5183. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  5184. *
  5185. * @param {any} node
  5186. * @returns {VarNode}
  5187. */
  5188. const temp = ( node ) => { // @deprecated, r170
  5189. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  5190. return createVar( node );
  5191. };
  5192. addMethodChaining( 'temp', temp );
  5193. /**
  5194. * Class for representing shader varyings as nodes. Varyings are create from
  5195. * existing nodes like the following:
  5196. *
  5197. * ```js
  5198. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5199. * ```
  5200. *
  5201. * @augments Node
  5202. */
  5203. class VaryingNode extends Node {
  5204. static get type() {
  5205. return 'VaryingNode';
  5206. }
  5207. /**
  5208. * Constructs a new varying node.
  5209. *
  5210. * @param {Node} node - The node for which a varying should be created.
  5211. * @param {?string} name - The name of the varying in the shader.
  5212. */
  5213. constructor( node, name = null ) {
  5214. super();
  5215. /**
  5216. * The node for which a varying should be created.
  5217. *
  5218. * @type {Node}
  5219. */
  5220. this.node = node;
  5221. /**
  5222. * The name of the varying in the shader. If no name is defined,
  5223. * the node system auto-generates one.
  5224. *
  5225. * @type {?string}
  5226. * @default null
  5227. */
  5228. this.name = name;
  5229. /**
  5230. * This flag can be used for type testing.
  5231. *
  5232. * @type {boolean}
  5233. * @readonly
  5234. * @default true
  5235. */
  5236. this.isVaryingNode = true;
  5237. /**
  5238. * The interpolation type of the varying data.
  5239. *
  5240. * @type {?string}
  5241. * @default null
  5242. */
  5243. this.interpolationType = null;
  5244. /**
  5245. * The interpolation sampling type of varying data.
  5246. *
  5247. * @type {?string}
  5248. * @default null
  5249. */
  5250. this.interpolationSampling = null;
  5251. }
  5252. /**
  5253. * The method is overwritten so it always returns `true`.
  5254. *
  5255. * @param {NodeBuilder} builder - The current node builder.
  5256. * @return {boolean} Whether this node is global or not.
  5257. */
  5258. isGlobal( /*builder*/ ) {
  5259. return true;
  5260. }
  5261. /**
  5262. * Defines the interpolation type of the varying.
  5263. *
  5264. * @param {string} type - The interpolation type.
  5265. * @param {?string} sampling - The interpolation sampling type
  5266. * @return {VaryingNode} A reference to this node.
  5267. */
  5268. setInterpolation( type, sampling = null ) {
  5269. this.interpolationType = type;
  5270. this.interpolationSampling = sampling;
  5271. return this;
  5272. }
  5273. getHash( builder ) {
  5274. return this.name || super.getHash( builder );
  5275. }
  5276. getNodeType( builder ) {
  5277. // VaryingNode is auto type
  5278. return this.node.getNodeType( builder );
  5279. }
  5280. /**
  5281. * This method performs the setup of a varying node with the current node builder.
  5282. *
  5283. * @param {NodeBuilder} builder - The current node builder.
  5284. * @return {NodeVarying} The node varying from the node builder.
  5285. */
  5286. setupVarying( builder ) {
  5287. const properties = builder.getNodeProperties( this );
  5288. let varying = properties.varying;
  5289. if ( varying === undefined ) {
  5290. const name = this.name;
  5291. const type = this.getNodeType( builder );
  5292. const interpolationType = this.interpolationType;
  5293. const interpolationSampling = this.interpolationSampling;
  5294. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5295. properties.node = this.node;
  5296. }
  5297. // this property can be used to check if the varying can be optimized for a variable
  5298. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5299. return varying;
  5300. }
  5301. setup( builder ) {
  5302. this.setupVarying( builder );
  5303. }
  5304. analyze( builder ) {
  5305. this.setupVarying( builder );
  5306. return this.node.analyze( builder );
  5307. }
  5308. generate( builder ) {
  5309. const properties = builder.getNodeProperties( this );
  5310. const varying = this.setupVarying( builder );
  5311. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  5312. if ( properties.propertyName === undefined || needsReassign ) {
  5313. const type = this.getNodeType( builder );
  5314. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5315. // force node run in vertex stage
  5316. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  5317. properties.propertyName = propertyName;
  5318. if ( needsReassign ) {
  5319. // once reassign varying in fragment stage
  5320. properties.reassignPosition = false;
  5321. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  5322. properties.reassignPosition = true;
  5323. }
  5324. }
  5325. return builder.getPropertyName( varying );
  5326. }
  5327. }
  5328. /**
  5329. * TSL function for creating a varying node.
  5330. *
  5331. * @tsl
  5332. * @function
  5333. * @param {Node} node - The node for which a varying should be created.
  5334. * @param {?string} name - The name of the varying in the shader.
  5335. * @returns {VaryingNode}
  5336. */
  5337. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5338. /**
  5339. * Computes a node in the vertex stage.
  5340. *
  5341. * @tsl
  5342. * @function
  5343. * @param {Node} node - The node which should be executed in the vertex stage.
  5344. * @returns {VaryingNode}
  5345. */
  5346. const vertexStage = ( node ) => varying( node );
  5347. addMethodChaining( 'toVarying', varying );
  5348. addMethodChaining( 'toVertexStage', vertexStage );
  5349. // Deprecated
  5350. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5351. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5352. return varying( ...params );
  5353. } );
  5354. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5355. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5356. return varying( ...params );
  5357. } );
  5358. /**
  5359. * Converts the given color value from sRGB to linear-sRGB color space.
  5360. *
  5361. * @tsl
  5362. * @function
  5363. * @param {Node<vec3>} color - The sRGB color.
  5364. * @return {Node<vec3>} The linear-sRGB color.
  5365. */
  5366. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5367. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5368. const b = color.mul( 0.0773993808 );
  5369. const factor = color.lessThanEqual( 0.04045 );
  5370. const rgbResult = mix( a, b, factor );
  5371. return rgbResult;
  5372. } ).setLayout( {
  5373. name: 'sRGBTransferEOTF',
  5374. type: 'vec3',
  5375. inputs: [
  5376. { name: 'color', type: 'vec3' }
  5377. ]
  5378. } );
  5379. /**
  5380. * Converts the given color value from linear-sRGB to sRGB color space.
  5381. *
  5382. * @tsl
  5383. * @function
  5384. * @param {Node<vec3>} color - The linear-sRGB color.
  5385. * @return {Node<vec3>} The sRGB color.
  5386. */
  5387. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5388. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5389. const b = color.mul( 12.92 );
  5390. const factor = color.lessThanEqual( 0.0031308 );
  5391. const rgbResult = mix( a, b, factor );
  5392. return rgbResult;
  5393. } ).setLayout( {
  5394. name: 'sRGBTransferOETF',
  5395. type: 'vec3',
  5396. inputs: [
  5397. { name: 'color', type: 'vec3' }
  5398. ]
  5399. } );
  5400. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5401. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5402. /**
  5403. * This node represents a color space conversion. Meaning it converts
  5404. * a color value from a source to a target color space.
  5405. *
  5406. * @augments TempNode
  5407. */
  5408. class ColorSpaceNode extends TempNode {
  5409. static get type() {
  5410. return 'ColorSpaceNode';
  5411. }
  5412. /**
  5413. * Constructs a new color space node.
  5414. *
  5415. * @param {Node} colorNode - Represents the color to convert.
  5416. * @param {string} source - The source color space.
  5417. * @param {string} target - The target color space.
  5418. */
  5419. constructor( colorNode, source, target ) {
  5420. super( 'vec4' );
  5421. /**
  5422. * Represents the color to convert.
  5423. *
  5424. * @type {Node}
  5425. */
  5426. this.colorNode = colorNode;
  5427. /**
  5428. * The source color space.
  5429. *
  5430. * @type {string}
  5431. */
  5432. this.source = source;
  5433. /**
  5434. * The target color space.
  5435. *
  5436. * @type {string}
  5437. */
  5438. this.target = target;
  5439. }
  5440. /**
  5441. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5442. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5443. * color management and renderer.
  5444. *
  5445. * @param {NodeBuilder} builder - The current node builder.
  5446. * @param {string} colorSpace - The color space to resolve.
  5447. * @return {string} The resolved color space.
  5448. */
  5449. resolveColorSpace( builder, colorSpace ) {
  5450. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5451. return ColorManagement.workingColorSpace;
  5452. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5453. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5454. }
  5455. return colorSpace;
  5456. }
  5457. setup( builder ) {
  5458. const { colorNode } = this;
  5459. const source = this.resolveColorSpace( builder, this.source );
  5460. const target = this.resolveColorSpace( builder, this.target );
  5461. let outputNode = colorNode;
  5462. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5463. return outputNode;
  5464. }
  5465. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5466. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5467. }
  5468. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5469. outputNode = vec4(
  5470. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5471. outputNode.a
  5472. );
  5473. }
  5474. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5475. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5476. }
  5477. return outputNode;
  5478. }
  5479. }
  5480. /**
  5481. * TSL function for converting a given color node to the current output color space.
  5482. *
  5483. * @tsl
  5484. * @function
  5485. * @param {Node} node - Represents the node to convert.
  5486. * @returns {ColorSpaceNode}
  5487. */
  5488. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  5489. /**
  5490. * TSL function for converting a given color node to the current working color space.
  5491. *
  5492. * @tsl
  5493. * @function
  5494. * @param {Node} node - Represents the node to convert.
  5495. * @returns {ColorSpaceNode}
  5496. */
  5497. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  5498. /**
  5499. * TSL function for converting a given color node from the current working color space to the given color space.
  5500. *
  5501. * @tsl
  5502. * @function
  5503. * @param {Node} node - Represents the node to convert.
  5504. * @param {string} colorSpace - The target color space.
  5505. * @returns {ColorSpaceNode}
  5506. */
  5507. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  5508. /**
  5509. * TSL function for converting a given color node from the given color space to the current working color space.
  5510. *
  5511. * @tsl
  5512. * @function
  5513. * @param {Node} node - Represents the node to convert.
  5514. * @param {string} colorSpace - The source color space.
  5515. * @returns {ColorSpaceNode}
  5516. */
  5517. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  5518. /**
  5519. * TSL function for converting a given color node from one color space to another one.
  5520. *
  5521. * @tsl
  5522. * @function
  5523. * @param {Node} node - Represents the node to convert.
  5524. * @param {string} sourceColorSpace - The source color space.
  5525. * @param {string} targetColorSpace - The target color space.
  5526. * @returns {ColorSpaceNode}
  5527. */
  5528. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5529. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  5530. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  5531. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5532. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5533. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5534. /**
  5535. * This class is only relevant if the referenced property is array-like.
  5536. * In this case, `ReferenceElementNode` allows to refer to a specific
  5537. * element inside the data structure via an index.
  5538. *
  5539. * @augments ArrayElementNode
  5540. */
  5541. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5542. static get type() {
  5543. return 'ReferenceElementNode';
  5544. }
  5545. /**
  5546. * Constructs a new reference element node.
  5547. *
  5548. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5549. * @param {Node} indexNode - The index node that defines the element access.
  5550. */
  5551. constructor( referenceNode, indexNode ) {
  5552. super( referenceNode, indexNode );
  5553. /**
  5554. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5555. * property references to the current node.
  5556. *
  5557. * @type {?ReferenceBaseNode}
  5558. * @default null
  5559. */
  5560. this.referenceNode = referenceNode;
  5561. /**
  5562. * This flag can be used for type testing.
  5563. *
  5564. * @type {boolean}
  5565. * @readonly
  5566. * @default true
  5567. */
  5568. this.isReferenceElementNode = true;
  5569. }
  5570. /**
  5571. * This method is overwritten since the node type is inferred from
  5572. * the uniform type of the reference node.
  5573. *
  5574. * @return {string} The node type.
  5575. */
  5576. getNodeType() {
  5577. return this.referenceNode.uniformType;
  5578. }
  5579. generate( builder ) {
  5580. const snippet = super.generate( builder );
  5581. const arrayType = this.referenceNode.getNodeType();
  5582. const elementType = this.getNodeType();
  5583. return builder.format( snippet, arrayType, elementType );
  5584. }
  5585. };
  5586. /**
  5587. * Base class for nodes which establishes a reference to a property of another object.
  5588. * In this way, the value of the node is automatically linked to the value of
  5589. * referenced object. Reference nodes internally represent the linked value
  5590. * as a uniform.
  5591. *
  5592. * @augments Node
  5593. */
  5594. class ReferenceBaseNode extends Node {
  5595. static get type() {
  5596. return 'ReferenceBaseNode';
  5597. }
  5598. /**
  5599. * Constructs a new reference base node.
  5600. *
  5601. * @param {string} property - The name of the property the node refers to.
  5602. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5603. * @param {?Object} [object=null] - The object the property belongs to.
  5604. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5605. */
  5606. constructor( property, uniformType, object = null, count = null ) {
  5607. super();
  5608. /**
  5609. * The name of the property the node refers to.
  5610. *
  5611. * @type {string}
  5612. */
  5613. this.property = property;
  5614. /**
  5615. * The uniform type that should be used to represent the property value.
  5616. *
  5617. * @type {string}
  5618. */
  5619. this.uniformType = uniformType;
  5620. /**
  5621. * The object the property belongs to.
  5622. *
  5623. * @type {?Object}
  5624. * @default null
  5625. */
  5626. this.object = object;
  5627. /**
  5628. * When the linked property is an array, this parameter defines its length.
  5629. *
  5630. * @type {?number}
  5631. * @default null
  5632. */
  5633. this.count = count;
  5634. /**
  5635. * The property name might have dots so nested properties can be referred.
  5636. * The hierarchy of the names is stored inside this array.
  5637. *
  5638. * @type {Array<string>}
  5639. */
  5640. this.properties = property.split( '.' );
  5641. /**
  5642. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5643. * since the final reference might be updated from calling code.
  5644. *
  5645. * @type {?Object}
  5646. * @default null
  5647. */
  5648. this.reference = object;
  5649. /**
  5650. * The uniform node that holds the value of the reference node.
  5651. *
  5652. * @type {UniformNode}
  5653. * @default null
  5654. */
  5655. this.node = null;
  5656. /**
  5657. * The uniform group of the internal uniform.
  5658. *
  5659. * @type {UniformGroupNode}
  5660. * @default null
  5661. */
  5662. this.group = null;
  5663. /**
  5664. * Overwritten since reference nodes are updated per object.
  5665. *
  5666. * @type {string}
  5667. * @default 'object'
  5668. */
  5669. this.updateType = NodeUpdateType.OBJECT;
  5670. }
  5671. /**
  5672. * Sets the uniform group for this reference node.
  5673. *
  5674. * @param {UniformGroupNode} group - The uniform group to set.
  5675. * @return {ReferenceBaseNode} A reference to this node.
  5676. */
  5677. setGroup( group ) {
  5678. this.group = group;
  5679. return this;
  5680. }
  5681. /**
  5682. * When the referred property is array-like, this method can be used
  5683. * to access elements via an index node.
  5684. *
  5685. * @param {IndexNode} indexNode - indexNode.
  5686. * @return {ReferenceElementNode} A reference to an element.
  5687. */
  5688. element( indexNode ) {
  5689. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5690. }
  5691. /**
  5692. * Sets the node type which automatically defines the internal
  5693. * uniform type.
  5694. *
  5695. * @param {string} uniformType - The type to set.
  5696. */
  5697. setNodeType( uniformType ) {
  5698. const node = uniform( null, uniformType ).getSelf();
  5699. if ( this.group !== null ) {
  5700. node.setGroup( this.group );
  5701. }
  5702. this.node = node;
  5703. }
  5704. /**
  5705. * This method is overwritten since the node type is inferred from
  5706. * the type of the reference node.
  5707. *
  5708. * @param {NodeBuilder} builder - The current node builder.
  5709. * @return {string} The node type.
  5710. */
  5711. getNodeType( builder ) {
  5712. if ( this.node === null ) {
  5713. this.updateReference( builder );
  5714. this.updateValue();
  5715. }
  5716. return this.node.getNodeType( builder );
  5717. }
  5718. /**
  5719. * Returns the property value from the given referred object.
  5720. *
  5721. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5722. * @return {any} The value.
  5723. */
  5724. getValueFromReference( object = this.reference ) {
  5725. const { properties } = this;
  5726. let value = object[ properties[ 0 ] ];
  5727. for ( let i = 1; i < properties.length; i ++ ) {
  5728. value = value[ properties[ i ] ];
  5729. }
  5730. return value;
  5731. }
  5732. /**
  5733. * Allows to update the reference based on the given state. The state is only
  5734. * evaluated {@link ReferenceBaseNode#object} is not set.
  5735. *
  5736. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5737. * @return {Object} The updated reference.
  5738. */
  5739. updateReference( state ) {
  5740. this.reference = this.object !== null ? this.object : state.object;
  5741. return this.reference;
  5742. }
  5743. /**
  5744. * The output of the reference node is the internal uniform node.
  5745. *
  5746. * @return {UniformNode} The output node.
  5747. */
  5748. setup() {
  5749. this.updateValue();
  5750. return this.node;
  5751. }
  5752. /**
  5753. * Overwritten to update the internal uniform value.
  5754. *
  5755. * @param {NodeFrame} frame - A reference to the current node frame.
  5756. */
  5757. update( /*frame*/ ) {
  5758. this.updateValue();
  5759. }
  5760. /**
  5761. * Retrieves the value from the referred object property and uses it
  5762. * to updated the internal uniform.
  5763. */
  5764. updateValue() {
  5765. if ( this.node === null ) this.setNodeType( this.uniformType );
  5766. const value = this.getValueFromReference();
  5767. if ( Array.isArray( value ) ) {
  5768. this.node.array = value;
  5769. } else {
  5770. this.node.value = value;
  5771. }
  5772. }
  5773. }
  5774. /**
  5775. * TSL function for creating a reference base node.
  5776. *
  5777. * @tsl
  5778. * @function
  5779. * @param {string} name - The name of the property the node refers to.
  5780. * @param {string} type - The uniform type that should be used to represent the property value.
  5781. * @param {Object} object - The object the property belongs to.
  5782. * @returns {ReferenceBaseNode}
  5783. */
  5784. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5785. /**
  5786. * This node is a special type of reference node which is intended
  5787. * for linking renderer properties with node values.
  5788. * ```js
  5789. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5790. * ```
  5791. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5792. * automatically be updated.
  5793. *
  5794. * @augments ReferenceBaseNode
  5795. */
  5796. class RendererReferenceNode extends ReferenceBaseNode {
  5797. static get type() {
  5798. return 'RendererReferenceNode';
  5799. }
  5800. /**
  5801. * Constructs a new renderer reference node.
  5802. *
  5803. * @param {string} property - The name of the property the node refers to.
  5804. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5805. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5806. * the node refers to the renderer of the current state.
  5807. */
  5808. constructor( property, inputType, renderer = null ) {
  5809. super( property, inputType, renderer );
  5810. /**
  5811. * The renderer the property belongs to. When no renderer is set,
  5812. * the node refers to the renderer of the current state.
  5813. *
  5814. * @type {?Renderer}
  5815. * @default null
  5816. */
  5817. this.renderer = renderer;
  5818. this.setGroup( renderGroup );
  5819. }
  5820. /**
  5821. * Updates the reference based on the given state. The state is only evaluated
  5822. * {@link RendererReferenceNode#renderer} is not set.
  5823. *
  5824. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5825. * @return {Object} The updated reference.
  5826. */
  5827. updateReference( state ) {
  5828. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5829. return this.reference;
  5830. }
  5831. }
  5832. /**
  5833. * TSL function for creating a renderer reference node.
  5834. *
  5835. * @tsl
  5836. * @function
  5837. * @param {string} name - The name of the property the node refers to.
  5838. * @param {string} type - The uniform type that should be used to represent the property value.
  5839. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5840. * the node refers to the renderer of the current state.
  5841. * @returns {RendererReferenceNode}
  5842. */
  5843. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5844. /**
  5845. * This node represents a tone mapping operation.
  5846. *
  5847. * @augments TempNode
  5848. */
  5849. class ToneMappingNode extends TempNode {
  5850. static get type() {
  5851. return 'ToneMappingNode';
  5852. }
  5853. /**
  5854. * Constructs a new tone mapping node.
  5855. *
  5856. * @param {number} toneMapping - The tone mapping type.
  5857. * @param {Node} exposureNode - The tone mapping exposure.
  5858. * @param {Node} [colorNode=null] - The color node to process.
  5859. */
  5860. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5861. super( 'vec3' );
  5862. /**
  5863. * The tone mapping type.
  5864. *
  5865. * @type {number}
  5866. */
  5867. this.toneMapping = toneMapping;
  5868. /**
  5869. * The tone mapping exposure.
  5870. *
  5871. * @type {Node}
  5872. * @default null
  5873. */
  5874. this.exposureNode = exposureNode;
  5875. /**
  5876. * Represents the color to process.
  5877. *
  5878. * @type {?Node}
  5879. * @default null
  5880. */
  5881. this.colorNode = colorNode;
  5882. }
  5883. /**
  5884. * Overwrites the default `customCacheKey()` implementation by including the tone
  5885. * mapping type into the cache key.
  5886. *
  5887. * @return {number} The hash.
  5888. */
  5889. customCacheKey() {
  5890. return hash$1( this.toneMapping );
  5891. }
  5892. setup( builder ) {
  5893. const colorNode = this.colorNode || builder.context.color;
  5894. const toneMapping = this.toneMapping;
  5895. if ( toneMapping === NoToneMapping ) return colorNode;
  5896. let outputNode = null;
  5897. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5898. if ( toneMappingFn !== null ) {
  5899. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5900. } else {
  5901. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5902. outputNode = colorNode;
  5903. }
  5904. return outputNode;
  5905. }
  5906. }
  5907. /**
  5908. * TSL function for creating a tone mapping node.
  5909. *
  5910. * @tsl
  5911. * @function
  5912. * @param {number} mapping - The tone mapping type.
  5913. * @param {Node<float> | number} exposure - The tone mapping exposure.
  5914. * @param {Node<vec3> | Color} color - The color node to process.
  5915. * @returns {ToneMappingNode<vec3>}
  5916. */
  5917. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5918. /**
  5919. * TSL object that represents the global tone mapping exposure of the renderer.
  5920. *
  5921. * @tsl
  5922. * @type {RendererReferenceNode<vec3>}
  5923. */
  5924. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5925. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5926. /**
  5927. * In earlier `three.js` versions it was only possible to define attribute data
  5928. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5929. * on the node level.
  5930. * ```js
  5931. * const geometry = new THREE.PlaneGeometry();
  5932. * const positionAttribute = geometry.getAttribute( 'position' );
  5933. *
  5934. * const colors = [];
  5935. * for ( let i = 0; i < position.count; i ++ ) {
  5936. * colors.push( 1, 0, 0 );
  5937. * }
  5938. *
  5939. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5940. * ```
  5941. * This new approach is especially interesting when geometry data are generated via
  5942. * compute shaders. The below line converts a storage buffer into an attribute node.
  5943. * ```js
  5944. * material.positionNode = positionBuffer.toAttribute();
  5945. * ```
  5946. * @augments InputNode
  5947. */
  5948. class BufferAttributeNode extends InputNode {
  5949. static get type() {
  5950. return 'BufferAttributeNode';
  5951. }
  5952. /**
  5953. * Constructs a new buffer attribute node.
  5954. *
  5955. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5956. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5957. * @param {number} [bufferStride=0] - The buffer stride.
  5958. * @param {number} [bufferOffset=0] - The buffer offset.
  5959. */
  5960. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5961. super( value, bufferType );
  5962. /**
  5963. * This flag can be used for type testing.
  5964. *
  5965. * @type {boolean}
  5966. * @readonly
  5967. * @default true
  5968. */
  5969. this.isBufferNode = true;
  5970. /**
  5971. * The buffer type (e.g. `'vec3'`).
  5972. *
  5973. * @type {?string}
  5974. * @default null
  5975. */
  5976. this.bufferType = bufferType;
  5977. /**
  5978. * The buffer stride.
  5979. *
  5980. * @type {number}
  5981. * @default 0
  5982. */
  5983. this.bufferStride = bufferStride;
  5984. /**
  5985. * The buffer offset.
  5986. *
  5987. * @type {number}
  5988. * @default 0
  5989. */
  5990. this.bufferOffset = bufferOffset;
  5991. /**
  5992. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5993. * if you are planning to update the attribute data per frame.
  5994. *
  5995. * @type {number}
  5996. * @default StaticDrawUsage
  5997. */
  5998. this.usage = StaticDrawUsage;
  5999. /**
  6000. * Whether the attribute is instanced or not.
  6001. *
  6002. * @type {boolean}
  6003. * @default false
  6004. */
  6005. this.instanced = false;
  6006. /**
  6007. * A reference to the buffer attribute.
  6008. *
  6009. * @type {?BufferAttribute}
  6010. * @default null
  6011. */
  6012. this.attribute = null;
  6013. /**
  6014. * `BufferAttributeNode` sets this property to `true` by default.
  6015. *
  6016. * @type {boolean}
  6017. * @default true
  6018. */
  6019. this.global = true;
  6020. if ( value && value.isBufferAttribute === true ) {
  6021. this.attribute = value;
  6022. this.usage = value.usage;
  6023. this.instanced = value.isInstancedBufferAttribute;
  6024. }
  6025. }
  6026. /**
  6027. * This method is overwritten since the attribute data might be shared
  6028. * and thus the hash should be shared as well.
  6029. *
  6030. * @param {NodeBuilder} builder - The current node builder.
  6031. * @return {string} The hash.
  6032. */
  6033. getHash( builder ) {
  6034. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6035. let bufferData = builder.globalCache.getData( this.value );
  6036. if ( bufferData === undefined ) {
  6037. bufferData = {
  6038. node: this
  6039. };
  6040. builder.globalCache.setData( this.value, bufferData );
  6041. }
  6042. return bufferData.node.uuid;
  6043. }
  6044. return this.uuid;
  6045. }
  6046. /**
  6047. * This method is overwritten since the node type is inferred from
  6048. * the buffer attribute.
  6049. *
  6050. * @param {NodeBuilder} builder - The current node builder.
  6051. * @return {string} The node type.
  6052. */
  6053. getNodeType( builder ) {
  6054. if ( this.bufferType === null ) {
  6055. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6056. }
  6057. return this.bufferType;
  6058. }
  6059. /**
  6060. * Depending on which value was passed to the node, `setup()` behaves
  6061. * differently. If no instance of `BufferAttribute` was passed, the method
  6062. * creates an internal attribute and configures it respectively.
  6063. *
  6064. * @param {NodeBuilder} builder - The current node builder.
  6065. */
  6066. setup( builder ) {
  6067. if ( this.attribute !== null ) return;
  6068. const type = this.getNodeType( builder );
  6069. const array = this.value;
  6070. const itemSize = builder.getTypeLength( type );
  6071. const stride = this.bufferStride || itemSize;
  6072. const offset = this.bufferOffset;
  6073. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6074. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6075. buffer.setUsage( this.usage );
  6076. this.attribute = bufferAttribute;
  6077. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6078. }
  6079. /**
  6080. * Generates the code snippet of the buffer attribute node.
  6081. *
  6082. * @param {NodeBuilder} builder - The current node builder.
  6083. * @return {string} The generated code snippet.
  6084. */
  6085. generate( builder ) {
  6086. const nodeType = this.getNodeType( builder );
  6087. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6088. const propertyName = builder.getPropertyName( nodeAttribute );
  6089. let output = null;
  6090. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6091. this.name = propertyName;
  6092. output = propertyName;
  6093. } else {
  6094. const nodeVarying = varying( this );
  6095. output = nodeVarying.build( builder, nodeType );
  6096. }
  6097. return output;
  6098. }
  6099. /**
  6100. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6101. *
  6102. * @param {NodeBuilder} builder - The current node builder.
  6103. * @return {string} The input type.
  6104. */
  6105. getInputType( /*builder*/ ) {
  6106. return 'bufferAttribute';
  6107. }
  6108. /**
  6109. * Sets the `usage` property to the given value.
  6110. *
  6111. * @param {number} value - The usage to set.
  6112. * @return {BufferAttributeNode} A reference to this node.
  6113. */
  6114. setUsage( value ) {
  6115. this.usage = value;
  6116. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6117. this.attribute.usage = value;
  6118. }
  6119. return this;
  6120. }
  6121. /**
  6122. * Sets the `instanced` property to the given value.
  6123. *
  6124. * @param {boolean} value - The value to set.
  6125. * @return {BufferAttributeNode} A reference to this node.
  6126. */
  6127. setInstanced( value ) {
  6128. this.instanced = value;
  6129. return this;
  6130. }
  6131. }
  6132. /**
  6133. * TSL function for creating a buffer attribute node.
  6134. *
  6135. * @tsl
  6136. * @function
  6137. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6138. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6139. * @param {number} [stride=0] - The buffer stride.
  6140. * @param {number} [offset=0] - The buffer offset.
  6141. * @returns {BufferAttributeNode}
  6142. */
  6143. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6144. /**
  6145. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6146. * Use this function if attribute data are updated per frame.
  6147. *
  6148. * @tsl
  6149. * @function
  6150. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6151. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6152. * @param {number} [stride=0] - The buffer stride.
  6153. * @param {number} [offset=0] - The buffer offset.
  6154. * @returns {BufferAttributeNode}
  6155. */
  6156. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6157. /**
  6158. * TSL function for creating a buffer attribute node but with enabled instancing
  6159. *
  6160. * @tsl
  6161. * @function
  6162. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6163. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6164. * @param {number} [stride=0] - The buffer stride.
  6165. * @param {number} [offset=0] - The buffer offset.
  6166. * @returns {BufferAttributeNode}
  6167. */
  6168. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6169. /**
  6170. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6171. *
  6172. * @tsl
  6173. * @function
  6174. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6175. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6176. * @param {number} [stride=0] - The buffer stride.
  6177. * @param {number} [offset=0] - The buffer offset.
  6178. * @returns {BufferAttributeNode}
  6179. */
  6180. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6181. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6182. /**
  6183. * TODO
  6184. *
  6185. * @augments Node
  6186. */
  6187. class ComputeNode extends Node {
  6188. static get type() {
  6189. return 'ComputeNode';
  6190. }
  6191. /**
  6192. * Constructs a new compute node.
  6193. *
  6194. * @param {Node} computeNode - TODO
  6195. * @param {number} count - TODO.
  6196. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6197. */
  6198. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  6199. super( 'void' );
  6200. /**
  6201. * This flag can be used for type testing.
  6202. *
  6203. * @type {boolean}
  6204. * @readonly
  6205. * @default true
  6206. */
  6207. this.isComputeNode = true;
  6208. /**
  6209. * TODO
  6210. *
  6211. * @type {Node}
  6212. */
  6213. this.computeNode = computeNode;
  6214. /**
  6215. * TODO
  6216. *
  6217. * @type {number}
  6218. */
  6219. this.count = count;
  6220. /**
  6221. * TODO
  6222. *
  6223. * @type {Array<number>}
  6224. * @default [64]
  6225. */
  6226. this.workgroupSize = workgroupSize;
  6227. /**
  6228. * TODO
  6229. *
  6230. * @type {number}
  6231. */
  6232. this.dispatchCount = 0;
  6233. /**
  6234. * TODO
  6235. *
  6236. * @type {number}
  6237. */
  6238. this.version = 1;
  6239. /**
  6240. * The name or label of the uniform.
  6241. *
  6242. * @type {string}
  6243. * @default ''
  6244. */
  6245. this.name = '';
  6246. /**
  6247. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6248. * is executed once per object by default.
  6249. *
  6250. * @type {string}
  6251. * @default 'object'
  6252. */
  6253. this.updateBeforeType = NodeUpdateType.OBJECT;
  6254. /**
  6255. * TODO
  6256. *
  6257. * @type {?Function}
  6258. */
  6259. this.onInitFunction = null;
  6260. this.updateDispatchCount();
  6261. }
  6262. /**
  6263. * Executes the `dispose` event for this node.
  6264. */
  6265. dispose() {
  6266. this.dispatchEvent( { type: 'dispose' } );
  6267. }
  6268. /**
  6269. * Sets the {@link ComputeNode#name} property.
  6270. *
  6271. * @param {string} name - The name of the uniform.
  6272. * @return {ComputeNode} A reference to this node.
  6273. */
  6274. label( name ) {
  6275. this.name = name;
  6276. return this;
  6277. }
  6278. /**
  6279. * TODO
  6280. */
  6281. updateDispatchCount() {
  6282. const { count, workgroupSize } = this;
  6283. let size = workgroupSize[ 0 ];
  6284. for ( let i = 1; i < workgroupSize.length; i ++ )
  6285. size *= workgroupSize[ i ];
  6286. this.dispatchCount = Math.ceil( count / size );
  6287. }
  6288. /**
  6289. * TODO
  6290. *
  6291. * @param {Function} callback - TODO.
  6292. * @return {ComputeNode} A reference to this node.
  6293. */
  6294. onInit( callback ) {
  6295. this.onInitFunction = callback;
  6296. return this;
  6297. }
  6298. /**
  6299. * The method execute the compute for this node.
  6300. *
  6301. * @param {NodeFrame} frame - A reference to the current node frame.
  6302. */
  6303. updateBefore( { renderer } ) {
  6304. renderer.compute( this );
  6305. }
  6306. setup( builder ) {
  6307. const result = this.computeNode.build( builder );
  6308. if ( result ) {
  6309. const properties = builder.getNodeProperties( this );
  6310. properties.outputComputeNode = result.outputNode;
  6311. result.outputNode = null;
  6312. }
  6313. return result;
  6314. }
  6315. generate( builder, output ) {
  6316. const { shaderStage } = builder;
  6317. if ( shaderStage === 'compute' ) {
  6318. const snippet = this.computeNode.build( builder, 'void' );
  6319. if ( snippet !== '' ) {
  6320. builder.addLineFlowCode( snippet, this );
  6321. }
  6322. } else {
  6323. const properties = builder.getNodeProperties( this );
  6324. const outputComputeNode = properties.outputComputeNode;
  6325. if ( outputComputeNode ) {
  6326. return outputComputeNode.build( builder, output );
  6327. }
  6328. }
  6329. }
  6330. }
  6331. /**
  6332. * TSL function for creating a compute node.
  6333. *
  6334. * @tsl
  6335. * @function
  6336. * @param {Node} node - TODO
  6337. * @param {number} count - TODO.
  6338. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6339. * @returns {AtomicFunctionNode}
  6340. */
  6341. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  6342. addMethodChaining( 'compute', compute );
  6343. /**
  6344. * This node can be used as a cache management component for another node.
  6345. * Caching is in general used by default in {@link NodeBuilder} but this node
  6346. * allows the usage of a shared parent cache during the build process.
  6347. *
  6348. * @augments Node
  6349. */
  6350. class CacheNode extends Node {
  6351. static get type() {
  6352. return 'CacheNode';
  6353. }
  6354. /**
  6355. * Constructs a new cache node.
  6356. *
  6357. * @param {Node} node - The node that should be cached.
  6358. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6359. */
  6360. constructor( node, parent = true ) {
  6361. super();
  6362. /**
  6363. * The node that should be cached.
  6364. *
  6365. * @type {Node}
  6366. */
  6367. this.node = node;
  6368. /**
  6369. * Whether this node refers to a shared parent cache or not.
  6370. *
  6371. * @type {boolean}
  6372. * @default true
  6373. */
  6374. this.parent = parent;
  6375. /**
  6376. * This flag can be used for type testing.
  6377. *
  6378. * @type {boolean}
  6379. * @readonly
  6380. * @default true
  6381. */
  6382. this.isCacheNode = true;
  6383. }
  6384. getNodeType( builder ) {
  6385. const previousCache = builder.getCache();
  6386. const cache = builder.getCacheFromNode( this, this.parent );
  6387. builder.setCache( cache );
  6388. const nodeType = this.node.getNodeType( builder );
  6389. builder.setCache( previousCache );
  6390. return nodeType;
  6391. }
  6392. build( builder, ...params ) {
  6393. const previousCache = builder.getCache();
  6394. const cache = builder.getCacheFromNode( this, this.parent );
  6395. builder.setCache( cache );
  6396. const data = this.node.build( builder, ...params );
  6397. builder.setCache( previousCache );
  6398. return data;
  6399. }
  6400. }
  6401. /**
  6402. * TSL function for creating a cache node.
  6403. *
  6404. * @tsl
  6405. * @function
  6406. * @param {Node} node - The node that should be cached.
  6407. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6408. * @returns {CacheNode}
  6409. */
  6410. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6411. addMethodChaining( 'cache', cache );
  6412. /**
  6413. * The class generates the code of a given node but returns another node in the output.
  6414. * This can be used to call a method or node that does not return a value, i.e.
  6415. * type `void` on an input where returning a value is required. Example:
  6416. *
  6417. * ```js
  6418. * material.colorNode = myColor.bypass( runVoidFn() )
  6419. *```
  6420. *
  6421. * @augments Node
  6422. */
  6423. class BypassNode extends Node {
  6424. static get type() {
  6425. return 'BypassNode';
  6426. }
  6427. /**
  6428. * Constructs a new bypass node.
  6429. *
  6430. * @param {Node} outputNode - The output node.
  6431. * @param {Node} callNode - The call node.
  6432. */
  6433. constructor( outputNode, callNode ) {
  6434. super();
  6435. /**
  6436. * This flag can be used for type testing.
  6437. *
  6438. * @type {boolean}
  6439. * @readonly
  6440. * @default true
  6441. */
  6442. this.isBypassNode = true;
  6443. /**
  6444. * The output node.
  6445. *
  6446. * @type {Node}
  6447. */
  6448. this.outputNode = outputNode;
  6449. /**
  6450. * The call node.
  6451. *
  6452. * @type {Node}
  6453. */
  6454. this.callNode = callNode;
  6455. }
  6456. getNodeType( builder ) {
  6457. return this.outputNode.getNodeType( builder );
  6458. }
  6459. generate( builder ) {
  6460. const snippet = this.callNode.build( builder, 'void' );
  6461. if ( snippet !== '' ) {
  6462. builder.addLineFlowCode( snippet, this );
  6463. }
  6464. return this.outputNode.build( builder );
  6465. }
  6466. }
  6467. /**
  6468. * TSL function for creating a bypass node.
  6469. *
  6470. * @tsl
  6471. * @function
  6472. * @param {Node} outputNode - The output node.
  6473. * @param {Node} callNode - The call node.
  6474. * @returns {BypassNode}
  6475. */
  6476. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6477. addMethodChaining( 'bypass', bypass );
  6478. /**
  6479. * This node allows to remap a node value from one range into another. E.g a value of
  6480. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6481. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6482. *
  6483. * @augments Node
  6484. */
  6485. class RemapNode extends Node {
  6486. static get type() {
  6487. return 'RemapNode';
  6488. }
  6489. /**
  6490. * Constructs a new remap node.
  6491. *
  6492. * @param {Node} node - The node that should be remapped.
  6493. * @param {Node} inLowNode - The source or current lower bound of the range.
  6494. * @param {Node} inHighNode - The source or current upper bound of the range.
  6495. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6496. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6497. */
  6498. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6499. super();
  6500. /**
  6501. * The node that should be remapped.
  6502. *
  6503. * @type {Node}
  6504. */
  6505. this.node = node;
  6506. /**
  6507. * The source or current lower bound of the range.
  6508. *
  6509. * @type {Node}
  6510. */
  6511. this.inLowNode = inLowNode;
  6512. /**
  6513. * The source or current upper bound of the range.
  6514. *
  6515. * @type {Node}
  6516. */
  6517. this.inHighNode = inHighNode;
  6518. /**
  6519. * The target lower bound of the range.
  6520. *
  6521. * @type {Node}
  6522. * @default float(0)
  6523. */
  6524. this.outLowNode = outLowNode;
  6525. /**
  6526. * The target upper bound of the range.
  6527. *
  6528. * @type {Node}
  6529. * @default float(1)
  6530. */
  6531. this.outHighNode = outHighNode;
  6532. /**
  6533. * Whether the node value should be clamped before
  6534. * remapping it to the target range.
  6535. *
  6536. * @type {boolean}
  6537. * @default true
  6538. */
  6539. this.doClamp = true;
  6540. }
  6541. setup() {
  6542. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6543. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6544. if ( doClamp === true ) t = t.clamp();
  6545. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6546. }
  6547. }
  6548. /**
  6549. * TSL function for creating a remap node.
  6550. *
  6551. * @tsl
  6552. * @function
  6553. * @param {Node} node - The node that should be remapped.
  6554. * @param {Node} inLowNode - The source or current lower bound of the range.
  6555. * @param {Node} inHighNode - The source or current upper bound of the range.
  6556. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6557. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6558. * @returns {RemapNode}
  6559. */
  6560. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  6561. /**
  6562. * TSL function for creating a remap node, but with enabled clamping.
  6563. *
  6564. * @tsl
  6565. * @function
  6566. * @param {Node} node - The node that should be remapped.
  6567. * @param {Node} inLowNode - The source or current lower bound of the range.
  6568. * @param {Node} inHighNode - The source or current upper bound of the range.
  6569. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6570. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6571. * @returns {RemapNode}
  6572. */
  6573. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  6574. addMethodChaining( 'remap', remap );
  6575. addMethodChaining( 'remapClamp', remapClamp );
  6576. /**
  6577. * This class can be used to implement basic expressions in shader code.
  6578. * Basic examples for that are `return`, `continue` or `discard` statements.
  6579. *
  6580. * @augments Node
  6581. */
  6582. class ExpressionNode extends Node {
  6583. static get type() {
  6584. return 'ExpressionNode';
  6585. }
  6586. /**
  6587. * Constructs a new expression node.
  6588. *
  6589. * @param {string} [snippet=''] - The native code snippet.
  6590. * @param {string} [nodeType='void'] - The node type.
  6591. */
  6592. constructor( snippet = '', nodeType = 'void' ) {
  6593. super( nodeType );
  6594. /**
  6595. * The native code snippet.
  6596. *
  6597. * @type {string}
  6598. * @default ''
  6599. */
  6600. this.snippet = snippet;
  6601. }
  6602. generate( builder, output ) {
  6603. const type = this.getNodeType( builder );
  6604. const snippet = this.snippet;
  6605. if ( type === 'void' ) {
  6606. builder.addLineFlowCode( snippet, this );
  6607. } else {
  6608. return builder.format( snippet, type, output );
  6609. }
  6610. }
  6611. }
  6612. /**
  6613. * TSL function for creating an expression node.
  6614. *
  6615. * @tsl
  6616. * @function
  6617. * @param {string} [snippet] - The native code snippet.
  6618. * @param {?string} [nodeType='void'] - The node type.
  6619. * @returns {ExpressionNode}
  6620. */
  6621. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  6622. /**
  6623. * Represents a `discard` shader operation in TSL.
  6624. *
  6625. * @tsl
  6626. * @function
  6627. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6628. * @return {Node} The `discard` expression.
  6629. */
  6630. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  6631. /**
  6632. * Represents a `return` shader operation in TSL.
  6633. *
  6634. * @tsl
  6635. * @function
  6636. * @return {ExpressionNode} The `return` expression.
  6637. */
  6638. const Return = () => expression( 'return' ).toStack();
  6639. addMethodChaining( 'discard', Discard );
  6640. /**
  6641. * Normally, tone mapping and color conversion happens automatically
  6642. * before outputting pixel too the default (screen) framebuffer. In certain
  6643. * post processing setups this happens to late because certain effects
  6644. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6645. * to apply tone mapping and color space conversion at an arbitrary point
  6646. * in the effect chain.
  6647. *
  6648. * When applying tone mapping and color space conversion manually with this node,
  6649. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6650. *
  6651. * ```js
  6652. * const postProcessing = new PostProcessing( renderer );
  6653. * postProcessing.outputColorTransform = false;
  6654. *
  6655. * const scenePass = pass( scene, camera );
  6656. * const outputPass = renderOutput( scenePass );
  6657. *
  6658. * postProcessing.outputNode = outputPass;
  6659. * ```
  6660. *
  6661. * @augments TempNode
  6662. */
  6663. class RenderOutputNode extends TempNode {
  6664. static get type() {
  6665. return 'RenderOutputNode';
  6666. }
  6667. /**
  6668. * Constructs a new render output node.
  6669. *
  6670. * @param {Node} colorNode - The color node to process.
  6671. * @param {?number} toneMapping - The tone mapping type.
  6672. * @param {?string} outputColorSpace - The output color space.
  6673. */
  6674. constructor( colorNode, toneMapping, outputColorSpace ) {
  6675. super( 'vec4' );
  6676. /**
  6677. * The color node to process.
  6678. *
  6679. * @type {Node}
  6680. */
  6681. this.colorNode = colorNode;
  6682. /**
  6683. * The tone mapping type.
  6684. *
  6685. * @type {?number}
  6686. */
  6687. this.toneMapping = toneMapping;
  6688. /**
  6689. * The output color space.
  6690. *
  6691. * @type {?string}
  6692. */
  6693. this.outputColorSpace = outputColorSpace;
  6694. /**
  6695. * This flag can be used for type testing.
  6696. *
  6697. * @type {boolean}
  6698. * @readonly
  6699. * @default true
  6700. */
  6701. this.isRenderOutputNode = true;
  6702. }
  6703. setup( { context } ) {
  6704. let outputNode = this.colorNode || context.color;
  6705. // tone mapping
  6706. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6707. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6708. if ( toneMapping !== NoToneMapping ) {
  6709. outputNode = outputNode.toneMapping( toneMapping );
  6710. }
  6711. // working to output color space
  6712. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6713. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6714. }
  6715. return outputNode;
  6716. }
  6717. }
  6718. /**
  6719. * TSL function for creating a posterize node.
  6720. *
  6721. * @tsl
  6722. * @function
  6723. * @param {Node} color - The color node to process.
  6724. * @param {?number} [toneMapping=null] - The tone mapping type.
  6725. * @param {?string} [outputColorSpace=null] - The output color space.
  6726. * @returns {RenderOutputNode}
  6727. */
  6728. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6729. addMethodChaining( 'renderOutput', renderOutput );
  6730. class DebugNode extends TempNode {
  6731. static get type() {
  6732. return 'DebugNode';
  6733. }
  6734. constructor( node, callback = null ) {
  6735. super();
  6736. this.node = node;
  6737. this.callback = callback;
  6738. }
  6739. getNodeType( builder ) {
  6740. return this.node.getNodeType( builder );
  6741. }
  6742. setup( builder ) {
  6743. return this.node.build( builder );
  6744. }
  6745. analyze( builder ) {
  6746. return this.node.build( builder );
  6747. }
  6748. generate( builder ) {
  6749. const callback = this.callback;
  6750. const snippet = this.node.build( builder );
  6751. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  6752. const border = '-'.repeat( title.length );
  6753. let code = '';
  6754. code += '// #' + title + '#\n';
  6755. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  6756. code += '/* ... */ ' + snippet + ' /* ... */\n';
  6757. code += '// #' + border + '#\n';
  6758. if ( callback !== null ) {
  6759. callback( builder, code );
  6760. } else {
  6761. console.log( code );
  6762. }
  6763. return snippet;
  6764. }
  6765. }
  6766. /**
  6767. * TSL function for creating a debug node.
  6768. *
  6769. * @tsl
  6770. * @function
  6771. * @param {Node} node - The node to debug.
  6772. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  6773. * @returns {DebugNode}
  6774. */
  6775. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) );
  6776. addMethodChaining( 'debug', debug );
  6777. // Non-PURE exports list, side-effects are required here.
  6778. // TSL Base Syntax
  6779. function addNodeElement( name/*, nodeElement*/ ) {
  6780. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6781. }
  6782. /**
  6783. * Base class for representing shader attributes as nodes.
  6784. *
  6785. * @augments Node
  6786. */
  6787. class AttributeNode extends Node {
  6788. static get type() {
  6789. return 'AttributeNode';
  6790. }
  6791. /**
  6792. * Constructs a new attribute node.
  6793. *
  6794. * @param {string} attributeName - The name of the attribute.
  6795. * @param {?string} nodeType - The node type.
  6796. */
  6797. constructor( attributeName, nodeType = null ) {
  6798. super( nodeType );
  6799. /**
  6800. * `AttributeNode` sets this property to `true` by default.
  6801. *
  6802. * @type {boolean}
  6803. * @default true
  6804. */
  6805. this.global = true;
  6806. this._attributeName = attributeName;
  6807. }
  6808. getHash( builder ) {
  6809. return this.getAttributeName( builder );
  6810. }
  6811. getNodeType( builder ) {
  6812. let nodeType = this.nodeType;
  6813. if ( nodeType === null ) {
  6814. const attributeName = this.getAttributeName( builder );
  6815. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6816. const attribute = builder.geometry.getAttribute( attributeName );
  6817. nodeType = builder.getTypeFromAttribute( attribute );
  6818. } else {
  6819. nodeType = 'float';
  6820. }
  6821. }
  6822. return nodeType;
  6823. }
  6824. /**
  6825. * Sets the attribute name to the given value. The method can be
  6826. * overwritten in derived classes if the final name must be computed
  6827. * analytically.
  6828. *
  6829. * @param {string} attributeName - The name of the attribute.
  6830. * @return {AttributeNode} A reference to this node.
  6831. */
  6832. setAttributeName( attributeName ) {
  6833. this._attributeName = attributeName;
  6834. return this;
  6835. }
  6836. /**
  6837. * Returns the attribute name of this node. The method can be
  6838. * overwritten in derived classes if the final name must be computed
  6839. * analytically.
  6840. *
  6841. * @param {NodeBuilder} builder - The current node builder.
  6842. * @return {string} The attribute name.
  6843. */
  6844. getAttributeName( /*builder*/ ) {
  6845. return this._attributeName;
  6846. }
  6847. generate( builder ) {
  6848. const attributeName = this.getAttributeName( builder );
  6849. const nodeType = this.getNodeType( builder );
  6850. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6851. if ( geometryAttribute === true ) {
  6852. const attribute = builder.geometry.getAttribute( attributeName );
  6853. const attributeType = builder.getTypeFromAttribute( attribute );
  6854. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6855. if ( builder.shaderStage === 'vertex' ) {
  6856. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6857. } else {
  6858. const nodeVarying = varying( this );
  6859. return nodeVarying.build( builder, nodeType );
  6860. }
  6861. } else {
  6862. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6863. return builder.generateConst( nodeType );
  6864. }
  6865. }
  6866. serialize( data ) {
  6867. super.serialize( data );
  6868. data.global = this.global;
  6869. data._attributeName = this._attributeName;
  6870. }
  6871. deserialize( data ) {
  6872. super.deserialize( data );
  6873. this.global = data.global;
  6874. this._attributeName = data._attributeName;
  6875. }
  6876. }
  6877. /**
  6878. * TSL function for creating an attribute node.
  6879. *
  6880. * @tsl
  6881. * @function
  6882. * @param {string} name - The name of the attribute.
  6883. * @param {?string} [nodeType=null] - The node type.
  6884. * @returns {AttributeNode}
  6885. */
  6886. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  6887. /**
  6888. * TSL function for creating an uv attribute node with the given index.
  6889. *
  6890. * @tsl
  6891. * @function
  6892. * @param {number} [index=0] - The uv index.
  6893. * @return {AttributeNode<vec2>} The uv attribute node.
  6894. */
  6895. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6896. /**
  6897. * A node that represents the dimensions of a texture. The texture size is
  6898. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6899. * or `textureSize()`.
  6900. *
  6901. * @augments Node
  6902. */
  6903. class TextureSizeNode extends Node {
  6904. static get type() {
  6905. return 'TextureSizeNode';
  6906. }
  6907. /**
  6908. * Constructs a new texture size node.
  6909. *
  6910. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6911. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6912. */
  6913. constructor( textureNode, levelNode = null ) {
  6914. super( 'uvec2' );
  6915. /**
  6916. * This flag can be used for type testing.
  6917. *
  6918. * @type {boolean}
  6919. * @readonly
  6920. * @default true
  6921. */
  6922. this.isTextureSizeNode = true;
  6923. /**
  6924. * A texture node which size should be retrieved.
  6925. *
  6926. * @type {TextureNode}
  6927. */
  6928. this.textureNode = textureNode;
  6929. /**
  6930. * A level node which defines the requested mip.
  6931. *
  6932. * @type {Node<int>}
  6933. * @default null
  6934. */
  6935. this.levelNode = levelNode;
  6936. }
  6937. generate( builder, output ) {
  6938. const textureProperty = this.textureNode.build( builder, 'property' );
  6939. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6940. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6941. }
  6942. }
  6943. /**
  6944. * TSL function for creating a texture size node.
  6945. *
  6946. * @tsl
  6947. * @function
  6948. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6949. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6950. * @returns {TextureSizeNode}
  6951. */
  6952. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  6953. /**
  6954. * A special type of uniform node that computes the
  6955. * maximum mipmap level for a given texture node.
  6956. *
  6957. * ```js
  6958. * const level = maxMipLevel( textureNode );
  6959. * ```
  6960. *
  6961. * @augments UniformNode
  6962. */
  6963. class MaxMipLevelNode extends UniformNode {
  6964. static get type() {
  6965. return 'MaxMipLevelNode';
  6966. }
  6967. /**
  6968. * Constructs a new max mip level node.
  6969. *
  6970. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6971. */
  6972. constructor( textureNode ) {
  6973. super( 0 );
  6974. /**
  6975. * The texture node to compute the max mip level for.
  6976. *
  6977. * @private
  6978. * @type {TextureNode}
  6979. */
  6980. this._textureNode = textureNode;
  6981. /**
  6982. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6983. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6984. *
  6985. * @type {string}
  6986. * @default 'frame'
  6987. */
  6988. this.updateType = NodeUpdateType.FRAME;
  6989. }
  6990. /**
  6991. * The texture node to compute the max mip level for.
  6992. *
  6993. * @readonly
  6994. * @type {TextureNode}
  6995. */
  6996. get textureNode() {
  6997. return this._textureNode;
  6998. }
  6999. /**
  7000. * The texture.
  7001. *
  7002. * @readonly
  7003. * @type {Texture}
  7004. */
  7005. get texture() {
  7006. return this._textureNode.value;
  7007. }
  7008. update() {
  7009. const texture = this.texture;
  7010. const images = texture.images;
  7011. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7012. if ( image && image.width !== undefined ) {
  7013. const { width, height } = image;
  7014. this.value = Math.log2( Math.max( width, height ) );
  7015. }
  7016. }
  7017. }
  7018. /**
  7019. * TSL function for creating a max mip level node.
  7020. *
  7021. * @tsl
  7022. * @function
  7023. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7024. * @returns {MaxMipLevelNode}
  7025. */
  7026. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7027. /**
  7028. * This type of uniform node represents a 2D texture.
  7029. *
  7030. * @augments UniformNode
  7031. */
  7032. class TextureNode extends UniformNode {
  7033. static get type() {
  7034. return 'TextureNode';
  7035. }
  7036. /**
  7037. * Constructs a new texture node.
  7038. *
  7039. * @param {Texture} value - The texture.
  7040. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7041. * @param {?Node<int>} [levelNode=null] - The level node.
  7042. * @param {?Node<float>} [biasNode=null] - The bias node.
  7043. */
  7044. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7045. super( value );
  7046. /**
  7047. * This flag can be used for type testing.
  7048. *
  7049. * @type {boolean}
  7050. * @readonly
  7051. * @default true
  7052. */
  7053. this.isTextureNode = true;
  7054. /**
  7055. * Represents the texture coordinates.
  7056. *
  7057. * @type {?Node<vec2|vec3>}
  7058. * @default null
  7059. */
  7060. this.uvNode = uvNode;
  7061. /**
  7062. * Represents the mip level that should be selected.
  7063. *
  7064. * @type {?Node<int>}
  7065. * @default null
  7066. */
  7067. this.levelNode = levelNode;
  7068. /**
  7069. * Represents the bias to be applied during level-of-detail computation.
  7070. *
  7071. * @type {?Node<float>}
  7072. * @default null
  7073. */
  7074. this.biasNode = biasNode;
  7075. /**
  7076. * Represents a reference value a texture sample is compared to.
  7077. *
  7078. * @type {?Node<float>}
  7079. * @default null
  7080. */
  7081. this.compareNode = null;
  7082. /**
  7083. * When using texture arrays, the depth node defines the layer to select.
  7084. *
  7085. * @type {?Node<int>}
  7086. * @default null
  7087. */
  7088. this.depthNode = null;
  7089. /**
  7090. * When defined, a texture is sampled using explicit gradients.
  7091. *
  7092. * @type {?Array<Node<vec2>>}
  7093. * @default null
  7094. */
  7095. this.gradNode = null;
  7096. /**
  7097. * Whether texture values should be sampled or fetched.
  7098. *
  7099. * @type {boolean}
  7100. * @default true
  7101. */
  7102. this.sampler = true;
  7103. /**
  7104. * Whether the uv transformation matrix should be
  7105. * automatically updated or not. Use `setUpdateMatrix()`
  7106. * if you want to change the value of the property.
  7107. *
  7108. * @type {boolean}
  7109. * @default false
  7110. */
  7111. this.updateMatrix = false;
  7112. /**
  7113. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7114. * sets the value to `frame` when the uv transformation matrix should
  7115. * automatically be updated.
  7116. *
  7117. * @type {string}
  7118. * @default 'none'
  7119. */
  7120. this.updateType = NodeUpdateType.NONE;
  7121. /**
  7122. * The reference node.
  7123. *
  7124. * @type {?Node}
  7125. * @default null
  7126. */
  7127. this.referenceNode = null;
  7128. /**
  7129. * The texture value is stored in a private property.
  7130. *
  7131. * @private
  7132. * @type {Texture}
  7133. */
  7134. this._value = value;
  7135. /**
  7136. * The uniform node that represents the uv transformation matrix.
  7137. *
  7138. * @private
  7139. * @type {?UniformNode<mat3>}
  7140. */
  7141. this._matrixUniform = null;
  7142. this.setUpdateMatrix( uvNode === null );
  7143. }
  7144. set value( value ) {
  7145. if ( this.referenceNode ) {
  7146. this.referenceNode.value = value;
  7147. } else {
  7148. this._value = value;
  7149. }
  7150. }
  7151. /**
  7152. * The texture value.
  7153. *
  7154. * @type {Texture}
  7155. */
  7156. get value() {
  7157. return this.referenceNode ? this.referenceNode.value : this._value;
  7158. }
  7159. /**
  7160. * Overwritten since the uniform hash is defined by the texture's UUID.
  7161. *
  7162. * @param {NodeBuilder} builder - The current node builder.
  7163. * @return {string} The uniform hash.
  7164. */
  7165. getUniformHash( /*builder*/ ) {
  7166. return this.value.uuid;
  7167. }
  7168. /**
  7169. * Overwritten since the node type is inferred from the texture type.
  7170. *
  7171. * @param {NodeBuilder} builder - The current node builder.
  7172. * @return {string} The node type.
  7173. */
  7174. getNodeType( /*builder*/ ) {
  7175. if ( this.value.isDepthTexture === true ) return 'float';
  7176. if ( this.value.type === UnsignedIntType ) {
  7177. return 'uvec4';
  7178. } else if ( this.value.type === IntType ) {
  7179. return 'ivec4';
  7180. }
  7181. return 'vec4';
  7182. }
  7183. /**
  7184. * Overwrites the default implementation to return a fixed value `'texture'`.
  7185. *
  7186. * @param {NodeBuilder} builder - The current node builder.
  7187. * @return {string} The input type.
  7188. */
  7189. getInputType( /*builder*/ ) {
  7190. return 'texture';
  7191. }
  7192. /**
  7193. * Returns a default uvs based on the current texture's channel.
  7194. *
  7195. * @return {AttributeNode<vec2>} The default uvs.
  7196. */
  7197. getDefaultUV() {
  7198. return uv( this.value.channel );
  7199. }
  7200. /**
  7201. * Overwritten to always return the texture reference of the node.
  7202. *
  7203. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7204. * @return {Texture} The texture reference.
  7205. */
  7206. updateReference( /*state*/ ) {
  7207. return this.value;
  7208. }
  7209. /**
  7210. * Transforms the given uv node with the texture transformation matrix.
  7211. *
  7212. * @param {Node} uvNode - The uv node to transform.
  7213. * @return {Node} The transformed uv node.
  7214. */
  7215. getTransformedUV( uvNode ) {
  7216. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7217. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7218. }
  7219. /**
  7220. * Defines whether the uv transformation matrix should automatically be updated or not.
  7221. *
  7222. * @param {boolean} value - The update toggle.
  7223. * @return {TextureNode} A reference to this node.
  7224. */
  7225. setUpdateMatrix( value ) {
  7226. this.updateMatrix = value;
  7227. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7228. return this;
  7229. }
  7230. /**
  7231. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7232. * to modify the uv node for correct sampling.
  7233. *
  7234. * @param {NodeBuilder} builder - The current node builder.
  7235. * @param {Node} uvNode - The uv node to setup.
  7236. * @return {Node} The updated uv node.
  7237. */
  7238. setupUV( builder, uvNode ) {
  7239. const texture = this.value;
  7240. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7241. if ( this.sampler ) {
  7242. uvNode = uvNode.flipY();
  7243. } else {
  7244. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7245. }
  7246. }
  7247. return uvNode;
  7248. }
  7249. /**
  7250. * Setups texture node by preparing the internal nodes for code generation.
  7251. *
  7252. * @param {NodeBuilder} builder - The current node builder.
  7253. */
  7254. setup( builder ) {
  7255. const properties = builder.getNodeProperties( this );
  7256. properties.referenceNode = this.referenceNode;
  7257. //
  7258. const texture = this.value;
  7259. if ( ! texture || texture.isTexture !== true ) {
  7260. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7261. }
  7262. //
  7263. let uvNode = this.uvNode;
  7264. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7265. uvNode = builder.context.getUV( this, builder );
  7266. }
  7267. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7268. if ( this.updateMatrix === true ) {
  7269. uvNode = this.getTransformedUV( uvNode );
  7270. }
  7271. uvNode = this.setupUV( builder, uvNode );
  7272. //
  7273. let levelNode = this.levelNode;
  7274. if ( levelNode === null && builder.context.getTextureLevel ) {
  7275. levelNode = builder.context.getTextureLevel( this );
  7276. }
  7277. //
  7278. properties.uvNode = uvNode;
  7279. properties.levelNode = levelNode;
  7280. properties.biasNode = this.biasNode;
  7281. properties.compareNode = this.compareNode;
  7282. properties.gradNode = this.gradNode;
  7283. properties.depthNode = this.depthNode;
  7284. }
  7285. /**
  7286. * Generates the uv code snippet.
  7287. *
  7288. * @param {NodeBuilder} builder - The current node builder.
  7289. * @param {Node} uvNode - The uv node to generate code for.
  7290. * @return {string} The generated code snippet.
  7291. */
  7292. generateUV( builder, uvNode ) {
  7293. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7294. }
  7295. /**
  7296. * Generates the snippet for the texture sampling.
  7297. *
  7298. * @param {NodeBuilder} builder - The current node builder.
  7299. * @param {string} textureProperty - The texture property.
  7300. * @param {string} uvSnippet - The uv snippet.
  7301. * @param {?string} levelSnippet - The level snippet.
  7302. * @param {?string} biasSnippet - The bias snippet.
  7303. * @param {?string} depthSnippet - The depth snippet.
  7304. * @param {?string} compareSnippet - The compare snippet.
  7305. * @param {?Array<string>} gradSnippet - The grad snippet.
  7306. * @return {string} The generated code snippet.
  7307. */
  7308. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7309. const texture = this.value;
  7310. let snippet;
  7311. if ( levelSnippet ) {
  7312. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7313. } else if ( biasSnippet ) {
  7314. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7315. } else if ( gradSnippet ) {
  7316. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7317. } else if ( compareSnippet ) {
  7318. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7319. } else if ( this.sampler === false ) {
  7320. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7321. } else {
  7322. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7323. }
  7324. return snippet;
  7325. }
  7326. /**
  7327. * Generates the code snippet of the texture node.
  7328. *
  7329. * @param {NodeBuilder} builder - The current node builder.
  7330. * @param {string} output - The current output.
  7331. * @return {string} The generated code snippet.
  7332. */
  7333. generate( builder, output ) {
  7334. const texture = this.value;
  7335. const properties = builder.getNodeProperties( this );
  7336. const textureProperty = super.generate( builder, 'property' );
  7337. if ( /^sampler/.test( output ) ) {
  7338. return textureProperty + '_sampler';
  7339. } else if ( builder.isReference( output ) ) {
  7340. return textureProperty;
  7341. } else {
  7342. const nodeData = builder.getDataFromNode( this );
  7343. let propertyName = nodeData.propertyName;
  7344. if ( propertyName === undefined ) {
  7345. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7346. const uvSnippet = this.generateUV( builder, uvNode );
  7347. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7348. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7349. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7350. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7351. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7352. const nodeVar = builder.getVarFromNode( this );
  7353. propertyName = builder.getPropertyName( nodeVar );
  7354. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7355. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7356. nodeData.snippet = snippet;
  7357. nodeData.propertyName = propertyName;
  7358. }
  7359. let snippet = propertyName;
  7360. const nodeType = this.getNodeType( builder );
  7361. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7362. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7363. }
  7364. return builder.format( snippet, nodeType, output );
  7365. }
  7366. }
  7367. /**
  7368. * Sets the sampler value.
  7369. *
  7370. * @param {boolean} value - The sampler value to set.
  7371. * @return {TextureNode} A reference to this texture node.
  7372. */
  7373. setSampler( value ) {
  7374. this.sampler = value;
  7375. return this;
  7376. }
  7377. /**
  7378. * Returns the sampler value.
  7379. *
  7380. * @return {boolean} The sampler value.
  7381. */
  7382. getSampler() {
  7383. return this.sampler;
  7384. }
  7385. // @TODO: Move to TSL
  7386. /**
  7387. * @function
  7388. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7389. *
  7390. * @param {Node} uvNode - The uv node.
  7391. * @return {TextureNode} A texture node representing the texture sample.
  7392. */
  7393. uv( uvNode ) { // @deprecated, r172
  7394. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7395. return this.sample( uvNode );
  7396. }
  7397. /**
  7398. * Samples the texture with the given uv node.
  7399. *
  7400. * @param {Node} uvNode - The uv node.
  7401. * @return {TextureNode} A texture node representing the texture sample.
  7402. */
  7403. sample( uvNode ) {
  7404. const textureNode = this.clone();
  7405. textureNode.uvNode = nodeObject( uvNode );
  7406. textureNode.referenceNode = this.getSelf();
  7407. return nodeObject( textureNode );
  7408. }
  7409. /**
  7410. * Samples a blurred version of the texture by defining an internal bias.
  7411. *
  7412. * @param {Node<float>} amountNode - How blurred the texture should be.
  7413. * @return {TextureNode} A texture node representing the texture sample.
  7414. */
  7415. blur( amountNode ) {
  7416. const textureNode = this.clone();
  7417. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7418. textureNode.referenceNode = this.getSelf();
  7419. const map = textureNode.value;
  7420. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7421. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7422. textureNode.biasNode = null;
  7423. }
  7424. return nodeObject( textureNode );
  7425. }
  7426. /**
  7427. * Samples a specific mip of the texture.
  7428. *
  7429. * @param {Node<int>} levelNode - The mip level to sample.
  7430. * @return {TextureNode} A texture node representing the texture sample.
  7431. */
  7432. level( levelNode ) {
  7433. const textureNode = this.clone();
  7434. textureNode.levelNode = nodeObject( levelNode );
  7435. textureNode.referenceNode = this.getSelf();
  7436. return nodeObject( textureNode );
  7437. }
  7438. /**
  7439. * Returns the texture size of the requested level.
  7440. *
  7441. * @param {Node<int>} levelNode - The level to compute the size for.
  7442. * @return {TextureSizeNode} The texture size.
  7443. */
  7444. size( levelNode ) {
  7445. return textureSize( this, levelNode );
  7446. }
  7447. /**
  7448. * Samples the texture with the given bias.
  7449. *
  7450. * @param {Node<float>} biasNode - The bias node.
  7451. * @return {TextureNode} A texture node representing the texture sample.
  7452. */
  7453. bias( biasNode ) {
  7454. const textureNode = this.clone();
  7455. textureNode.biasNode = nodeObject( biasNode );
  7456. textureNode.referenceNode = this.getSelf();
  7457. return nodeObject( textureNode );
  7458. }
  7459. /**
  7460. * Samples the texture by executing a compare operation.
  7461. *
  7462. * @param {Node<float>} compareNode - The node that defines the compare value.
  7463. * @return {TextureNode} A texture node representing the texture sample.
  7464. */
  7465. compare( compareNode ) {
  7466. const textureNode = this.clone();
  7467. textureNode.compareNode = nodeObject( compareNode );
  7468. textureNode.referenceNode = this.getSelf();
  7469. return nodeObject( textureNode );
  7470. }
  7471. /**
  7472. * Samples the texture using an explicit gradient.
  7473. *
  7474. * @param {Node<vec2>} gradNodeX - The gradX node.
  7475. * @param {Node<vec2>} gradNodeY - The gradY node.
  7476. * @return {TextureNode} A texture node representing the texture sample.
  7477. */
  7478. grad( gradNodeX, gradNodeY ) {
  7479. const textureNode = this.clone();
  7480. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7481. textureNode.referenceNode = this.getSelf();
  7482. return nodeObject( textureNode );
  7483. }
  7484. /**
  7485. * Samples the texture by defining a depth node.
  7486. *
  7487. * @param {Node<int>} depthNode - The depth node.
  7488. * @return {TextureNode} A texture node representing the texture sample.
  7489. */
  7490. depth( depthNode ) {
  7491. const textureNode = this.clone();
  7492. textureNode.depthNode = nodeObject( depthNode );
  7493. textureNode.referenceNode = this.getSelf();
  7494. return nodeObject( textureNode );
  7495. }
  7496. // --
  7497. serialize( data ) {
  7498. super.serialize( data );
  7499. data.value = this.value.toJSON( data.meta ).uuid;
  7500. data.sampler = this.sampler;
  7501. data.updateMatrix = this.updateMatrix;
  7502. data.updateType = this.updateType;
  7503. }
  7504. deserialize( data ) {
  7505. super.deserialize( data );
  7506. this.value = data.meta.textures[ data.value ];
  7507. this.sampler = data.sampler;
  7508. this.updateMatrix = data.updateMatrix;
  7509. this.updateType = data.updateType;
  7510. }
  7511. /**
  7512. * The update is used to implement the update of the uv transformation matrix.
  7513. */
  7514. update() {
  7515. const texture = this.value;
  7516. const matrixUniform = this._matrixUniform;
  7517. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7518. if ( texture.matrixAutoUpdate === true ) {
  7519. texture.updateMatrix();
  7520. }
  7521. }
  7522. /**
  7523. * Clones the texture node.
  7524. *
  7525. * @return {TextureNode} The cloned texture node.
  7526. */
  7527. clone() {
  7528. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7529. newNode.sampler = this.sampler;
  7530. newNode.depthNode = this.depthNode;
  7531. newNode.compareNode = this.compareNode;
  7532. newNode.gradNode = this.gradNode;
  7533. return newNode;
  7534. }
  7535. }
  7536. /**
  7537. * TSL function for creating a texture node.
  7538. *
  7539. * @tsl
  7540. * @function
  7541. * @param {Texture} value - The texture.
  7542. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7543. * @param {?Node<int>} [levelNode=null] - The level node.
  7544. * @param {?Node<float>} [biasNode=null] - The bias node.
  7545. * @returns {TextureNode}
  7546. */
  7547. const texture = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 );
  7548. /**
  7549. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7550. *
  7551. * @tsl
  7552. * @function
  7553. * @param {Texture} value - The texture.
  7554. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7555. * @param {?Node<int>} [levelNode=null] - The level node.
  7556. * @param {?Node<float>} [biasNode=null] - The bias node.
  7557. * @returns {TextureNode}
  7558. */
  7559. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7560. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7561. /**
  7562. * Converts a texture or texture node to a sampler.
  7563. *
  7564. * @tsl
  7565. * @function
  7566. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7567. * @returns {Node}
  7568. */
  7569. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  7570. /**
  7571. * Converts a texture or texture node to a sampler comparison.
  7572. *
  7573. * @tsl
  7574. * @function
  7575. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7576. * @returns {Node}
  7577. */
  7578. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  7579. /**
  7580. * A special type of uniform node which represents array-like data
  7581. * as uniform buffers. The access usually happens via `element()`
  7582. * which returns an instance of {@link ArrayElementNode}. For example:
  7583. *
  7584. * ```js
  7585. * const bufferNode = buffer( array, 'mat4', count );
  7586. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7587. * ```
  7588. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7589. * since it handles more input types and automatically cares about buffer paddings.
  7590. *
  7591. * @augments UniformNode
  7592. */
  7593. class BufferNode extends UniformNode {
  7594. static get type() {
  7595. return 'BufferNode';
  7596. }
  7597. /**
  7598. * Constructs a new buffer node.
  7599. *
  7600. * @param {Array<number>} value - Array-like buffer data.
  7601. * @param {string} bufferType - The data type of the buffer.
  7602. * @param {number} [bufferCount=0] - The count of buffer elements.
  7603. */
  7604. constructor( value, bufferType, bufferCount = 0 ) {
  7605. super( value, bufferType );
  7606. /**
  7607. * This flag can be used for type testing.
  7608. *
  7609. * @type {boolean}
  7610. * @readonly
  7611. * @default true
  7612. */
  7613. this.isBufferNode = true;
  7614. /**
  7615. * The data type of the buffer.
  7616. *
  7617. * @type {string}
  7618. */
  7619. this.bufferType = bufferType;
  7620. /**
  7621. * The uniform node that holds the value of the reference node.
  7622. *
  7623. * @type {number}
  7624. * @default 0
  7625. */
  7626. this.bufferCount = bufferCount;
  7627. }
  7628. /**
  7629. * The data type of the buffer elements.
  7630. *
  7631. * @param {NodeBuilder} builder - The current node builder.
  7632. * @return {string} The element type.
  7633. */
  7634. getElementType( builder ) {
  7635. return this.getNodeType( builder );
  7636. }
  7637. /**
  7638. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7639. *
  7640. * @param {NodeBuilder} builder - The current node builder.
  7641. * @return {string} The input type.
  7642. */
  7643. getInputType( /*builder*/ ) {
  7644. return 'buffer';
  7645. }
  7646. }
  7647. /**
  7648. * TSL function for creating a buffer node.
  7649. *
  7650. * @tsl
  7651. * @function
  7652. * @param {Array} value - Array-like buffer data.
  7653. * @param {string} type - The data type of a buffer element.
  7654. * @param {number} count - The count of buffer elements.
  7655. * @returns {BufferNode}
  7656. */
  7657. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7658. /**
  7659. * Represents the element access on uniform array nodes.
  7660. *
  7661. * @augments ArrayElementNode
  7662. */
  7663. class UniformArrayElementNode extends ArrayElementNode {
  7664. static get type() {
  7665. return 'UniformArrayElementNode';
  7666. }
  7667. /**
  7668. * Constructs a new buffer node.
  7669. *
  7670. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7671. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7672. */
  7673. constructor( uniformArrayNode, indexNode ) {
  7674. super( uniformArrayNode, indexNode );
  7675. /**
  7676. * This flag can be used for type testing.
  7677. *
  7678. * @type {boolean}
  7679. * @readonly
  7680. * @default true
  7681. */
  7682. this.isArrayBufferElementNode = true;
  7683. }
  7684. generate( builder ) {
  7685. const snippet = super.generate( builder );
  7686. const type = this.getNodeType();
  7687. const paddedType = this.node.getPaddedType();
  7688. return builder.format( snippet, paddedType, type );
  7689. }
  7690. }
  7691. /**
  7692. * Similar to {@link BufferNode} this module represents array-like data as
  7693. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7694. * data types in the array (e.g `three.js` primitives) and automatically
  7695. * manage buffer padding. It should be the first choice when working with
  7696. * uniforms buffers.
  7697. * ```js
  7698. * const tintColors = uniformArray( [
  7699. * new Color( 1, 0, 0 ),
  7700. * new Color( 0, 1, 0 ),
  7701. * new Color( 0, 0, 1 )
  7702. * ], 'color' );
  7703. *
  7704. * const redColor = tintColors.element( 0 );
  7705. *
  7706. * @augments BufferNode
  7707. */
  7708. class UniformArrayNode extends BufferNode {
  7709. static get type() {
  7710. return 'UniformArrayNode';
  7711. }
  7712. /**
  7713. * Constructs a new uniform array node.
  7714. *
  7715. * @param {Array<any>} value - Array holding the buffer data.
  7716. * @param {?string} [elementType=null] - The data type of a buffer element.
  7717. */
  7718. constructor( value, elementType = null ) {
  7719. super( null );
  7720. /**
  7721. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7722. * hold number primitives as well as three.js objects like vectors, matrices
  7723. * or colors.
  7724. *
  7725. * @type {Array<any>}
  7726. */
  7727. this.array = value;
  7728. /**
  7729. * The data type of an array element.
  7730. *
  7731. * @type {string}
  7732. */
  7733. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7734. /**
  7735. * The padded type. Uniform buffers must conform to a certain buffer layout
  7736. * so a separate type is computed to ensure correct buffer size.
  7737. *
  7738. * @type {string}
  7739. */
  7740. this.paddedType = this.getPaddedType();
  7741. /**
  7742. * Overwritten since uniform array nodes are updated per render.
  7743. *
  7744. * @type {string}
  7745. * @default 'render'
  7746. */
  7747. this.updateType = NodeUpdateType.RENDER;
  7748. /**
  7749. * This flag can be used for type testing.
  7750. *
  7751. * @type {boolean}
  7752. * @readonly
  7753. * @default true
  7754. */
  7755. this.isArrayBufferNode = true;
  7756. }
  7757. /**
  7758. * This method is overwritten since the node type is inferred from the
  7759. * {@link UniformArrayNode#paddedType}.
  7760. *
  7761. * @param {NodeBuilder} builder - The current node builder.
  7762. * @return {string} The node type.
  7763. */
  7764. getNodeType( /*builder*/ ) {
  7765. return this.paddedType;
  7766. }
  7767. /**
  7768. * The data type of the array elements.
  7769. *
  7770. * @param {NodeBuilder} builder - The current node builder.
  7771. * @return {string} The element type.
  7772. */
  7773. getElementType() {
  7774. return this.elementType;
  7775. }
  7776. /**
  7777. * Returns the padded type based on the element type.
  7778. *
  7779. * @return {string} The padded type.
  7780. */
  7781. getPaddedType() {
  7782. const elementType = this.elementType;
  7783. let paddedType = 'vec4';
  7784. if ( elementType === 'mat2' ) {
  7785. paddedType = 'mat2';
  7786. } else if ( /mat/.test( elementType ) === true ) {
  7787. paddedType = 'mat4';
  7788. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7789. paddedType = 'ivec4';
  7790. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7791. paddedType = 'uvec4';
  7792. }
  7793. return paddedType;
  7794. }
  7795. /**
  7796. * The update makes sure to correctly transfer the data from the (complex) objects
  7797. * in the array to the internal, correctly padded value buffer.
  7798. *
  7799. * @param {NodeFrame} frame - A reference to the current node frame.
  7800. */
  7801. update( /*frame*/ ) {
  7802. const { array, value } = this;
  7803. const elementType = this.elementType;
  7804. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7805. for ( let i = 0; i < array.length; i ++ ) {
  7806. const index = i * 4;
  7807. value[ index ] = array[ i ];
  7808. }
  7809. } else if ( elementType === 'color' ) {
  7810. for ( let i = 0; i < array.length; i ++ ) {
  7811. const index = i * 4;
  7812. const vector = array[ i ];
  7813. value[ index ] = vector.r;
  7814. value[ index + 1 ] = vector.g;
  7815. value[ index + 2 ] = vector.b || 0;
  7816. //value[ index + 3 ] = vector.a || 0;
  7817. }
  7818. } else if ( elementType === 'mat2' ) {
  7819. for ( let i = 0; i < array.length; i ++ ) {
  7820. const index = i * 4;
  7821. const matrix = array[ i ];
  7822. value[ index ] = matrix.elements[ 0 ];
  7823. value[ index + 1 ] = matrix.elements[ 1 ];
  7824. value[ index + 2 ] = matrix.elements[ 2 ];
  7825. value[ index + 3 ] = matrix.elements[ 3 ];
  7826. }
  7827. } else if ( elementType === 'mat3' ) {
  7828. for ( let i = 0; i < array.length; i ++ ) {
  7829. const index = i * 16;
  7830. const matrix = array[ i ];
  7831. value[ index ] = matrix.elements[ 0 ];
  7832. value[ index + 1 ] = matrix.elements[ 1 ];
  7833. value[ index + 2 ] = matrix.elements[ 2 ];
  7834. value[ index + 4 ] = matrix.elements[ 3 ];
  7835. value[ index + 5 ] = matrix.elements[ 4 ];
  7836. value[ index + 6 ] = matrix.elements[ 5 ];
  7837. value[ index + 8 ] = matrix.elements[ 6 ];
  7838. value[ index + 9 ] = matrix.elements[ 7 ];
  7839. value[ index + 10 ] = matrix.elements[ 8 ];
  7840. value[ index + 15 ] = 1;
  7841. }
  7842. } else if ( elementType === 'mat4' ) {
  7843. for ( let i = 0; i < array.length; i ++ ) {
  7844. const index = i * 16;
  7845. const matrix = array[ i ];
  7846. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7847. value[ index + i ] = matrix.elements[ i ];
  7848. }
  7849. }
  7850. } else {
  7851. for ( let i = 0; i < array.length; i ++ ) {
  7852. const index = i * 4;
  7853. const vector = array[ i ];
  7854. value[ index ] = vector.x;
  7855. value[ index + 1 ] = vector.y;
  7856. value[ index + 2 ] = vector.z || 0;
  7857. value[ index + 3 ] = vector.w || 0;
  7858. }
  7859. }
  7860. }
  7861. /**
  7862. * Implement the value buffer creation based on the array data.
  7863. *
  7864. * @param {NodeBuilder} builder - A reference to the current node builder.
  7865. * @return {null}
  7866. */
  7867. setup( builder ) {
  7868. const length = this.array.length;
  7869. const elementType = this.elementType;
  7870. let arrayType = Float32Array;
  7871. const paddedType = this.paddedType;
  7872. const paddedElementLength = builder.getTypeLength( paddedType );
  7873. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7874. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7875. this.value = new arrayType( length * paddedElementLength );
  7876. this.bufferCount = length;
  7877. this.bufferType = paddedType;
  7878. return super.setup( builder );
  7879. }
  7880. /**
  7881. * Overwrites the default `element()` method to provide element access
  7882. * based on {@link UniformArrayNode}.
  7883. *
  7884. * @param {IndexNode} indexNode - The index node.
  7885. * @return {UniformArrayElementNode}
  7886. */
  7887. element( indexNode ) {
  7888. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7889. }
  7890. }
  7891. /**
  7892. * TSL function for creating an uniform array node.
  7893. *
  7894. * @tsl
  7895. * @function
  7896. * @param {Array<any>} values - Array-like data.
  7897. * @param {?string} [nodeType] - The data type of the array elements.
  7898. * @returns {UniformArrayNode}
  7899. */
  7900. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7901. /**
  7902. * @tsl
  7903. * @function
  7904. * @deprecated since r168. Use {@link uniformArray} instead.
  7905. *
  7906. * @param {Array<any>} values - Array-like data.
  7907. * @param {string} nodeType - The data type of the array elements.
  7908. * @returns {UniformArrayNode}
  7909. */
  7910. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7911. console.warn( 'THREE.TSL: uniforms() has been renamed to uniformArray().' );
  7912. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7913. };
  7914. /**
  7915. * The node allows to set values for built-in shader variables. That is
  7916. * required for features like hardware-accelerated vertex clipping.
  7917. *
  7918. * @augments Node
  7919. */
  7920. class BuiltinNode extends Node {
  7921. /**
  7922. * Constructs a new builtin node.
  7923. *
  7924. * @param {string} name - The name of the built-in shader variable.
  7925. */
  7926. constructor( name ) {
  7927. super( 'float' );
  7928. /**
  7929. * The name of the built-in shader variable.
  7930. *
  7931. * @type {string}
  7932. */
  7933. this.name = name;
  7934. /**
  7935. * This flag can be used for type testing.
  7936. *
  7937. * @type {boolean}
  7938. * @readonly
  7939. * @default true
  7940. */
  7941. this.isBuiltinNode = true;
  7942. }
  7943. /**
  7944. * Generates the code snippet of the builtin node.
  7945. *
  7946. * @param {NodeBuilder} builder - The current node builder.
  7947. * @return {string} The generated code snippet.
  7948. */
  7949. generate( /* builder */ ) {
  7950. return this.name;
  7951. }
  7952. }
  7953. /**
  7954. * TSL function for creating a builtin node.
  7955. *
  7956. * @tsl
  7957. * @function
  7958. * @param {string} name - The name of the built-in shader variable.
  7959. * @returns {BuiltinNode}
  7960. */
  7961. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  7962. /**
  7963. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7964. *
  7965. * @tsl
  7966. * @type {UniformNode<uint>}
  7967. */
  7968. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).label( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7969. /**
  7970. * TSL object that represents the `near` value of the camera used for the current render.
  7971. *
  7972. * @tsl
  7973. * @type {UniformNode<float>}
  7974. */
  7975. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7976. /**
  7977. * TSL object that represents the `far` value of the camera used for the current render.
  7978. *
  7979. * @tsl
  7980. * @type {UniformNode<float>}
  7981. */
  7982. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7983. /**
  7984. * TSL object that represents the projection matrix of the camera used for the current render.
  7985. *
  7986. * @tsl
  7987. * @type {UniformNode<mat4>}
  7988. */
  7989. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7990. let cameraProjectionMatrix;
  7991. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7992. const matrices = [];
  7993. for ( const subCamera of camera.cameras ) {
  7994. matrices.push( subCamera.projectionMatrix );
  7995. }
  7996. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7997. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7998. } else {
  7999. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8000. }
  8001. return cameraProjectionMatrix;
  8002. } ).once() )();
  8003. /**
  8004. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8005. *
  8006. * @tsl
  8007. * @type {UniformNode<mat4>}
  8008. */
  8009. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8010. let cameraProjectionMatrixInverse;
  8011. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8012. const matrices = [];
  8013. for ( const subCamera of camera.cameras ) {
  8014. matrices.push( subCamera.projectionMatrixInverse );
  8015. }
  8016. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatricesInverse' );
  8017. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrixInverse' );
  8018. } else {
  8019. cameraProjectionMatrixInverse = uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8020. }
  8021. return cameraProjectionMatrixInverse;
  8022. } ).once() )();
  8023. /**
  8024. * TSL object that represents the view matrix of the camera used for the current render.
  8025. *
  8026. * @tsl
  8027. * @type {UniformNode<mat4>}
  8028. */
  8029. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8030. let cameraViewMatrix;
  8031. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8032. const matrices = [];
  8033. for ( const subCamera of camera.cameras ) {
  8034. matrices.push( subCamera.matrixWorldInverse );
  8035. }
  8036. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  8037. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraViewMatrix' );
  8038. } else {
  8039. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8040. }
  8041. return cameraViewMatrix;
  8042. } ).once() )();
  8043. /**
  8044. * TSL object that represents the world matrix of the camera used for the current render.
  8045. *
  8046. * @tsl
  8047. * @type {UniformNode<mat4>}
  8048. */
  8049. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8050. /**
  8051. * TSL object that represents the normal matrix of the camera used for the current render.
  8052. *
  8053. * @tsl
  8054. * @type {UniformNode<mat3>}
  8055. */
  8056. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8057. /**
  8058. * TSL object that represents the position in world space of the camera used for the current render.
  8059. *
  8060. * @tsl
  8061. * @type {UniformNode<vec3>}
  8062. */
  8063. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8064. const _sphere = /*@__PURE__*/ new Sphere();
  8065. /**
  8066. * This node can be used to access transformation related metrics of 3D objects.
  8067. * Depending on the selected scope, a different metric is represented as a uniform
  8068. * in the shader. The following scopes are supported:
  8069. *
  8070. * - `POSITION`: The object's position in world space.
  8071. * - `VIEW_POSITION`: The object's position in view/camera space.
  8072. * - `DIRECTION`: The object's direction in world space.
  8073. * - `SCALE`: The object's scale in world space.
  8074. * - `WORLD_MATRIX`: The object's matrix in world space.
  8075. *
  8076. * @augments Node
  8077. */
  8078. class Object3DNode extends Node {
  8079. static get type() {
  8080. return 'Object3DNode';
  8081. }
  8082. /**
  8083. * Constructs a new object 3D node.
  8084. *
  8085. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8086. * @param {?Object3D} [object3d=null] - The 3D object.
  8087. */
  8088. constructor( scope, object3d = null ) {
  8089. super();
  8090. /**
  8091. * The node reports a different type of transformation depending on the scope.
  8092. *
  8093. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8094. */
  8095. this.scope = scope;
  8096. /**
  8097. * The 3D object.
  8098. *
  8099. * @type {?Object3D}
  8100. * @default null
  8101. */
  8102. this.object3d = object3d;
  8103. /**
  8104. * Overwritten since this type of node is updated per object.
  8105. *
  8106. * @type {string}
  8107. * @default 'object'
  8108. */
  8109. this.updateType = NodeUpdateType.OBJECT;
  8110. /**
  8111. * Holds the value of the node as a uniform.
  8112. *
  8113. * @private
  8114. * @type {UniformNode}
  8115. */
  8116. this._uniformNode = new UniformNode( null );
  8117. }
  8118. /**
  8119. * Overwritten since the node type is inferred from the scope.
  8120. *
  8121. * @return {string} The node type.
  8122. */
  8123. getNodeType() {
  8124. const scope = this.scope;
  8125. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8126. return 'mat4';
  8127. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8128. return 'vec3';
  8129. } else if ( scope === Object3DNode.RADIUS ) {
  8130. return 'float';
  8131. }
  8132. }
  8133. /**
  8134. * Updates the uniform value depending on the scope.
  8135. *
  8136. * @param {NodeFrame} frame - The current node frame.
  8137. */
  8138. update( frame ) {
  8139. const object = this.object3d;
  8140. const uniformNode = this._uniformNode;
  8141. const scope = this.scope;
  8142. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8143. uniformNode.value = object.matrixWorld;
  8144. } else if ( scope === Object3DNode.POSITION ) {
  8145. uniformNode.value = uniformNode.value || new Vector3();
  8146. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8147. } else if ( scope === Object3DNode.SCALE ) {
  8148. uniformNode.value = uniformNode.value || new Vector3();
  8149. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8150. } else if ( scope === Object3DNode.DIRECTION ) {
  8151. uniformNode.value = uniformNode.value || new Vector3();
  8152. object.getWorldDirection( uniformNode.value );
  8153. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8154. const camera = frame.camera;
  8155. uniformNode.value = uniformNode.value || new Vector3();
  8156. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8157. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8158. } else if ( scope === Object3DNode.RADIUS ) {
  8159. const geometry = frame.object.geometry;
  8160. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8161. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8162. uniformNode.value = _sphere.radius;
  8163. }
  8164. }
  8165. /**
  8166. * Generates the code snippet of the uniform node. The node type of the uniform
  8167. * node also depends on the selected scope.
  8168. *
  8169. * @param {NodeBuilder} builder - The current node builder.
  8170. * @return {string} The generated code snippet.
  8171. */
  8172. generate( builder ) {
  8173. const scope = this.scope;
  8174. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8175. this._uniformNode.nodeType = 'mat4';
  8176. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8177. this._uniformNode.nodeType = 'vec3';
  8178. } else if ( scope === Object3DNode.RADIUS ) {
  8179. this._uniformNode.nodeType = 'float';
  8180. }
  8181. return this._uniformNode.build( builder );
  8182. }
  8183. serialize( data ) {
  8184. super.serialize( data );
  8185. data.scope = this.scope;
  8186. }
  8187. deserialize( data ) {
  8188. super.deserialize( data );
  8189. this.scope = data.scope;
  8190. }
  8191. }
  8192. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8193. Object3DNode.POSITION = 'position';
  8194. Object3DNode.SCALE = 'scale';
  8195. Object3DNode.VIEW_POSITION = 'viewPosition';
  8196. Object3DNode.DIRECTION = 'direction';
  8197. Object3DNode.RADIUS = 'radius';
  8198. /**
  8199. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8200. *
  8201. * @tsl
  8202. * @function
  8203. * @param {?Object3D} [object3d] - The 3D object.
  8204. * @returns {Object3DNode<vec3>}
  8205. */
  8206. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8207. /**
  8208. * TSL function for creating an object 3D node that represents the object's world matrix.
  8209. *
  8210. * @tsl
  8211. * @function
  8212. * @param {?Object3D} [object3d] - The 3D object.
  8213. * @returns {Object3DNode<mat4>}
  8214. */
  8215. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  8216. /**
  8217. * TSL function for creating an object 3D node that represents the object's position in world space.
  8218. *
  8219. * @tsl
  8220. * @function
  8221. * @param {?Object3D} [object3d] - The 3D object.
  8222. * @returns {Object3DNode<vec3>}
  8223. */
  8224. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  8225. /**
  8226. * TSL function for creating an object 3D node that represents the object's scale in world space.
  8227. *
  8228. * @tsl
  8229. * @function
  8230. * @param {?Object3D} [object3d] - The 3D object.
  8231. * @returns {Object3DNode<vec3>}
  8232. */
  8233. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  8234. /**
  8235. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  8236. *
  8237. * @tsl
  8238. * @function
  8239. * @param {?Object3D} [object3d] - The 3D object.
  8240. * @returns {Object3DNode<vec3>}
  8241. */
  8242. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  8243. /**
  8244. * TSL function for creating an object 3D node that represents the object's radius.
  8245. *
  8246. * @tsl
  8247. * @function
  8248. * @param {?Object3D} [object3d] - The 3D object.
  8249. * @returns {Object3DNode<vec3>}
  8250. */
  8251. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  8252. /**
  8253. * This type of node is a specialized version of `Object3DNode`
  8254. * with larger set of model related metrics. Unlike `Object3DNode`,
  8255. * `ModelNode` extracts the reference to the 3D object from the
  8256. * current node frame state.
  8257. *
  8258. * @augments Object3DNode
  8259. */
  8260. class ModelNode extends Object3DNode {
  8261. static get type() {
  8262. return 'ModelNode';
  8263. }
  8264. /**
  8265. * Constructs a new object model node.
  8266. *
  8267. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8268. */
  8269. constructor( scope ) {
  8270. super( scope );
  8271. }
  8272. /**
  8273. * Extracts the model reference from the frame state and then
  8274. * updates the uniform value depending on the scope.
  8275. *
  8276. * @param {NodeFrame} frame - The current node frame.
  8277. */
  8278. update( frame ) {
  8279. this.object3d = frame.object;
  8280. super.update( frame );
  8281. }
  8282. }
  8283. /**
  8284. * TSL object that represents the object's direction in world space.
  8285. *
  8286. * @tsl
  8287. * @type {ModelNode<vec3>}
  8288. */
  8289. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  8290. /**
  8291. * TSL object that represents the object's world matrix.
  8292. *
  8293. * @tsl
  8294. * @type {ModelNode<mat4>}
  8295. */
  8296. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  8297. /**
  8298. * TSL object that represents the object's position in world space.
  8299. *
  8300. * @tsl
  8301. * @type {ModelNode<vec3>}
  8302. */
  8303. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  8304. /**
  8305. * TSL object that represents the object's scale in world space.
  8306. *
  8307. * @tsl
  8308. * @type {ModelNode<vec3>}
  8309. */
  8310. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  8311. /**
  8312. * TSL object that represents the object's position in view/camera space.
  8313. *
  8314. * @tsl
  8315. * @type {ModelNode<vec3>}
  8316. */
  8317. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  8318. /**
  8319. * TSL object that represents the object's radius.
  8320. *
  8321. * @tsl
  8322. * @type {ModelNode<float>}
  8323. */
  8324. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  8325. /**
  8326. * TSL object that represents the object's normal matrix.
  8327. *
  8328. * @tsl
  8329. * @type {UniformNode<mat3>}
  8330. */
  8331. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  8332. /**
  8333. * TSL object that represents the object's inverse world matrix.
  8334. *
  8335. * @tsl
  8336. * @type {UniformNode<mat4>}
  8337. */
  8338. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  8339. /**
  8340. * TSL object that represents the object's model view matrix.
  8341. *
  8342. * @tsl
  8343. * @type {Node<mat4>}
  8344. */
  8345. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8346. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  8347. } ).once() )().toVar( 'modelViewMatrix' );
  8348. // GPU Precision
  8349. /**
  8350. * TSL object that represents the object's model view in `mediump` precision.
  8351. *
  8352. * @tsl
  8353. * @type {Node<mat4>}
  8354. */
  8355. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  8356. // CPU Precision
  8357. /**
  8358. * TSL object that represents the object's model view in `highp` precision
  8359. * which is achieved by computing the matrix in JS and not in the shader.
  8360. *
  8361. * @tsl
  8362. * @type {Node<mat4>}
  8363. */
  8364. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8365. builder.context.isHighPrecisionModelViewMatrix = true;
  8366. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  8367. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8368. } );
  8369. } ).once() )().toVar( 'highpModelViewMatrix' );
  8370. /**
  8371. * TSL object that represents the object's model normal view in `highp` precision
  8372. * which is achieved by computing the matrix in JS and not in the shader.
  8373. *
  8374. * @tsl
  8375. * @type {Node<mat3>}
  8376. */
  8377. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8378. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  8379. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  8380. if ( isHighPrecisionModelViewMatrix !== true ) {
  8381. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8382. }
  8383. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  8384. } );
  8385. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  8386. /**
  8387. * TSL object that represents the position attribute of the current rendered object.
  8388. *
  8389. * @tsl
  8390. * @type {AttributeNode<vec3>}
  8391. */
  8392. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  8393. /**
  8394. * TSL object that represents the vertex position in local space of the current rendered object.
  8395. *
  8396. * @tsl
  8397. * @type {AttributeNode<vec3>}
  8398. */
  8399. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  8400. /**
  8401. * TSL object that represents the previous vertex position in local space of the current rendered object.
  8402. * Used in context of {@link VelocityNode} for rendering motion vectors.
  8403. *
  8404. * @tsl
  8405. * @type {AttributeNode<vec3>}
  8406. */
  8407. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  8408. /**
  8409. * TSL object that represents the vertex position in world space of the current rendered object.
  8410. *
  8411. * @tsl
  8412. * @type {VaryingNode<vec3>}
  8413. */
  8414. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  8415. /**
  8416. * TSL object that represents the position world direction of the current rendered object.
  8417. *
  8418. * @tsl
  8419. * @type {Node<vec3>}
  8420. */
  8421. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  8422. /**
  8423. * TSL object that represents the vertex position in view space of the current rendered object.
  8424. *
  8425. * @tsl
  8426. * @type {VaryingNode<vec3>}
  8427. */
  8428. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8429. return builder.context.setupPositionView();
  8430. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  8431. /**
  8432. * TSL object that represents the position view direction of the current rendered object.
  8433. *
  8434. * @tsl
  8435. * @type {VaryingNode<vec3>}
  8436. */
  8437. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8438. /**
  8439. * This node can be used to evaluate whether a primitive is front or back facing.
  8440. *
  8441. * @augments Node
  8442. */
  8443. class FrontFacingNode extends Node {
  8444. static get type() {
  8445. return 'FrontFacingNode';
  8446. }
  8447. /**
  8448. * Constructs a new front facing node.
  8449. */
  8450. constructor() {
  8451. super( 'bool' );
  8452. /**
  8453. * This flag can be used for type testing.
  8454. *
  8455. * @type {boolean}
  8456. * @readonly
  8457. * @default true
  8458. */
  8459. this.isFrontFacingNode = true;
  8460. }
  8461. generate( builder ) {
  8462. const { renderer, material } = builder;
  8463. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8464. if ( material.side === BackSide ) {
  8465. return 'false';
  8466. }
  8467. }
  8468. return builder.getFrontFacing();
  8469. }
  8470. }
  8471. /**
  8472. * TSL object that represents whether a primitive is front or back facing
  8473. *
  8474. * @tsl
  8475. * @type {FrontFacingNode<bool>}
  8476. */
  8477. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8478. /**
  8479. * TSL object that represents the front facing status as a number instead of a bool.
  8480. * `1` means front facing, `-1` means back facing.
  8481. *
  8482. * @tsl
  8483. * @type {Node<float>}
  8484. */
  8485. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8486. /**
  8487. * TSL object that represents the normal attribute of the current rendered object.
  8488. *
  8489. * @tsl
  8490. * @type {Node<vec3>}
  8491. */
  8492. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8493. /**
  8494. * TSL object that represents the vertex normal in local space of the current rendered object.
  8495. *
  8496. * @tsl
  8497. * @type {Node<vec3>}
  8498. */
  8499. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8500. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8501. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  8502. return vec3( 0, 1, 0 );
  8503. }
  8504. return normalGeometry;
  8505. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8506. /**
  8507. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  8508. *
  8509. * @tsl
  8510. * @type {Node<vec3>}
  8511. */
  8512. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8513. /**
  8514. * TSL object that represents the vertex normal in view space of the current rendered object.
  8515. *
  8516. * @tsl
  8517. * @type {Node<vec3>}
  8518. */
  8519. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8520. let node;
  8521. if ( builder.material.flatShading === true ) {
  8522. node = normalFlat;
  8523. } else {
  8524. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  8525. }
  8526. return node;
  8527. }, 'vec3' ).once() )().toVar( 'normalView' );
  8528. /**
  8529. * TSL object that represents the vertex normal in world space of the current rendered object.
  8530. *
  8531. * @tsl
  8532. * @type {Node<vec3>}
  8533. */
  8534. const normalWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8535. let normal = normalView.transformDirection( cameraViewMatrix );
  8536. if ( builder.material.flatShading !== true ) {
  8537. normal = varying( normal, 'v_normalWorld' );
  8538. }
  8539. return normal;
  8540. }, 'vec3' ).once() )().normalize().toVar( 'normalWorld' );
  8541. /**
  8542. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  8543. *
  8544. * @tsl
  8545. * @type {Node<vec3>}
  8546. */
  8547. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8548. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8549. let node = builder.context.setupNormal().context( { getUV: null } );
  8550. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8551. return node;
  8552. }, 'vec3' ).once() )().toVar( 'transformedNormalView' );
  8553. /**
  8554. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  8555. *
  8556. * @tsl
  8557. * @type {Node<vec3>}
  8558. */
  8559. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  8560. /**
  8561. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  8562. *
  8563. * @tsl
  8564. * @type {Node<vec3>}
  8565. */
  8566. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8567. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8568. let node = builder.context.setupClearcoatNormal().context( { getUV: null } );
  8569. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8570. return node;
  8571. }, 'vec3' ).once() )().toVar( 'transformedClearcoatNormalView' );
  8572. /**
  8573. * Transforms the normal with the given matrix.
  8574. *
  8575. * @tsl
  8576. * @function
  8577. * @param {Node<vec3>} normal - The normal.
  8578. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8579. * @return {Node<vec3>} The transformed normal.
  8580. */
  8581. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8582. const m = mat3( matrix );
  8583. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8584. return m.mul( transformedNormal ).xyz;
  8585. } );
  8586. /**
  8587. * Transforms the given normal from local to view space.
  8588. *
  8589. * @tsl
  8590. * @function
  8591. * @param {Node<vec3>} normal - The normal.
  8592. * @param {NodeBuilder} builder - The current node builder.
  8593. * @return {Node<vec3>} The transformed normal.
  8594. */
  8595. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8596. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  8597. if ( modelNormalViewMatrix !== null ) {
  8598. return modelNormalViewMatrix.transformDirection( normal );
  8599. }
  8600. //
  8601. const transformedNormal = modelNormalMatrix.mul( normal );
  8602. return cameraViewMatrix.transformDirection( transformedNormal );
  8603. } );
  8604. const _e1$1 = /*@__PURE__*/ new Euler();
  8605. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8606. /**
  8607. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8608. *
  8609. * @tsl
  8610. * @type {UniformNode<float>}
  8611. */
  8612. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  8613. /**
  8614. * TSL object that represents the intensity of environment maps of PBR materials.
  8615. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  8616. *
  8617. * @tsl
  8618. * @type {Node<float>}
  8619. */
  8620. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  8621. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  8622. } );
  8623. /**
  8624. * TSL object that represents the rotation of environment maps.
  8625. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  8626. * rotation of `scene.environment` instead.
  8627. *
  8628. * @tsl
  8629. * @type {Node<mat4>}
  8630. */
  8631. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  8632. return frame.material;
  8633. } ).onObjectUpdate( function ( { material, scene } ) {
  8634. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  8635. if ( rotation ) {
  8636. _e1$1.copy( rotation );
  8637. _m1$1.makeRotationFromEuler( _e1$1 );
  8638. } else {
  8639. _m1$1.identity();
  8640. }
  8641. return _m1$1;
  8642. } );
  8643. /**
  8644. * The reflect vector in view space.
  8645. *
  8646. * @tsl
  8647. * @type {Node<vec3>}
  8648. */
  8649. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  8650. /**
  8651. * The refract vector in view space.
  8652. *
  8653. * @tsl
  8654. * @type {Node<vec3>}
  8655. */
  8656. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  8657. /**
  8658. * Used for sampling cube maps when using cube reflection mapping.
  8659. *
  8660. * @tsl
  8661. * @type {Node<vec3>}
  8662. */
  8663. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8664. /**
  8665. * Used for sampling cube maps when using cube refraction mapping.
  8666. *
  8667. * @tsl
  8668. * @type {Node<vec3>}
  8669. */
  8670. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8671. /**
  8672. * This type of uniform node represents a cube texture.
  8673. *
  8674. * @augments TextureNode
  8675. */
  8676. class CubeTextureNode extends TextureNode {
  8677. static get type() {
  8678. return 'CubeTextureNode';
  8679. }
  8680. /**
  8681. * Constructs a new cube texture node.
  8682. *
  8683. * @param {CubeTexture} value - The cube texture.
  8684. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8685. * @param {?Node<int>} [levelNode=null] - The level node.
  8686. * @param {?Node<float>} [biasNode=null] - The bias node.
  8687. */
  8688. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8689. super( value, uvNode, levelNode, biasNode );
  8690. /**
  8691. * This flag can be used for type testing.
  8692. *
  8693. * @type {boolean}
  8694. * @readonly
  8695. * @default true
  8696. */
  8697. this.isCubeTextureNode = true;
  8698. }
  8699. /**
  8700. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8701. *
  8702. * @param {NodeBuilder} builder - The current node builder.
  8703. * @return {string} The input type.
  8704. */
  8705. getInputType( /*builder*/ ) {
  8706. return 'cubeTexture';
  8707. }
  8708. /**
  8709. * Returns a default uvs based on the mapping type of the cube texture.
  8710. *
  8711. * @return {Node<vec3>} The default uv attribute.
  8712. */
  8713. getDefaultUV() {
  8714. const texture = this.value;
  8715. if ( texture.mapping === CubeReflectionMapping ) {
  8716. return reflectVector;
  8717. } else if ( texture.mapping === CubeRefractionMapping ) {
  8718. return refractVector;
  8719. } else {
  8720. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8721. return vec3( 0, 0, 0 );
  8722. }
  8723. }
  8724. /**
  8725. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8726. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8727. *
  8728. * @param {boolean} value - The update toggle.
  8729. */
  8730. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8731. /**
  8732. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8733. * to modify the uv node for correct sampling.
  8734. *
  8735. * @param {NodeBuilder} builder - The current node builder.
  8736. * @param {Node} uvNode - The uv node to setup.
  8737. * @return {Node} The updated uv node.
  8738. */
  8739. setupUV( builder, uvNode ) {
  8740. const texture = this.value;
  8741. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8742. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  8743. }
  8744. return materialEnvRotation.mul( uvNode );
  8745. }
  8746. /**
  8747. * Generates the uv code snippet.
  8748. *
  8749. * @param {NodeBuilder} builder - The current node builder.
  8750. * @param {Node} cubeUV - The uv node to generate code for.
  8751. * @return {string} The generated code snippet.
  8752. */
  8753. generateUV( builder, cubeUV ) {
  8754. return cubeUV.build( builder, 'vec3' );
  8755. }
  8756. }
  8757. /**
  8758. * TSL function for creating a cube texture node.
  8759. *
  8760. * @tsl
  8761. * @function
  8762. * @param {CubeTexture} value - The cube texture.
  8763. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8764. * @param {?Node<int>} [levelNode=null] - The level node.
  8765. * @param {?Node<float>} [biasNode=null] - The bias node.
  8766. * @returns {CubeTextureNode}
  8767. */
  8768. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  8769. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8770. /**
  8771. * This class is only relevant if the referenced property is array-like.
  8772. * In this case, `ReferenceElementNode` allows to refer to a specific
  8773. * element inside the data structure via an index.
  8774. *
  8775. * @augments ArrayElementNode
  8776. */
  8777. class ReferenceElementNode extends ArrayElementNode {
  8778. static get type() {
  8779. return 'ReferenceElementNode';
  8780. }
  8781. /**
  8782. * Constructs a new reference element node.
  8783. *
  8784. * @param {?ReferenceNode} referenceNode - The reference node.
  8785. * @param {Node} indexNode - The index node that defines the element access.
  8786. */
  8787. constructor( referenceNode, indexNode ) {
  8788. super( referenceNode, indexNode );
  8789. /**
  8790. * Similar to {@link ReferenceNode#reference}, an additional
  8791. * property references to the current node.
  8792. *
  8793. * @type {?ReferenceNode}
  8794. * @default null
  8795. */
  8796. this.referenceNode = referenceNode;
  8797. /**
  8798. * This flag can be used for type testing.
  8799. *
  8800. * @type {boolean}
  8801. * @readonly
  8802. * @default true
  8803. */
  8804. this.isReferenceElementNode = true;
  8805. }
  8806. /**
  8807. * This method is overwritten since the node type is inferred from
  8808. * the uniform type of the reference node.
  8809. *
  8810. * @return {string} The node type.
  8811. */
  8812. getNodeType() {
  8813. return this.referenceNode.uniformType;
  8814. }
  8815. generate( builder ) {
  8816. const snippet = super.generate( builder );
  8817. const arrayType = this.referenceNode.getNodeType();
  8818. const elementType = this.getNodeType();
  8819. return builder.format( snippet, arrayType, elementType );
  8820. }
  8821. }
  8822. /**
  8823. * This type of node establishes a reference to a property of another object.
  8824. * In this way, the value of the node is automatically linked to the value of
  8825. * referenced object. Reference nodes internally represent the linked value
  8826. * as a uniform.
  8827. *
  8828. * @augments Node
  8829. */
  8830. class ReferenceNode extends Node {
  8831. static get type() {
  8832. return 'ReferenceNode';
  8833. }
  8834. /**
  8835. * Constructs a new reference node.
  8836. *
  8837. * @param {string} property - The name of the property the node refers to.
  8838. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  8839. * @param {?Object} [object=null] - The object the property belongs to.
  8840. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8841. */
  8842. constructor( property, uniformType, object = null, count = null ) {
  8843. super();
  8844. /**
  8845. * The name of the property the node refers to.
  8846. *
  8847. * @type {string}
  8848. */
  8849. this.property = property;
  8850. /**
  8851. * The uniform type that should be used to represent the property value.
  8852. *
  8853. * @type {string}
  8854. */
  8855. this.uniformType = uniformType;
  8856. /**
  8857. * The object the property belongs to.
  8858. *
  8859. * @type {?Object}
  8860. * @default null
  8861. */
  8862. this.object = object;
  8863. /**
  8864. * When the linked property is an array, this parameter defines its length.
  8865. *
  8866. * @type {?number}
  8867. * @default null
  8868. */
  8869. this.count = count;
  8870. /**
  8871. * The property name might have dots so nested properties can be referred.
  8872. * The hierarchy of the names is stored inside this array.
  8873. *
  8874. * @type {Array<string>}
  8875. */
  8876. this.properties = property.split( '.' );
  8877. /**
  8878. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  8879. * since the final reference might be updated from calling code.
  8880. *
  8881. * @type {?Object}
  8882. * @default null
  8883. */
  8884. this.reference = object;
  8885. /**
  8886. * The uniform node that holds the value of the reference node.
  8887. *
  8888. * @type {UniformNode}
  8889. * @default null
  8890. */
  8891. this.node = null;
  8892. /**
  8893. * The uniform group of the internal uniform.
  8894. *
  8895. * @type {UniformGroupNode}
  8896. * @default null
  8897. */
  8898. this.group = null;
  8899. /**
  8900. * An optional label of the internal uniform node.
  8901. *
  8902. * @type {?string}
  8903. * @default null
  8904. */
  8905. this.name = null;
  8906. /**
  8907. * Overwritten since reference nodes are updated per object.
  8908. *
  8909. * @type {string}
  8910. * @default 'object'
  8911. */
  8912. this.updateType = NodeUpdateType.OBJECT;
  8913. }
  8914. /**
  8915. * When the referred property is array-like, this method can be used
  8916. * to access elements via an index node.
  8917. *
  8918. * @param {IndexNode} indexNode - indexNode.
  8919. * @return {ReferenceElementNode} A reference to an element.
  8920. */
  8921. element( indexNode ) {
  8922. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8923. }
  8924. /**
  8925. * Sets the uniform group for this reference node.
  8926. *
  8927. * @param {UniformGroupNode} group - The uniform group to set.
  8928. * @return {ReferenceNode} A reference to this node.
  8929. */
  8930. setGroup( group ) {
  8931. this.group = group;
  8932. return this;
  8933. }
  8934. /**
  8935. * Sets the label for the internal uniform.
  8936. *
  8937. * @param {string} name - The label to set.
  8938. * @return {ReferenceNode} A reference to this node.
  8939. */
  8940. label( name ) {
  8941. this.name = name;
  8942. return this;
  8943. }
  8944. /**
  8945. * Sets the node type which automatically defines the internal
  8946. * uniform type.
  8947. *
  8948. * @param {string} uniformType - The type to set.
  8949. */
  8950. setNodeType( uniformType ) {
  8951. let node = null;
  8952. if ( this.count !== null ) {
  8953. node = buffer( null, uniformType, this.count );
  8954. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8955. node = uniformArray( null, uniformType );
  8956. } else if ( uniformType === 'texture' ) {
  8957. node = texture( null );
  8958. } else if ( uniformType === 'cubeTexture' ) {
  8959. node = cubeTexture( null );
  8960. } else {
  8961. node = uniform( null, uniformType );
  8962. }
  8963. if ( this.group !== null ) {
  8964. node.setGroup( this.group );
  8965. }
  8966. if ( this.name !== null ) node.label( this.name );
  8967. this.node = node.getSelf();
  8968. }
  8969. /**
  8970. * This method is overwritten since the node type is inferred from
  8971. * the type of the reference node.
  8972. *
  8973. * @param {NodeBuilder} builder - The current node builder.
  8974. * @return {string} The node type.
  8975. */
  8976. getNodeType( builder ) {
  8977. if ( this.node === null ) {
  8978. this.updateReference( builder );
  8979. this.updateValue();
  8980. }
  8981. return this.node.getNodeType( builder );
  8982. }
  8983. /**
  8984. * Returns the property value from the given referred object.
  8985. *
  8986. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8987. * @return {any} The value.
  8988. */
  8989. getValueFromReference( object = this.reference ) {
  8990. const { properties } = this;
  8991. let value = object[ properties[ 0 ] ];
  8992. for ( let i = 1; i < properties.length; i ++ ) {
  8993. value = value[ properties[ i ] ];
  8994. }
  8995. return value;
  8996. }
  8997. /**
  8998. * Allows to update the reference based on the given state. The state is only
  8999. * evaluated {@link ReferenceNode#object} is not set.
  9000. *
  9001. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9002. * @return {Object} The updated reference.
  9003. */
  9004. updateReference( state ) {
  9005. this.reference = this.object !== null ? this.object : state.object;
  9006. return this.reference;
  9007. }
  9008. /**
  9009. * The output of the reference node is the internal uniform node.
  9010. *
  9011. * @param {NodeBuilder} builder - The current node builder.
  9012. * @return {UniformNode} The output node.
  9013. */
  9014. setup( /* builder */ ) {
  9015. this.updateValue();
  9016. return this.node;
  9017. }
  9018. /**
  9019. * Overwritten to update the internal uniform value.
  9020. *
  9021. * @param {NodeFrame} frame - A reference to the current node frame.
  9022. */
  9023. update( /*frame*/ ) {
  9024. this.updateValue();
  9025. }
  9026. /**
  9027. * Retrieves the value from the referred object property and uses it
  9028. * to updated the internal uniform.
  9029. */
  9030. updateValue() {
  9031. if ( this.node === null ) this.setNodeType( this.uniformType );
  9032. const value = this.getValueFromReference();
  9033. if ( Array.isArray( value ) ) {
  9034. this.node.array = value;
  9035. } else {
  9036. this.node.value = value;
  9037. }
  9038. }
  9039. }
  9040. /**
  9041. * TSL function for creating a reference node.
  9042. *
  9043. * @tsl
  9044. * @function
  9045. * @param {string} name - The name of the property the node refers to.
  9046. * @param {string} type - The uniform type that should be used to represent the property value.
  9047. * @param {?Object} [object] - The object the property belongs to.
  9048. * @returns {ReferenceNode}
  9049. */
  9050. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9051. /**
  9052. * TSL function for creating a reference node. Use this function if you want need a reference
  9053. * to an array-like property that should be represented as a uniform buffer.
  9054. *
  9055. * @tsl
  9056. * @function
  9057. * @param {string} name - The name of the property the node refers to.
  9058. * @param {string} type - The uniform type that should be used to represent the property value.
  9059. * @param {number} count - The number of value inside the array-like object.
  9060. * @param {Object} object - An array-like object the property belongs to.
  9061. * @returns {ReferenceNode}
  9062. */
  9063. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9064. /**
  9065. * This node is a special type of reference node which is intended
  9066. * for linking material properties with node values.
  9067. * ```js
  9068. * const opacityNode = materialReference( 'opacity', 'float', material );
  9069. * ```
  9070. * When changing `material.opacity`, the node value of `opacityNode` will
  9071. * automatically be updated.
  9072. *
  9073. * @augments ReferenceNode
  9074. */
  9075. class MaterialReferenceNode extends ReferenceNode {
  9076. static get type() {
  9077. return 'MaterialReferenceNode';
  9078. }
  9079. /**
  9080. * Constructs a new material reference node.
  9081. *
  9082. * @param {string} property - The name of the property the node refers to.
  9083. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9084. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9085. * the node refers to the material of the current rendered object.
  9086. */
  9087. constructor( property, inputType, material = null ) {
  9088. super( property, inputType, material );
  9089. /**
  9090. * The material the property belongs to. When no material is set,
  9091. * the node refers to the material of the current rendered object.
  9092. *
  9093. * @type {?Material}
  9094. * @default null
  9095. */
  9096. this.material = material;
  9097. /**
  9098. * This flag can be used for type testing.
  9099. *
  9100. * @type {boolean}
  9101. * @readonly
  9102. * @default true
  9103. */
  9104. this.isMaterialReferenceNode = true;
  9105. }
  9106. /**
  9107. * Updates the reference based on the given state. The state is only evaluated
  9108. * {@link MaterialReferenceNode#material} is not set.
  9109. *
  9110. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9111. * @return {Object} The updated reference.
  9112. */
  9113. updateReference( state ) {
  9114. this.reference = this.material !== null ? this.material : state.material;
  9115. return this.reference;
  9116. }
  9117. }
  9118. /**
  9119. * TSL function for creating a material reference node.
  9120. *
  9121. * @tsl
  9122. * @function
  9123. * @param {string} name - The name of the property the node refers to.
  9124. * @param {string} type - The uniform type that should be used to represent the property value.
  9125. * @param {?Material} [material=null] - The material the property belongs to.
  9126. * When no material is set, the node refers to the material of the current rendered object.
  9127. * @returns {MaterialReferenceNode}
  9128. */
  9129. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  9130. /**
  9131. * TSL object that represents the tangent attribute of the current rendered object.
  9132. *
  9133. * @tsl
  9134. * @type {Node<vec4>}
  9135. */
  9136. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  9137. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  9138. builder.geometry.computeTangents();
  9139. }
  9140. return attribute( 'tangent', 'vec4' );
  9141. } )();
  9142. /**
  9143. * TSL object that represents the vertex tangent in local space of the current rendered object.
  9144. *
  9145. * @tsl
  9146. * @type {Node<vec3>}
  9147. */
  9148. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  9149. /**
  9150. * TSL object that represents the vertex tangent in view space of the current rendered object.
  9151. *
  9152. * @tsl
  9153. * @type {Node<vec3>}
  9154. */
  9155. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  9156. /**
  9157. * TSL object that represents the vertex tangent in world space of the current rendered object.
  9158. *
  9159. * @tsl
  9160. * @type {Node<vec3>}
  9161. */
  9162. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  9163. /**
  9164. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  9165. *
  9166. * @tsl
  9167. * @type {Node<vec3>}
  9168. */
  9169. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  9170. /**
  9171. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  9172. *
  9173. * @tsl
  9174. * @type {Node<vec3>}
  9175. */
  9176. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  9177. /**
  9178. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  9179. *
  9180. * @tsl
  9181. * @private
  9182. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  9183. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  9184. * @returns {Node<vec3>} The bitangent node.
  9185. */
  9186. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  9187. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  9188. if ( builder.material.flatShading !== true ) {
  9189. bitangent = varying( crossNormalTangent, varyingName );
  9190. }
  9191. return bitangent;
  9192. } ).once();
  9193. /**
  9194. * TSL object that represents the bitangent attribute of the current rendered object.
  9195. *
  9196. * @tsl
  9197. * @type {Node<vec3>}
  9198. */
  9199. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  9200. /**
  9201. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  9202. *
  9203. * @tsl
  9204. * @type {Node<vec3>}
  9205. */
  9206. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  9207. /**
  9208. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  9209. *
  9210. * @tsl
  9211. * @type {Node<vec3>}
  9212. */
  9213. const bitangentView = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  9214. /**
  9215. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  9216. *
  9217. * @tsl
  9218. * @type {Node<vec3>}
  9219. */
  9220. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  9221. /**
  9222. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  9223. *
  9224. * @tsl
  9225. * @type {Node<vec3>}
  9226. */
  9227. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ), 'v_transformedBitangentView' ).normalize().toVar( 'transformedBitangentView' );
  9228. /**
  9229. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  9230. *
  9231. * @tsl
  9232. * @type {Node<vec4>}
  9233. */
  9234. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  9235. /**
  9236. * TSL object that represents the TBN matrix in view space.
  9237. *
  9238. * @tsl
  9239. * @type {Node<mat3>}
  9240. */
  9241. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  9242. /**
  9243. * TSL object that represents the parallax direction.
  9244. *
  9245. * @tsl
  9246. * @type {Node<mat3>}
  9247. */
  9248. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  9249. /**
  9250. * TSL function for computing parallax uv coordinates.
  9251. *
  9252. * @tsl
  9253. * @function
  9254. * @param {Node<vec2>} uv - A uv node.
  9255. * @param {Node<vec2>} scale - A scale node.
  9256. * @returns {Node<vec2>} Parallax uv coordinates.
  9257. */
  9258. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  9259. /**
  9260. * TSL function for computing bent normals.
  9261. *
  9262. * @tsl
  9263. * @function
  9264. * @returns {Node<vec3>} Bent normals.
  9265. */
  9266. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  9267. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  9268. let bentNormal = anisotropyB.cross( positionViewDirection );
  9269. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  9270. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  9271. return bentNormal;
  9272. } )();
  9273. // Normal Mapping Without Precomputed Tangents
  9274. // http://www.thetenthplanet.de/archives/1180
  9275. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  9276. const { eye_pos, surf_norm, mapN, uv } = inputs;
  9277. const q0 = eye_pos.dFdx();
  9278. const q1 = eye_pos.dFdy();
  9279. const st0 = uv.dFdx();
  9280. const st1 = uv.dFdy();
  9281. const N = surf_norm; // normalized
  9282. const q1perp = q1.cross( N );
  9283. const q0perp = N.cross( q0 );
  9284. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  9285. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  9286. const det = T.dot( T ).max( B.dot( B ) );
  9287. const scale = faceDirection.mul( det.inverseSqrt() );
  9288. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  9289. } );
  9290. /**
  9291. * This class can be used for applying normals maps to materials.
  9292. *
  9293. * ```js
  9294. * material.normalNode = normalMap( texture( normalTex ) );
  9295. * ```
  9296. *
  9297. * @augments TempNode
  9298. */
  9299. class NormalMapNode extends TempNode {
  9300. static get type() {
  9301. return 'NormalMapNode';
  9302. }
  9303. /**
  9304. * Constructs a new normal map node.
  9305. *
  9306. * @param {Node<vec3>} node - Represents the normal map data.
  9307. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9308. */
  9309. constructor( node, scaleNode = null ) {
  9310. super( 'vec3' );
  9311. /**
  9312. * Represents the normal map data.
  9313. *
  9314. * @type {Node<vec3>}
  9315. */
  9316. this.node = node;
  9317. /**
  9318. * Controls the intensity of the effect.
  9319. *
  9320. * @type {?Node<vec2>}
  9321. * @default null
  9322. */
  9323. this.scaleNode = scaleNode;
  9324. /**
  9325. * The normal map type.
  9326. *
  9327. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  9328. * @default TangentSpaceNormalMap
  9329. */
  9330. this.normalMapType = TangentSpaceNormalMap;
  9331. }
  9332. setup( builder ) {
  9333. const { normalMapType, scaleNode } = this;
  9334. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  9335. if ( scaleNode !== null ) {
  9336. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  9337. }
  9338. let outputNode = null;
  9339. if ( normalMapType === ObjectSpaceNormalMap ) {
  9340. outputNode = transformNormalToView( normalMap );
  9341. } else if ( normalMapType === TangentSpaceNormalMap ) {
  9342. const tangent = builder.hasGeometryAttribute( 'tangent' );
  9343. if ( tangent === true ) {
  9344. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  9345. } else {
  9346. outputNode = perturbNormal2Arb( {
  9347. eye_pos: positionView,
  9348. surf_norm: normalView,
  9349. mapN: normalMap,
  9350. uv: uv()
  9351. } );
  9352. }
  9353. }
  9354. return outputNode;
  9355. }
  9356. }
  9357. /**
  9358. * TSL function for creating a normal map node.
  9359. *
  9360. * @tsl
  9361. * @function
  9362. * @param {Node<vec3>} node - Represents the normal map data.
  9363. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9364. * @returns {NormalMapNode}
  9365. */
  9366. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  9367. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  9368. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  9369. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  9370. // It's used to preserve the same TextureNode instance
  9371. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  9372. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  9373. return vec2(
  9374. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  9375. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  9376. ).mul( bumpScale );
  9377. } );
  9378. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9379. const perturbNormalArb = Fn( ( inputs ) => {
  9380. const { surf_pos, surf_norm, dHdxy } = inputs;
  9381. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  9382. const vSigmaX = surf_pos.dFdx().normalize();
  9383. const vSigmaY = surf_pos.dFdy().normalize();
  9384. const vN = surf_norm; // normalized
  9385. const R1 = vSigmaY.cross( vN );
  9386. const R2 = vN.cross( vSigmaX );
  9387. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  9388. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  9389. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  9390. } );
  9391. /**
  9392. * This class can be used for applying bump maps to materials.
  9393. *
  9394. * ```js
  9395. * material.normalNode = bumpMap( texture( bumpTex ) );
  9396. * ```
  9397. *
  9398. * @augments TempNode
  9399. */
  9400. class BumpMapNode extends TempNode {
  9401. static get type() {
  9402. return 'BumpMapNode';
  9403. }
  9404. /**
  9405. * Constructs a new bump map node.
  9406. *
  9407. * @param {Node<float>} textureNode - Represents the bump map data.
  9408. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9409. */
  9410. constructor( textureNode, scaleNode = null ) {
  9411. super( 'vec3' );
  9412. /**
  9413. * Represents the bump map data.
  9414. *
  9415. * @type {Node<float>}
  9416. */
  9417. this.textureNode = textureNode;
  9418. /**
  9419. * Controls the intensity of the bump effect.
  9420. *
  9421. * @type {?Node<float>}
  9422. * @default null
  9423. */
  9424. this.scaleNode = scaleNode;
  9425. }
  9426. setup() {
  9427. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  9428. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  9429. return perturbNormalArb( {
  9430. surf_pos: positionView,
  9431. surf_norm: normalView,
  9432. dHdxy
  9433. } );
  9434. }
  9435. }
  9436. /**
  9437. * TSL function for creating a bump map node.
  9438. *
  9439. * @tsl
  9440. * @function
  9441. * @param {Node<float>} textureNode - Represents the bump map data.
  9442. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9443. * @returns {BumpMapNode}
  9444. */
  9445. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  9446. const _propertyCache = new Map();
  9447. /**
  9448. * This class should simplify the node access to material properties.
  9449. * It internal uses reference nodes to make sure changes to material
  9450. * properties are automatically reflected to predefined TSL objects
  9451. * like e.g. `materialColor`.
  9452. *
  9453. * @augments Node
  9454. */
  9455. class MaterialNode extends Node {
  9456. static get type() {
  9457. return 'MaterialNode';
  9458. }
  9459. /**
  9460. * Constructs a new material node.
  9461. *
  9462. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  9463. */
  9464. constructor( scope ) {
  9465. super();
  9466. /**
  9467. * The scope defines what material property is referred by the node.
  9468. *
  9469. * @type {string}
  9470. */
  9471. this.scope = scope;
  9472. }
  9473. /**
  9474. * Returns a cached reference node for the given property and type.
  9475. *
  9476. * @param {string} property - The name of the material property.
  9477. * @param {string} type - The uniform type of the property.
  9478. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9479. */
  9480. getCache( property, type ) {
  9481. let node = _propertyCache.get( property );
  9482. if ( node === undefined ) {
  9483. node = materialReference( property, type );
  9484. _propertyCache.set( property, node );
  9485. }
  9486. return node;
  9487. }
  9488. /**
  9489. * Returns a float-typed material reference node for the given property name.
  9490. *
  9491. * @param {string} property - The name of the material property.
  9492. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  9493. */
  9494. getFloat( property ) {
  9495. return this.getCache( property, 'float' );
  9496. }
  9497. /**
  9498. * Returns a color-typed material reference node for the given property name.
  9499. *
  9500. * @param {string} property - The name of the material property.
  9501. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  9502. */
  9503. getColor( property ) {
  9504. return this.getCache( property, 'color' );
  9505. }
  9506. /**
  9507. * Returns a texture-typed material reference node for the given property name.
  9508. *
  9509. * @param {string} property - The name of the material property.
  9510. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9511. */
  9512. getTexture( property ) {
  9513. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  9514. }
  9515. /**
  9516. * The node setup is done depending on the selected scope. Multiple material properties
  9517. * might be grouped into a single node composition if they logically belong together.
  9518. *
  9519. * @param {NodeBuilder} builder - The current node builder.
  9520. * @return {Node} The node representing the selected scope.
  9521. */
  9522. setup( builder ) {
  9523. const material = builder.context.material;
  9524. const scope = this.scope;
  9525. let node = null;
  9526. if ( scope === MaterialNode.COLOR ) {
  9527. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  9528. if ( material.map && material.map.isTexture === true ) {
  9529. node = colorNode.mul( this.getTexture( 'map' ) );
  9530. } else {
  9531. node = colorNode;
  9532. }
  9533. } else if ( scope === MaterialNode.OPACITY ) {
  9534. const opacityNode = this.getFloat( scope );
  9535. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9536. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9537. } else {
  9538. node = opacityNode;
  9539. }
  9540. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9541. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9542. node = this.getTexture( 'specular' ).r;
  9543. } else {
  9544. node = float( 1 );
  9545. }
  9546. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9547. const specularIntensityNode = this.getFloat( scope );
  9548. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9549. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9550. } else {
  9551. node = specularIntensityNode;
  9552. }
  9553. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9554. const specularColorNode = this.getColor( scope );
  9555. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9556. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9557. } else {
  9558. node = specularColorNode;
  9559. }
  9560. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9561. const roughnessNode = this.getFloat( scope );
  9562. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9563. node = roughnessNode.mul( this.getTexture( scope ).g );
  9564. } else {
  9565. node = roughnessNode;
  9566. }
  9567. } else if ( scope === MaterialNode.METALNESS ) {
  9568. const metalnessNode = this.getFloat( scope );
  9569. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9570. node = metalnessNode.mul( this.getTexture( scope ).b );
  9571. } else {
  9572. node = metalnessNode;
  9573. }
  9574. } else if ( scope === MaterialNode.EMISSIVE ) {
  9575. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9576. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9577. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9578. node = emissiveNode.mul( this.getTexture( scope ) );
  9579. } else {
  9580. node = emissiveNode;
  9581. }
  9582. } else if ( scope === MaterialNode.NORMAL ) {
  9583. if ( material.normalMap ) {
  9584. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9585. node.normalMapType = material.normalMapType;
  9586. } else if ( material.bumpMap ) {
  9587. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9588. } else {
  9589. node = normalView;
  9590. }
  9591. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9592. const clearcoatNode = this.getFloat( scope );
  9593. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9594. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9595. } else {
  9596. node = clearcoatNode;
  9597. }
  9598. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9599. const clearcoatRoughnessNode = this.getFloat( scope );
  9600. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9601. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9602. } else {
  9603. node = clearcoatRoughnessNode;
  9604. }
  9605. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9606. if ( material.clearcoatNormalMap ) {
  9607. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9608. } else {
  9609. node = normalView;
  9610. }
  9611. } else if ( scope === MaterialNode.SHEEN ) {
  9612. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9613. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9614. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9615. } else {
  9616. node = sheenNode;
  9617. }
  9618. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9619. const sheenRoughnessNode = this.getFloat( scope );
  9620. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9621. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9622. } else {
  9623. node = sheenRoughnessNode;
  9624. }
  9625. node = node.clamp( 0.07, 1.0 );
  9626. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9627. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9628. const anisotropyPolar = this.getTexture( scope );
  9629. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9630. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9631. } else {
  9632. node = materialAnisotropyVector;
  9633. }
  9634. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9635. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9636. if ( material.iridescenceThicknessMap ) {
  9637. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9638. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9639. } else {
  9640. node = iridescenceThicknessMaximum;
  9641. }
  9642. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9643. const transmissionNode = this.getFloat( scope );
  9644. if ( material.transmissionMap ) {
  9645. node = transmissionNode.mul( this.getTexture( scope ).r );
  9646. } else {
  9647. node = transmissionNode;
  9648. }
  9649. } else if ( scope === MaterialNode.THICKNESS ) {
  9650. const thicknessNode = this.getFloat( scope );
  9651. if ( material.thicknessMap ) {
  9652. node = thicknessNode.mul( this.getTexture( scope ).g );
  9653. } else {
  9654. node = thicknessNode;
  9655. }
  9656. } else if ( scope === MaterialNode.IOR ) {
  9657. node = this.getFloat( scope );
  9658. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9659. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9660. } else if ( scope === MaterialNode.AO ) {
  9661. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9662. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  9663. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  9664. } else {
  9665. const outputType = this.getNodeType( builder );
  9666. node = this.getCache( scope, outputType );
  9667. }
  9668. return node;
  9669. }
  9670. }
  9671. MaterialNode.ALPHA_TEST = 'alphaTest';
  9672. MaterialNode.COLOR = 'color';
  9673. MaterialNode.OPACITY = 'opacity';
  9674. MaterialNode.SHININESS = 'shininess';
  9675. MaterialNode.SPECULAR = 'specular';
  9676. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  9677. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  9678. MaterialNode.SPECULAR_COLOR = 'specularColor';
  9679. MaterialNode.REFLECTIVITY = 'reflectivity';
  9680. MaterialNode.ROUGHNESS = 'roughness';
  9681. MaterialNode.METALNESS = 'metalness';
  9682. MaterialNode.NORMAL = 'normal';
  9683. MaterialNode.CLEARCOAT = 'clearcoat';
  9684. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  9685. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  9686. MaterialNode.EMISSIVE = 'emissive';
  9687. MaterialNode.ROTATION = 'rotation';
  9688. MaterialNode.SHEEN = 'sheen';
  9689. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  9690. MaterialNode.ANISOTROPY = 'anisotropy';
  9691. MaterialNode.IRIDESCENCE = 'iridescence';
  9692. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  9693. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  9694. MaterialNode.IOR = 'ior';
  9695. MaterialNode.TRANSMISSION = 'transmission';
  9696. MaterialNode.THICKNESS = 'thickness';
  9697. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  9698. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  9699. MaterialNode.LINE_SCALE = 'scale';
  9700. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  9701. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  9702. MaterialNode.LINE_WIDTH = 'linewidth';
  9703. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  9704. MaterialNode.POINT_SIZE = 'size';
  9705. MaterialNode.DISPERSION = 'dispersion';
  9706. MaterialNode.LIGHT_MAP = 'light';
  9707. MaterialNode.AO = 'ao';
  9708. /**
  9709. * TSL object that represents alpha test of the current material.
  9710. *
  9711. * @tsl
  9712. * @type {Node<float>}
  9713. */
  9714. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  9715. /**
  9716. * TSL object that represents the diffuse color of the current material.
  9717. * The value is composed via `color` * `map`.
  9718. *
  9719. * @tsl
  9720. * @type {Node<vec3>}
  9721. */
  9722. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  9723. /**
  9724. * TSL object that represents the shininess of the current material.
  9725. *
  9726. * @tsl
  9727. * @type {Node<float>}
  9728. */
  9729. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9730. /**
  9731. * TSL object that represents the emissive color of the current material.
  9732. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9733. *
  9734. * @tsl
  9735. * @type {Node<vec3>}
  9736. */
  9737. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9738. /**
  9739. * TSL object that represents the opacity of the current material.
  9740. * The value is composed via `opacity` * `alphaMap`.
  9741. *
  9742. * @tsl
  9743. * @type {Node<float>}
  9744. */
  9745. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9746. /**
  9747. * TSL object that represents the specular of the current material.
  9748. *
  9749. * @tsl
  9750. * @type {Node<vec3>}
  9751. */
  9752. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9753. /**
  9754. * TSL object that represents the specular intensity of the current material.
  9755. * The value is composed via `specularIntensity` * `specularMap.a`.
  9756. *
  9757. * @tsl
  9758. * @type {Node<float>}
  9759. */
  9760. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9761. /**
  9762. * TSL object that represents the specular color of the current material.
  9763. * The value is composed via `specularColor` * `specularMap.rgb`.
  9764. *
  9765. * @tsl
  9766. * @type {Node<vec3>}
  9767. */
  9768. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9769. /**
  9770. * TSL object that represents the specular strength of the current material.
  9771. * The value is composed via `specularMap.r`.
  9772. *
  9773. * @tsl
  9774. * @type {Node<float>}
  9775. */
  9776. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9777. /**
  9778. * TSL object that represents the reflectivity of the current material.
  9779. *
  9780. * @tsl
  9781. * @type {Node<float>}
  9782. */
  9783. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9784. /**
  9785. * TSL object that represents the roughness of the current material.
  9786. * The value is composed via `roughness` * `roughnessMap.g`.
  9787. *
  9788. * @tsl
  9789. * @type {Node<float>}
  9790. */
  9791. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9792. /**
  9793. * TSL object that represents the metalness of the current material.
  9794. * The value is composed via `metalness` * `metalnessMap.b`.
  9795. *
  9796. * @tsl
  9797. * @type {Node<float>}
  9798. */
  9799. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9800. /**
  9801. * TSL object that represents the normal of the current material.
  9802. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9803. *
  9804. * @tsl
  9805. * @type {Node<vec3>}
  9806. */
  9807. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9808. /**
  9809. * TSL object that represents the clearcoat of the current material.
  9810. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9811. *
  9812. * @tsl
  9813. * @type {Node<float>}
  9814. */
  9815. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9816. /**
  9817. * TSL object that represents the clearcoat roughness of the current material.
  9818. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9819. *
  9820. * @tsl
  9821. * @type {Node<float>}
  9822. */
  9823. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9824. /**
  9825. * TSL object that represents the clearcoat normal of the current material.
  9826. * The value will be either `clearcoatNormalMap` or `normalView`.
  9827. *
  9828. * @tsl
  9829. * @type {Node<vec3>}
  9830. */
  9831. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9832. /**
  9833. * TSL object that represents the rotation of the current sprite material.
  9834. *
  9835. * @tsl
  9836. * @type {Node<float>}
  9837. */
  9838. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9839. /**
  9840. * TSL object that represents the sheen color of the current material.
  9841. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9842. *
  9843. * @tsl
  9844. * @type {Node<vec3>}
  9845. */
  9846. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9847. /**
  9848. * TSL object that represents the sheen roughness of the current material.
  9849. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9850. *
  9851. * @tsl
  9852. * @type {Node<float>}
  9853. */
  9854. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9855. /**
  9856. * TSL object that represents the anisotropy of the current material.
  9857. *
  9858. * @tsl
  9859. * @type {Node<vec2>}
  9860. */
  9861. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9862. /**
  9863. * TSL object that represents the iridescence of the current material.
  9864. *
  9865. * @tsl
  9866. * @type {Node<float>}
  9867. */
  9868. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9869. /**
  9870. * TSL object that represents the iridescence IOR of the current material.
  9871. *
  9872. * @tsl
  9873. * @type {Node<float>}
  9874. */
  9875. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9876. /**
  9877. * TSL object that represents the iridescence thickness of the current material.
  9878. *
  9879. * @tsl
  9880. * @type {Node<float>}
  9881. */
  9882. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9883. /**
  9884. * TSL object that represents the transmission of the current material.
  9885. * The value is composed via `transmission` * `transmissionMap.r`.
  9886. *
  9887. * @tsl
  9888. * @type {Node<float>}
  9889. */
  9890. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9891. /**
  9892. * TSL object that represents the thickness of the current material.
  9893. * The value is composed via `thickness` * `thicknessMap.g`.
  9894. *
  9895. * @tsl
  9896. * @type {Node<float>}
  9897. */
  9898. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9899. /**
  9900. * TSL object that represents the IOR of the current material.
  9901. *
  9902. * @tsl
  9903. * @type {Node<float>}
  9904. */
  9905. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  9906. /**
  9907. * TSL object that represents the attenuation distance of the current material.
  9908. *
  9909. * @tsl
  9910. * @type {Node<float>}
  9911. */
  9912. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  9913. /**
  9914. * TSL object that represents the attenuation color of the current material.
  9915. *
  9916. * @tsl
  9917. * @type {Node<vec3>}
  9918. */
  9919. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  9920. /**
  9921. * TSL object that represents the scale of the current dashed line material.
  9922. *
  9923. * @tsl
  9924. * @type {Node<float>}
  9925. */
  9926. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  9927. /**
  9928. * TSL object that represents the dash size of the current dashed line material.
  9929. *
  9930. * @tsl
  9931. * @type {Node<float>}
  9932. */
  9933. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  9934. /**
  9935. * TSL object that represents the gap size of the current dashed line material.
  9936. *
  9937. * @tsl
  9938. * @type {Node<float>}
  9939. */
  9940. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  9941. /**
  9942. * TSL object that represents the line width of the current line material.
  9943. *
  9944. * @tsl
  9945. * @type {Node<float>}
  9946. */
  9947. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  9948. /**
  9949. * TSL object that represents the dash offset of the current line material.
  9950. *
  9951. * @tsl
  9952. * @type {Node<float>}
  9953. */
  9954. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  9955. /**
  9956. * TSL object that represents the point size of the current points material.
  9957. *
  9958. * @tsl
  9959. * @type {Node<float>}
  9960. */
  9961. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9962. /**
  9963. * TSL object that represents the dispersion of the current material.
  9964. *
  9965. * @tsl
  9966. * @type {Node<float>}
  9967. */
  9968. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9969. /**
  9970. * TSL object that represents the light map of the current material.
  9971. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9972. *
  9973. * @tsl
  9974. * @type {Node<vec3>}
  9975. */
  9976. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9977. /**
  9978. * TSL object that represents the ambient occlusion map of the current material.
  9979. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9980. *
  9981. * @tsl
  9982. * @type {Node<float>}
  9983. */
  9984. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9985. /**
  9986. * TSL object that represents the anisotropy vector of the current material.
  9987. *
  9988. * @tsl
  9989. * @type {Node<vec2>}
  9990. */
  9991. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9992. return frame.material;
  9993. } ).onRenderUpdate( function ( { material } ) {
  9994. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9995. } );
  9996. /**
  9997. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9998. *
  9999. * @tsl
  10000. * @type {VaryingNode<vec4>}
  10001. */
  10002. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10003. return builder.context.setupModelViewProjection();
  10004. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10005. /**
  10006. * This class represents shader indices of different types. The following predefined node
  10007. * objects cover frequent use cases:
  10008. *
  10009. * - `vertexIndex`: The index of a vertex within a mesh.
  10010. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10011. * - `drawIndex`: The index of a draw call.
  10012. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10013. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10014. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10015. *
  10016. * @augments Node
  10017. */
  10018. class IndexNode extends Node {
  10019. static get type() {
  10020. return 'IndexNode';
  10021. }
  10022. /**
  10023. * Constructs a new index node.
  10024. *
  10025. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10026. */
  10027. constructor( scope ) {
  10028. super( 'uint' );
  10029. /**
  10030. * The scope of the index node.
  10031. *
  10032. * @type {string}
  10033. */
  10034. this.scope = scope;
  10035. /**
  10036. * This flag can be used for type testing.
  10037. *
  10038. * @type {boolean}
  10039. * @readonly
  10040. * @default true
  10041. */
  10042. this.isIndexNode = true;
  10043. }
  10044. generate( builder ) {
  10045. const nodeType = this.getNodeType( builder );
  10046. const scope = this.scope;
  10047. let propertyName;
  10048. if ( scope === IndexNode.VERTEX ) {
  10049. propertyName = builder.getVertexIndex();
  10050. } else if ( scope === IndexNode.INSTANCE ) {
  10051. propertyName = builder.getInstanceIndex();
  10052. } else if ( scope === IndexNode.DRAW ) {
  10053. propertyName = builder.getDrawIndex();
  10054. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10055. propertyName = builder.getInvocationLocalIndex();
  10056. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10057. propertyName = builder.getInvocationSubgroupIndex();
  10058. } else if ( scope === IndexNode.SUBGROUP ) {
  10059. propertyName = builder.getSubgroupIndex();
  10060. } else {
  10061. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10062. }
  10063. let output;
  10064. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10065. output = propertyName;
  10066. } else {
  10067. const nodeVarying = varying( this );
  10068. output = nodeVarying.build( builder, nodeType );
  10069. }
  10070. return output;
  10071. }
  10072. }
  10073. IndexNode.VERTEX = 'vertex';
  10074. IndexNode.INSTANCE = 'instance';
  10075. IndexNode.SUBGROUP = 'subgroup';
  10076. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10077. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10078. IndexNode.DRAW = 'draw';
  10079. /**
  10080. * TSL object that represents the index of a vertex within a mesh.
  10081. *
  10082. * @tsl
  10083. * @type {IndexNode}
  10084. */
  10085. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10086. /**
  10087. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10088. *
  10089. * @tsl
  10090. * @type {IndexNode}
  10091. */
  10092. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  10093. /**
  10094. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  10095. *
  10096. * @tsl
  10097. * @type {IndexNode}
  10098. */
  10099. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  10100. /**
  10101. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  10102. *
  10103. * @tsl
  10104. * @type {IndexNode}
  10105. */
  10106. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  10107. /**
  10108. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  10109. *
  10110. * @tsl
  10111. * @type {IndexNode}
  10112. */
  10113. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  10114. /**
  10115. * TSL object that represents the index of a draw call.
  10116. *
  10117. * @tsl
  10118. * @type {IndexNode}
  10119. */
  10120. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  10121. /**
  10122. * This node implements the vertex shader logic which is required
  10123. * when rendering 3D objects via instancing. The code makes sure
  10124. * vertex positions, normals and colors can be modified via instanced
  10125. * data.
  10126. *
  10127. * @augments Node
  10128. */
  10129. class InstanceNode extends Node {
  10130. static get type() {
  10131. return 'InstanceNode';
  10132. }
  10133. /**
  10134. * Constructs a new instance node.
  10135. *
  10136. * @param {number} count - The number of instances.
  10137. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10138. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10139. */
  10140. constructor( count, instanceMatrix, instanceColor = null ) {
  10141. super( 'void' );
  10142. /**
  10143. * The number of instances.
  10144. *
  10145. * @type {number}
  10146. */
  10147. this.count = count;
  10148. /**
  10149. * Instanced buffer attribute representing the transformation of instances.
  10150. *
  10151. * @type {InstancedBufferAttribute}
  10152. */
  10153. this.instanceMatrix = instanceMatrix;
  10154. /**
  10155. * Instanced buffer attribute representing the color of instances.
  10156. *
  10157. * @type {InstancedBufferAttribute}
  10158. */
  10159. this.instanceColor = instanceColor;
  10160. /**
  10161. * The node that represents the instance matrix data.
  10162. *
  10163. * @type {?Node}
  10164. */
  10165. this.instanceMatrixNode = null;
  10166. /**
  10167. * The node that represents the instance color data.
  10168. *
  10169. * @type {?Node}
  10170. * @default null
  10171. */
  10172. this.instanceColorNode = null;
  10173. /**
  10174. * The update type is set to `frame` since an update
  10175. * of instanced buffer data must be checked per frame.
  10176. *
  10177. * @type {string}
  10178. * @default 'frame'
  10179. */
  10180. this.updateType = NodeUpdateType.FRAME;
  10181. /**
  10182. * A reference to a buffer that is used by `instanceMatrixNode`.
  10183. *
  10184. * @type {?InstancedInterleavedBuffer}
  10185. */
  10186. this.buffer = null;
  10187. /**
  10188. * A reference to a buffer that is used by `instanceColorNode`.
  10189. *
  10190. * @type {?InstancedBufferAttribute}
  10191. */
  10192. this.bufferColor = null;
  10193. }
  10194. /**
  10195. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10196. * to predefined node variables for accumulation. That follows the same patterns
  10197. * like with morph and skinning nodes.
  10198. *
  10199. * @param {NodeBuilder} builder - The current node builder.
  10200. */
  10201. setup( builder ) {
  10202. const { count, instanceMatrix, instanceColor } = this;
  10203. let { instanceMatrixNode, instanceColorNode } = this;
  10204. if ( instanceMatrixNode === null ) {
  10205. // 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.
  10206. if ( count <= 1000 ) {
  10207. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  10208. } else {
  10209. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  10210. this.buffer = buffer;
  10211. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10212. const instanceBuffers = [
  10213. // F.Signature -> bufferAttribute( array, type, stride, offset )
  10214. bufferFn( buffer, 'vec4', 16, 0 ),
  10215. bufferFn( buffer, 'vec4', 16, 4 ),
  10216. bufferFn( buffer, 'vec4', 16, 8 ),
  10217. bufferFn( buffer, 'vec4', 16, 12 )
  10218. ];
  10219. instanceMatrixNode = mat4( ...instanceBuffers );
  10220. }
  10221. this.instanceMatrixNode = instanceMatrixNode;
  10222. }
  10223. if ( instanceColor && instanceColorNode === null ) {
  10224. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  10225. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10226. this.bufferColor = buffer;
  10227. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  10228. this.instanceColorNode = instanceColorNode;
  10229. }
  10230. // POSITION
  10231. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  10232. positionLocal.assign( instancePosition );
  10233. // NORMAL
  10234. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10235. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  10236. // ASSIGNS
  10237. normalLocal.assign( instanceNormal );
  10238. }
  10239. // COLOR
  10240. if ( this.instanceColorNode !== null ) {
  10241. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  10242. }
  10243. }
  10244. /**
  10245. * Checks if the internal buffers required an update.
  10246. *
  10247. * @param {NodeFrame} frame - The current node frame.
  10248. */
  10249. update( /*frame*/ ) {
  10250. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  10251. this.buffer.version = this.instanceMatrix.version;
  10252. }
  10253. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  10254. this.bufferColor.version = this.instanceColor.version;
  10255. }
  10256. }
  10257. }
  10258. /**
  10259. * TSL function for creating an instance node.
  10260. *
  10261. * @tsl
  10262. * @function
  10263. * @param {number} count - The number of instances.
  10264. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10265. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10266. * @returns {InstanceNode}
  10267. */
  10268. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  10269. /**
  10270. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  10271. * It allows an easier setup of the instance node.
  10272. *
  10273. * @augments InstanceNode
  10274. */
  10275. class InstancedMeshNode extends InstanceNode {
  10276. static get type() {
  10277. return 'InstancedMeshNode';
  10278. }
  10279. /**
  10280. * Constructs a new instanced mesh node.
  10281. *
  10282. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  10283. */
  10284. constructor( instancedMesh ) {
  10285. const { count, instanceMatrix, instanceColor } = instancedMesh;
  10286. super( count, instanceMatrix, instanceColor );
  10287. /**
  10288. * A reference to the instanced mesh.
  10289. *
  10290. * @type {InstancedMesh}
  10291. */
  10292. this.instancedMesh = instancedMesh;
  10293. }
  10294. }
  10295. /**
  10296. * TSL function for creating an instanced mesh node.
  10297. *
  10298. * @tsl
  10299. * @function
  10300. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  10301. * @returns {InstancedMeshNode}
  10302. */
  10303. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  10304. /**
  10305. * This node implements the vertex shader logic which is required
  10306. * when rendering 3D objects via batching. `BatchNode` must be used
  10307. * with instances of {@link BatchedMesh}.
  10308. *
  10309. * @augments Node
  10310. */
  10311. class BatchNode extends Node {
  10312. static get type() {
  10313. return 'BatchNode';
  10314. }
  10315. /**
  10316. * Constructs a new batch node.
  10317. *
  10318. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10319. */
  10320. constructor( batchMesh ) {
  10321. super( 'void' );
  10322. /**
  10323. * A reference to batched mesh.
  10324. *
  10325. * @type {BatchedMesh}
  10326. */
  10327. this.batchMesh = batchMesh;
  10328. /**
  10329. * The batching index node.
  10330. *
  10331. * @type {?IndexNode}
  10332. * @default null
  10333. */
  10334. this.batchingIdNode = null;
  10335. }
  10336. /**
  10337. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10338. * to predefined node variables for accumulation. That follows the same patterns
  10339. * like with morph and skinning nodes.
  10340. *
  10341. * @param {NodeBuilder} builder - The current node builder.
  10342. */
  10343. setup( builder ) {
  10344. if ( this.batchingIdNode === null ) {
  10345. if ( builder.getDrawIndex() === null ) {
  10346. this.batchingIdNode = instanceIndex;
  10347. } else {
  10348. this.batchingIdNode = drawIndex;
  10349. }
  10350. }
  10351. const getIndirectIndex = Fn( ( [ id ] ) => {
  10352. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  10353. const x = int( id ).mod( size );
  10354. const y = int( id ).div( size );
  10355. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  10356. } ).setLayout( {
  10357. name: 'getIndirectIndex',
  10358. type: 'uint',
  10359. inputs: [
  10360. { name: 'id', type: 'int' }
  10361. ]
  10362. } );
  10363. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  10364. const matricesTexture = this.batchMesh._matricesTexture;
  10365. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  10366. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  10367. const x = j.mod( size );
  10368. const y = j.div( size );
  10369. const batchingMatrix = mat4(
  10370. textureLoad( matricesTexture, ivec2( x, y ) ),
  10371. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  10372. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  10373. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  10374. );
  10375. const colorsTexture = this.batchMesh._colorsTexture;
  10376. if ( colorsTexture !== null ) {
  10377. const getBatchingColor = Fn( ( [ id ] ) => {
  10378. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  10379. const j = id;
  10380. const x = j.mod( size );
  10381. const y = j.div( size );
  10382. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  10383. } ).setLayout( {
  10384. name: 'getBatchingColor',
  10385. type: 'vec3',
  10386. inputs: [
  10387. { name: 'id', type: 'int' }
  10388. ]
  10389. } );
  10390. const color = getBatchingColor( indirectId );
  10391. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  10392. }
  10393. const bm = mat3( batchingMatrix );
  10394. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  10395. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  10396. const batchingNormal = bm.mul( transformedNormal ).xyz;
  10397. normalLocal.assign( batchingNormal );
  10398. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10399. tangentLocal.mulAssign( bm );
  10400. }
  10401. }
  10402. }
  10403. /**
  10404. * TSL function for creating a batch node.
  10405. *
  10406. * @tsl
  10407. * @function
  10408. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10409. * @returns {BatchNode}
  10410. */
  10411. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  10412. /**
  10413. * This class enables element access on instances of {@link StorageBufferNode}.
  10414. * In most cases, it is indirectly used when accessing elements with the
  10415. * {@link StorageBufferNode#element} method.
  10416. *
  10417. * ```js
  10418. * const position = positionStorage.element( instanceIndex );
  10419. * ```
  10420. *
  10421. * @augments ArrayElementNode
  10422. */
  10423. class StorageArrayElementNode extends ArrayElementNode {
  10424. static get type() {
  10425. return 'StorageArrayElementNode';
  10426. }
  10427. /**
  10428. * Constructs storage buffer element node.
  10429. *
  10430. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10431. * @param {Node} indexNode - The index node that defines the element access.
  10432. */
  10433. constructor( storageBufferNode, indexNode ) {
  10434. super( storageBufferNode, indexNode );
  10435. /**
  10436. * This flag can be used for type testing.
  10437. *
  10438. * @type {boolean}
  10439. * @readonly
  10440. * @default true
  10441. */
  10442. this.isStorageArrayElementNode = true;
  10443. }
  10444. /**
  10445. * The storage buffer node.
  10446. *
  10447. * @param {Node} value
  10448. * @type {StorageBufferNode}
  10449. */
  10450. set storageBufferNode( value ) {
  10451. this.node = value;
  10452. }
  10453. get storageBufferNode() {
  10454. return this.node;
  10455. }
  10456. getMemberType( builder, name ) {
  10457. const structTypeNode = this.storageBufferNode.structTypeNode;
  10458. if ( structTypeNode ) {
  10459. return structTypeNode.getMemberType( builder, name );
  10460. }
  10461. return 'void';
  10462. }
  10463. setup( builder ) {
  10464. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10465. if ( this.node.isPBO === true ) {
  10466. builder.setupPBO( this.node );
  10467. }
  10468. }
  10469. return super.setup( builder );
  10470. }
  10471. generate( builder, output ) {
  10472. let snippet;
  10473. const isAssignContext = builder.context.assign;
  10474. //
  10475. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10476. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  10477. snippet = builder.generatePBO( this );
  10478. } else {
  10479. snippet = this.node.build( builder );
  10480. }
  10481. } else {
  10482. snippet = super.generate( builder );
  10483. }
  10484. if ( isAssignContext !== true ) {
  10485. const type = this.getNodeType( builder );
  10486. snippet = builder.format( snippet, type, output );
  10487. }
  10488. return snippet;
  10489. }
  10490. }
  10491. /**
  10492. * TSL function for creating a storage element node.
  10493. *
  10494. * @tsl
  10495. * @function
  10496. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10497. * @param {Node} indexNode - The index node that defines the element access.
  10498. * @returns {StorageArrayElementNode}
  10499. */
  10500. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  10501. /**
  10502. * This node is used in context of compute shaders and allows to define a
  10503. * storage buffer for data. A typical workflow is to create instances of
  10504. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  10505. * setup up a compute shader that writes into the buffers and then convert
  10506. * the storage buffers to attribute nodes for rendering.
  10507. *
  10508. * ```js
  10509. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  10510. *
  10511. * const computeInit = Fn( () => { // the compute shader
  10512. *
  10513. * const position = positionBuffer.element( instanceIndex );
  10514. *
  10515. * // compute position data
  10516. *
  10517. * position.x = 1;
  10518. * position.y = 1;
  10519. * position.z = 1;
  10520. *
  10521. * } )().compute( particleCount );
  10522. *
  10523. * const particleMaterial = new THREE.SpriteNodeMaterial();
  10524. * particleMaterial.positionNode = positionBuffer.toAttribute();
  10525. *
  10526. * renderer.computeAsync( computeInit );
  10527. *
  10528. * ```
  10529. *
  10530. * @augments BufferNode
  10531. */
  10532. class StorageBufferNode extends BufferNode {
  10533. static get type() {
  10534. return 'StorageBufferNode';
  10535. }
  10536. /**
  10537. * Constructs a new storage buffer node.
  10538. *
  10539. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10540. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  10541. * @param {number} [bufferCount=0] - The buffer count.
  10542. */
  10543. constructor( value, bufferType = null, bufferCount = 0 ) {
  10544. let nodeType, structTypeNode = null;
  10545. if ( bufferType && bufferType.isStruct ) {
  10546. nodeType = 'struct';
  10547. structTypeNode = bufferType.layout;
  10548. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  10549. bufferCount = value.count;
  10550. }
  10551. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  10552. nodeType = getTypeFromLength( value.itemSize );
  10553. bufferCount = value.count;
  10554. } else {
  10555. nodeType = bufferType;
  10556. }
  10557. super( value, nodeType, bufferCount );
  10558. /**
  10559. * This flag can be used for type testing.
  10560. *
  10561. * @type {boolean}
  10562. * @readonly
  10563. * @default true
  10564. */
  10565. this.isStorageBufferNode = true;
  10566. /**
  10567. * The buffer struct type.
  10568. *
  10569. * @type {?StructTypeNode}
  10570. * @default null
  10571. */
  10572. this.structTypeNode = structTypeNode;
  10573. /**
  10574. * The access type of the texture node.
  10575. *
  10576. * @type {string}
  10577. * @default 'readWrite'
  10578. */
  10579. this.access = NodeAccess.READ_WRITE;
  10580. /**
  10581. * Whether the node is atomic or not.
  10582. *
  10583. * @type {boolean}
  10584. * @default false
  10585. */
  10586. this.isAtomic = false;
  10587. /**
  10588. * Whether the node represents a PBO or not.
  10589. * Only relevant for WebGL.
  10590. *
  10591. * @type {boolean}
  10592. * @default false
  10593. */
  10594. this.isPBO = false;
  10595. /**
  10596. * A reference to the internal buffer attribute node.
  10597. *
  10598. * @type {?BufferAttributeNode}
  10599. * @default null
  10600. */
  10601. this._attribute = null;
  10602. /**
  10603. * A reference to the internal varying node.
  10604. *
  10605. * @type {?VaryingNode}
  10606. * @default null
  10607. */
  10608. this._varying = null;
  10609. /**
  10610. * `StorageBufferNode` sets this property to `true` by default.
  10611. *
  10612. * @type {boolean}
  10613. * @default true
  10614. */
  10615. this.global = true;
  10616. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10617. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10618. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10619. else value.isStorageBufferAttribute = true;
  10620. }
  10621. }
  10622. /**
  10623. * This method is overwritten since the buffer data might be shared
  10624. * and thus the hash should be shared as well.
  10625. *
  10626. * @param {NodeBuilder} builder - The current node builder.
  10627. * @return {string} The hash.
  10628. */
  10629. getHash( builder ) {
  10630. if ( this.bufferCount === 0 ) {
  10631. let bufferData = builder.globalCache.getData( this.value );
  10632. if ( bufferData === undefined ) {
  10633. bufferData = {
  10634. node: this
  10635. };
  10636. builder.globalCache.setData( this.value, bufferData );
  10637. }
  10638. return bufferData.node.uuid;
  10639. }
  10640. return this.uuid;
  10641. }
  10642. /**
  10643. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  10644. *
  10645. * @param {NodeBuilder} builder - The current node builder.
  10646. * @return {string} The input type.
  10647. */
  10648. getInputType( /*builder*/ ) {
  10649. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10650. }
  10651. /**
  10652. * Enables element access with the given index node.
  10653. *
  10654. * @param {IndexNode} indexNode - The index node.
  10655. * @return {StorageArrayElementNode} A node representing the element access.
  10656. */
  10657. element( indexNode ) {
  10658. return storageElement( this, indexNode );
  10659. }
  10660. /**
  10661. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  10662. *
  10663. * @param {boolean} value - The value so set.
  10664. * @return {StorageBufferNode} A reference to this node.
  10665. */
  10666. setPBO( value ) {
  10667. this.isPBO = value;
  10668. return this;
  10669. }
  10670. /**
  10671. * Returns the `isPBO` value.
  10672. *
  10673. * @return {boolean} Whether the node represents a PBO or not.
  10674. */
  10675. getPBO() {
  10676. return this.isPBO;
  10677. }
  10678. /**
  10679. * Defines the node access.
  10680. *
  10681. * @param {string} value - The node access.
  10682. * @return {StorageBufferNode} A reference to this node.
  10683. */
  10684. setAccess( value ) {
  10685. this.access = value;
  10686. return this;
  10687. }
  10688. /**
  10689. * Convenience method for configuring a read-only node access.
  10690. *
  10691. * @return {StorageBufferNode} A reference to this node.
  10692. */
  10693. toReadOnly() {
  10694. return this.setAccess( NodeAccess.READ_ONLY );
  10695. }
  10696. /**
  10697. * Defines whether the node is atomic or not.
  10698. *
  10699. * @param {boolean} value - The atomic flag.
  10700. * @return {StorageBufferNode} A reference to this node.
  10701. */
  10702. setAtomic( value ) {
  10703. this.isAtomic = value;
  10704. return this;
  10705. }
  10706. /**
  10707. * Convenience method for making this node atomic.
  10708. *
  10709. * @return {StorageBufferNode} A reference to this node.
  10710. */
  10711. toAtomic() {
  10712. return this.setAtomic( true );
  10713. }
  10714. /**
  10715. * Returns attribute data for this storage buffer node.
  10716. *
  10717. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  10718. */
  10719. getAttributeData() {
  10720. if ( this._attribute === null ) {
  10721. this._attribute = bufferAttribute( this.value );
  10722. this._varying = varying( this._attribute );
  10723. }
  10724. return {
  10725. attribute: this._attribute,
  10726. varying: this._varying
  10727. };
  10728. }
  10729. /**
  10730. * This method is overwritten since the node type from the availability of storage buffers
  10731. * and the attribute data.
  10732. *
  10733. * @param {NodeBuilder} builder - The current node builder.
  10734. * @return {string} The node type.
  10735. */
  10736. getNodeType( builder ) {
  10737. if ( this.structTypeNode !== null ) {
  10738. return this.structTypeNode.getNodeType( builder );
  10739. }
  10740. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10741. return super.getNodeType( builder );
  10742. }
  10743. const { attribute } = this.getAttributeData();
  10744. return attribute.getNodeType( builder );
  10745. }
  10746. /**
  10747. * Generates the code snippet of the storage buffer node.
  10748. *
  10749. * @param {NodeBuilder} builder - The current node builder.
  10750. * @return {string} The generated code snippet.
  10751. */
  10752. generate( builder ) {
  10753. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  10754. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10755. return super.generate( builder );
  10756. }
  10757. const { attribute, varying } = this.getAttributeData();
  10758. const output = varying.build( builder );
  10759. builder.registerTransform( output, attribute );
  10760. return output;
  10761. }
  10762. }
  10763. /**
  10764. * TSL function for creating a storage buffer node.
  10765. *
  10766. * @tsl
  10767. * @function
  10768. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10769. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  10770. * @param {number} [count=0] - The buffer count.
  10771. * @returns {StorageBufferNode}
  10772. */
  10773. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10774. /**
  10775. * @tsl
  10776. * @function
  10777. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  10778. *
  10779. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10780. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  10781. * @param {number} count - The buffer count.
  10782. * @returns {StorageBufferNode}
  10783. */
  10784. const storageObject = ( value, type, count ) => { // @deprecated, r171
  10785. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  10786. return storage( value, type, count ).setPBO( true );
  10787. };
  10788. const _frameId = new WeakMap();
  10789. /**
  10790. * This node implements the vertex transformation shader logic which is required
  10791. * for skinning/skeletal animation.
  10792. *
  10793. * @augments Node
  10794. */
  10795. class SkinningNode extends Node {
  10796. static get type() {
  10797. return 'SkinningNode';
  10798. }
  10799. /**
  10800. * Constructs a new skinning node.
  10801. *
  10802. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10803. */
  10804. constructor( skinnedMesh ) {
  10805. super( 'void' );
  10806. /**
  10807. * The skinned mesh.
  10808. *
  10809. * @type {SkinnedMesh}
  10810. */
  10811. this.skinnedMesh = skinnedMesh;
  10812. /**
  10813. * The update type overwritten since skinning nodes are updated per object.
  10814. *
  10815. * @type {string}
  10816. */
  10817. this.updateType = NodeUpdateType.OBJECT;
  10818. //
  10819. /**
  10820. * The skin index attribute.
  10821. *
  10822. * @type {AttributeNode}
  10823. */
  10824. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  10825. /**
  10826. * The skin weight attribute.
  10827. *
  10828. * @type {AttributeNode}
  10829. */
  10830. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  10831. /**
  10832. * The bind matrix node.
  10833. *
  10834. * @type {Node<mat4>}
  10835. */
  10836. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  10837. /**
  10838. * The bind matrix inverse node.
  10839. *
  10840. * @type {Node<mat4>}
  10841. */
  10842. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  10843. /**
  10844. * The bind matrices as a uniform buffer node.
  10845. *
  10846. * @type {Node}
  10847. */
  10848. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10849. /**
  10850. * The current vertex position in local space.
  10851. *
  10852. * @type {Node<vec3>}
  10853. */
  10854. this.positionNode = positionLocal;
  10855. /**
  10856. * The result of vertex position in local space.
  10857. *
  10858. * @type {Node<vec3>}
  10859. */
  10860. this.toPositionNode = positionLocal;
  10861. /**
  10862. * The previous bind matrices as a uniform buffer node.
  10863. * Required for computing motion vectors.
  10864. *
  10865. * @type {?Node}
  10866. * @default null
  10867. */
  10868. this.previousBoneMatricesNode = null;
  10869. }
  10870. /**
  10871. * Transforms the given vertex position via skinning.
  10872. *
  10873. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  10874. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  10875. * @return {Node<vec3>} The transformed vertex position.
  10876. */
  10877. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  10878. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  10879. const boneMatX = boneMatrices.element( skinIndexNode.x );
  10880. const boneMatY = boneMatrices.element( skinIndexNode.y );
  10881. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  10882. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10883. // POSITION
  10884. const skinVertex = bindMatrixNode.mul( position );
  10885. const skinned = add(
  10886. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  10887. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  10888. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  10889. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  10890. );
  10891. return bindMatrixInverseNode.mul( skinned ).xyz;
  10892. }
  10893. /**
  10894. * Transforms the given vertex normal via skinning.
  10895. *
  10896. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  10897. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  10898. * @return {Node<vec3>} The transformed vertex normal.
  10899. */
  10900. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  10901. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  10902. const boneMatX = boneMatrices.element( skinIndexNode.x );
  10903. const boneMatY = boneMatrices.element( skinIndexNode.y );
  10904. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  10905. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10906. // NORMAL
  10907. let skinMatrix = add(
  10908. skinWeightNode.x.mul( boneMatX ),
  10909. skinWeightNode.y.mul( boneMatY ),
  10910. skinWeightNode.z.mul( boneMatZ ),
  10911. skinWeightNode.w.mul( boneMatW )
  10912. );
  10913. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  10914. return skinMatrix.transformDirection( normal ).xyz;
  10915. }
  10916. /**
  10917. * Computes the transformed/skinned vertex position of the previous frame.
  10918. *
  10919. * @param {NodeBuilder} builder - The current node builder.
  10920. * @return {Node<vec3>} The skinned position from the previous frame.
  10921. */
  10922. getPreviousSkinnedPosition( builder ) {
  10923. const skinnedMesh = builder.object;
  10924. if ( this.previousBoneMatricesNode === null ) {
  10925. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  10926. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10927. }
  10928. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  10929. }
  10930. /**
  10931. * Returns `true` if bone matrices from the previous frame are required. Relevant
  10932. * when computing motion vectors with {@link VelocityNode}.
  10933. *
  10934. * @param {NodeBuilder} builder - The current node builder.
  10935. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  10936. */
  10937. needsPreviousBoneMatrices( builder ) {
  10938. const mrt = builder.renderer.getMRT();
  10939. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  10940. }
  10941. /**
  10942. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  10943. *
  10944. * @param {NodeBuilder} builder - The current node builder.
  10945. * @return {Node<vec3>} The transformed vertex position.
  10946. */
  10947. setup( builder ) {
  10948. if ( this.needsPreviousBoneMatrices( builder ) ) {
  10949. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  10950. }
  10951. const skinPosition = this.getSkinnedPosition();
  10952. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  10953. //
  10954. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10955. const skinNormal = this.getSkinnedNormal();
  10956. normalLocal.assign( skinNormal );
  10957. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10958. tangentLocal.assign( skinNormal );
  10959. }
  10960. }
  10961. return skinPosition;
  10962. }
  10963. /**
  10964. * Generates the code snippet of the skinning node.
  10965. *
  10966. * @param {NodeBuilder} builder - The current node builder.
  10967. * @param {string} output - The current output.
  10968. * @return {string} The generated code snippet.
  10969. */
  10970. generate( builder, output ) {
  10971. if ( output !== 'void' ) {
  10972. return super.generate( builder, output );
  10973. }
  10974. }
  10975. /**
  10976. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  10977. *
  10978. * @param {NodeFrame} frame - The current node frame.
  10979. */
  10980. update( frame ) {
  10981. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  10982. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  10983. _frameId.set( skeleton, frame.frameId );
  10984. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  10985. skeleton.update();
  10986. }
  10987. }
  10988. /**
  10989. * TSL function for creating a skinning node.
  10990. *
  10991. * @tsl
  10992. * @function
  10993. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10994. * @returns {SkinningNode}
  10995. */
  10996. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  10997. /**
  10998. * TSL function for computing skinning.
  10999. *
  11000. * @tsl
  11001. * @function
  11002. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11003. * @param {Node<vec3>} [toPosition=null] - The target position.
  11004. * @returns {SkinningNode}
  11005. */
  11006. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11007. const node = new SkinningNode( skinnedMesh );
  11008. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11009. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11010. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11011. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11012. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11013. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11014. node.toPositionNode = toPosition;
  11015. return nodeObject( node );
  11016. };
  11017. /**
  11018. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11019. * ```js
  11020. * Loop( count, ( { i } ) => {
  11021. *
  11022. * } );
  11023. * ```
  11024. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11025. * ```js
  11026. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11027. *
  11028. * } );
  11029. *```
  11030. * Nested loops can be defined in a compacted form:
  11031. * ```js
  11032. * Loop( 10, 5, ( { i, j } ) => {
  11033. *
  11034. * } );
  11035. * ```
  11036. * Loops that should run backwards can be defined like so:
  11037. * ```js
  11038. * Loop( { start: 10 }, () => {} );
  11039. * ```
  11040. * It is possible to execute with boolean values, similar to the `while` syntax.
  11041. * ```js
  11042. * const value = float( 0 ).toVar();
  11043. *
  11044. * Loop( value.lessThan( 10 ), () => {
  11045. *
  11046. * value.addAssign( 1 );
  11047. *
  11048. * } );
  11049. * ```
  11050. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11051. * @augments Node
  11052. */
  11053. class LoopNode extends Node {
  11054. static get type() {
  11055. return 'LoopNode';
  11056. }
  11057. /**
  11058. * Constructs a new loop node.
  11059. *
  11060. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11061. */
  11062. constructor( params = [] ) {
  11063. super();
  11064. this.params = params;
  11065. }
  11066. /**
  11067. * Returns a loop variable name based on an index. The pattern is
  11068. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11069. *
  11070. * @param {number} index - The index.
  11071. * @return {string} The loop variable name.
  11072. */
  11073. getVarName( index ) {
  11074. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11075. }
  11076. /**
  11077. * Returns properties about this node.
  11078. *
  11079. * @param {NodeBuilder} builder - The current node builder.
  11080. * @return {Object} The node properties.
  11081. */
  11082. getProperties( builder ) {
  11083. const properties = builder.getNodeProperties( this );
  11084. if ( properties.stackNode !== undefined ) return properties;
  11085. //
  11086. const inputs = {};
  11087. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11088. const param = this.params[ i ];
  11089. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  11090. const type = ( param.isNode !== true && param.type ) || 'int';
  11091. inputs[ name ] = expression( name, type );
  11092. }
  11093. const stack = builder.addStack(); // TODO: cache() it
  11094. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  11095. properties.stackNode = stack;
  11096. const baseParam = this.params[ 0 ];
  11097. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  11098. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  11099. }
  11100. builder.removeStack();
  11101. return properties;
  11102. }
  11103. /**
  11104. * This method is overwritten since the node type is inferred based on the loop configuration.
  11105. *
  11106. * @param {NodeBuilder} builder - The current node builder.
  11107. * @return {string} The node type.
  11108. */
  11109. getNodeType( builder ) {
  11110. const { returnsNode } = this.getProperties( builder );
  11111. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  11112. }
  11113. setup( builder ) {
  11114. // setup properties
  11115. this.getProperties( builder );
  11116. }
  11117. generate( builder ) {
  11118. const properties = this.getProperties( builder );
  11119. const params = this.params;
  11120. const stackNode = properties.stackNode;
  11121. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  11122. const param = params[ i ];
  11123. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  11124. if ( param.isNode ) {
  11125. if ( param.getNodeType( builder ) === 'bool' ) {
  11126. isWhile = true;
  11127. type = 'bool';
  11128. end = param.build( builder, type );
  11129. } else {
  11130. type = 'int';
  11131. name = this.getVarName( i );
  11132. start = '0';
  11133. end = param.build( builder, type );
  11134. condition = '<';
  11135. }
  11136. } else {
  11137. type = param.type || 'int';
  11138. name = param.name || this.getVarName( i );
  11139. start = param.start;
  11140. end = param.end;
  11141. condition = param.condition;
  11142. update = param.update;
  11143. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  11144. else if ( start && start.isNode ) start = start.build( builder, type );
  11145. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  11146. else if ( end && end.isNode ) end = end.build( builder, type );
  11147. if ( start !== undefined && end === undefined ) {
  11148. start = start + ' - 1';
  11149. end = '0';
  11150. condition = '>=';
  11151. } else if ( end !== undefined && start === undefined ) {
  11152. start = '0';
  11153. condition = '<';
  11154. }
  11155. if ( condition === undefined ) {
  11156. if ( Number( start ) > Number( end ) ) {
  11157. condition = '>=';
  11158. } else {
  11159. condition = '<';
  11160. }
  11161. }
  11162. }
  11163. let loopSnippet;
  11164. if ( isWhile ) {
  11165. loopSnippet = `while ( ${ end } )`;
  11166. } else {
  11167. const internalParam = { start, end};
  11168. //
  11169. const startSnippet = internalParam.start;
  11170. const endSnippet = internalParam.end;
  11171. let updateSnippet;
  11172. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  11173. if ( update !== undefined && update !== null ) {
  11174. switch ( typeof update ) {
  11175. case 'function':
  11176. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  11177. const snippet = flow.code.replace( /\t|;/g, '' );
  11178. updateSnippet = snippet;
  11179. break;
  11180. case 'number':
  11181. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  11182. break;
  11183. case 'string':
  11184. updateSnippet = name + ' ' + update;
  11185. break;
  11186. default:
  11187. if ( update.isNode ) {
  11188. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  11189. } else {
  11190. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  11191. updateSnippet = 'break /* invalid update */';
  11192. }
  11193. }
  11194. } else {
  11195. if ( type === 'int' || type === 'uint' ) {
  11196. update = condition.includes( '<' ) ? '++' : '--';
  11197. } else {
  11198. update = deltaOperator() + ' 1.';
  11199. }
  11200. updateSnippet = name + ' ' + update;
  11201. }
  11202. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  11203. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  11204. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  11205. }
  11206. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  11207. }
  11208. const stackSnippet = stackNode.build( builder, 'void' );
  11209. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  11210. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  11211. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11212. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  11213. }
  11214. builder.addFlowTab();
  11215. return returnsSnippet;
  11216. }
  11217. }
  11218. /**
  11219. * TSL function for creating a loop node.
  11220. *
  11221. * @tsl
  11222. * @function
  11223. * @param {...any} params - A list of parameters.
  11224. * @returns {LoopNode}
  11225. */
  11226. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  11227. /**
  11228. * TSL function for creating a `Continue()` expression.
  11229. *
  11230. * @tsl
  11231. * @function
  11232. * @returns {ExpressionNode}
  11233. */
  11234. const Continue = () => expression( 'continue' ).toStack();
  11235. /**
  11236. * TSL function for creating a `Break()` expression.
  11237. *
  11238. * @tsl
  11239. * @function
  11240. * @returns {ExpressionNode}
  11241. */
  11242. const Break = () => expression( 'break' ).toStack();
  11243. // Deprecated
  11244. /**
  11245. * @tsl
  11246. * @function
  11247. * @deprecated since r168. Use {@link Loop} instead.
  11248. *
  11249. * @param {...any} params
  11250. * @returns {LoopNode}
  11251. */
  11252. const loop = ( ...params ) => { // @deprecated, r168
  11253. console.warn( 'THREE.TSL: loop() has been renamed to Loop().' );
  11254. return Loop( ...params );
  11255. };
  11256. const _morphTextures = /*@__PURE__*/ new WeakMap();
  11257. const _morphVec4 = /*@__PURE__*/ new Vector4();
  11258. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  11259. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  11260. const y = texelIndex.div( width );
  11261. const x = texelIndex.sub( y.mul( width ) );
  11262. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  11263. return bufferAttrib.mul( influence );
  11264. } );
  11265. function getEntry( geometry ) {
  11266. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11267. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  11268. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  11269. // instead of using attributes, the WebGL 2 code path encodes morph targets
  11270. // into an array of data textures. Each layer represents a single morph target.
  11271. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11272. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11273. let entry = _morphTextures.get( geometry );
  11274. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  11275. if ( entry !== undefined ) entry.texture.dispose();
  11276. const morphTargets = geometry.morphAttributes.position || [];
  11277. const morphNormals = geometry.morphAttributes.normal || [];
  11278. const morphColors = geometry.morphAttributes.color || [];
  11279. let vertexDataCount = 0;
  11280. if ( hasMorphPosition === true ) vertexDataCount = 1;
  11281. if ( hasMorphNormals === true ) vertexDataCount = 2;
  11282. if ( hasMorphColors === true ) vertexDataCount = 3;
  11283. let width = geometry.attributes.position.count * vertexDataCount;
  11284. let height = 1;
  11285. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  11286. if ( width > maxTextureSize ) {
  11287. height = Math.ceil( width / maxTextureSize );
  11288. width = maxTextureSize;
  11289. }
  11290. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  11291. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  11292. bufferTexture.type = FloatType;
  11293. bufferTexture.needsUpdate = true;
  11294. // fill buffer
  11295. const vertexDataStride = vertexDataCount * 4;
  11296. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  11297. const morphTarget = morphTargets[ i ];
  11298. const morphNormal = morphNormals[ i ];
  11299. const morphColor = morphColors[ i ];
  11300. const offset = width * height * 4 * i;
  11301. for ( let j = 0; j < morphTarget.count; j ++ ) {
  11302. const stride = j * vertexDataStride;
  11303. if ( hasMorphPosition === true ) {
  11304. _morphVec4.fromBufferAttribute( morphTarget, j );
  11305. buffer[ offset + stride + 0 ] = _morphVec4.x;
  11306. buffer[ offset + stride + 1 ] = _morphVec4.y;
  11307. buffer[ offset + stride + 2 ] = _morphVec4.z;
  11308. buffer[ offset + stride + 3 ] = 0;
  11309. }
  11310. if ( hasMorphNormals === true ) {
  11311. _morphVec4.fromBufferAttribute( morphNormal, j );
  11312. buffer[ offset + stride + 4 ] = _morphVec4.x;
  11313. buffer[ offset + stride + 5 ] = _morphVec4.y;
  11314. buffer[ offset + stride + 6 ] = _morphVec4.z;
  11315. buffer[ offset + stride + 7 ] = 0;
  11316. }
  11317. if ( hasMorphColors === true ) {
  11318. _morphVec4.fromBufferAttribute( morphColor, j );
  11319. buffer[ offset + stride + 8 ] = _morphVec4.x;
  11320. buffer[ offset + stride + 9 ] = _morphVec4.y;
  11321. buffer[ offset + stride + 10 ] = _morphVec4.z;
  11322. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  11323. }
  11324. }
  11325. }
  11326. entry = {
  11327. count: morphTargetsCount,
  11328. texture: bufferTexture,
  11329. stride: vertexDataCount,
  11330. size: new Vector2( width, height )
  11331. };
  11332. _morphTextures.set( geometry, entry );
  11333. function disposeTexture() {
  11334. bufferTexture.dispose();
  11335. _morphTextures.delete( geometry );
  11336. geometry.removeEventListener( 'dispose', disposeTexture );
  11337. }
  11338. geometry.addEventListener( 'dispose', disposeTexture );
  11339. }
  11340. return entry;
  11341. }
  11342. /**
  11343. * This node implements the vertex transformation shader logic which is required
  11344. * for morph target animation.
  11345. *
  11346. * @augments Node
  11347. */
  11348. class MorphNode extends Node {
  11349. static get type() {
  11350. return 'MorphNode';
  11351. }
  11352. /**
  11353. * Constructs a new morph node.
  11354. *
  11355. * @param {Mesh} mesh - The mesh holding the morph targets.
  11356. */
  11357. constructor( mesh ) {
  11358. super( 'void' );
  11359. /**
  11360. * The mesh holding the morph targets.
  11361. *
  11362. * @type {Mesh}
  11363. */
  11364. this.mesh = mesh;
  11365. /**
  11366. * A uniform node which represents the morph base influence value.
  11367. *
  11368. * @type {UniformNode<float>}
  11369. */
  11370. this.morphBaseInfluence = uniform( 1 );
  11371. /**
  11372. * The update type overwritten since morph nodes are updated per object.
  11373. *
  11374. * @type {string}
  11375. */
  11376. this.updateType = NodeUpdateType.OBJECT;
  11377. }
  11378. /**
  11379. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  11380. *
  11381. * @param {NodeBuilder} builder - The current node builder.
  11382. */
  11383. setup( builder ) {
  11384. const { geometry } = builder;
  11385. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11386. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  11387. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11388. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11389. // nodes
  11390. const { texture: bufferMap, stride, size } = getEntry( geometry );
  11391. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  11392. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  11393. const width = int( size.width );
  11394. Loop( morphTargetsCount, ( { i } ) => {
  11395. const influence = float( 0 ).toVar();
  11396. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  11397. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  11398. } else {
  11399. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  11400. }
  11401. If( influence.notEqual( 0 ), () => {
  11402. if ( hasMorphPosition === true ) {
  11403. positionLocal.addAssign( getMorph( {
  11404. bufferMap,
  11405. influence,
  11406. stride,
  11407. width,
  11408. depth: i,
  11409. offset: int( 0 )
  11410. } ) );
  11411. }
  11412. if ( hasMorphNormals === true ) {
  11413. normalLocal.addAssign( getMorph( {
  11414. bufferMap,
  11415. influence,
  11416. stride,
  11417. width,
  11418. depth: i,
  11419. offset: int( 1 )
  11420. } ) );
  11421. }
  11422. } );
  11423. } );
  11424. }
  11425. /**
  11426. * Updates the state of the morphed mesh by updating the base influence.
  11427. *
  11428. * @param {NodeFrame} frame - The current node frame.
  11429. */
  11430. update( /*frame*/ ) {
  11431. const morphBaseInfluence = this.morphBaseInfluence;
  11432. if ( this.mesh.geometry.morphTargetsRelative ) {
  11433. morphBaseInfluence.value = 1;
  11434. } else {
  11435. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  11436. }
  11437. }
  11438. }
  11439. /**
  11440. * TSL function for creating a morph node.
  11441. *
  11442. * @tsl
  11443. * @function
  11444. * @param {Mesh} mesh - The mesh holding the morph targets.
  11445. * @returns {MorphNode}
  11446. */
  11447. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  11448. /**
  11449. * Base class for lighting nodes.
  11450. *
  11451. * @augments Node
  11452. */
  11453. class LightingNode extends Node {
  11454. static get type() {
  11455. return 'LightingNode';
  11456. }
  11457. /**
  11458. * Constructs a new lighting node.
  11459. */
  11460. constructor() {
  11461. super( 'vec3' );
  11462. /**
  11463. * This flag can be used for type testing.
  11464. *
  11465. * @type {boolean}
  11466. * @readonly
  11467. * @default true
  11468. */
  11469. this.isLightingNode = true;
  11470. }
  11471. }
  11472. /**
  11473. * A generic class that can be used by nodes which contribute
  11474. * ambient occlusion to the scene. E.g. an ambient occlusion map
  11475. * node can be used as input for this module. Used in {@link NodeMaterial}.
  11476. *
  11477. * @augments LightingNode
  11478. */
  11479. class AONode extends LightingNode {
  11480. static get type() {
  11481. return 'AONode';
  11482. }
  11483. /**
  11484. * Constructs a new AO node.
  11485. *
  11486. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  11487. */
  11488. constructor( aoNode = null ) {
  11489. super();
  11490. /**
  11491. * The ambient occlusion node.
  11492. *
  11493. * @type {?Node<float>}
  11494. * @default null
  11495. */
  11496. this.aoNode = aoNode;
  11497. }
  11498. setup( builder ) {
  11499. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  11500. }
  11501. }
  11502. /**
  11503. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  11504. * by adding lighting specific context data. It represents the runtime context of
  11505. * {@link LightsNode}.
  11506. *
  11507. * @augments ContextNode
  11508. */
  11509. class LightingContextNode extends ContextNode {
  11510. static get type() {
  11511. return 'LightingContextNode';
  11512. }
  11513. /**
  11514. * Constructs a new lighting context node.
  11515. *
  11516. * @param {LightsNode} lightsNode - The lights node.
  11517. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  11518. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  11519. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  11520. */
  11521. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  11522. super( lightsNode );
  11523. /**
  11524. * The current lighting model.
  11525. *
  11526. * @type {?LightingModel}
  11527. * @default null
  11528. */
  11529. this.lightingModel = lightingModel;
  11530. /**
  11531. * A backdrop node.
  11532. *
  11533. * @type {?Node<vec3>}
  11534. * @default null
  11535. */
  11536. this.backdropNode = backdropNode;
  11537. /**
  11538. * A backdrop alpha node.
  11539. *
  11540. * @type {?Node<float>}
  11541. * @default null
  11542. */
  11543. this.backdropAlphaNode = backdropAlphaNode;
  11544. this._value = null;
  11545. }
  11546. /**
  11547. * Returns a lighting context object.
  11548. *
  11549. * @return {{
  11550. * radiance: Node<vec3>,
  11551. * irradiance: Node<vec3>,
  11552. * iblIrradiance: Node<vec3>,
  11553. * ambientOcclusion: Node<float>,
  11554. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  11555. * backdrop: Node<vec3>,
  11556. * backdropAlpha: Node<float>
  11557. * }} The lighting context object.
  11558. */
  11559. getContext() {
  11560. const { backdropNode, backdropAlphaNode } = this;
  11561. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  11562. directSpecular = vec3().toVar( 'directSpecular' ),
  11563. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  11564. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  11565. const reflectedLight = {
  11566. directDiffuse,
  11567. directSpecular,
  11568. indirectDiffuse,
  11569. indirectSpecular
  11570. };
  11571. const context = {
  11572. radiance: vec3().toVar( 'radiance' ),
  11573. irradiance: vec3().toVar( 'irradiance' ),
  11574. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  11575. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  11576. reflectedLight,
  11577. backdrop: backdropNode,
  11578. backdropAlpha: backdropAlphaNode
  11579. };
  11580. return context;
  11581. }
  11582. setup( builder ) {
  11583. this.value = this._value || ( this._value = this.getContext() );
  11584. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  11585. return super.setup( builder );
  11586. }
  11587. }
  11588. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  11589. /**
  11590. * A generic class that can be used by nodes which contribute
  11591. * irradiance to the scene. E.g. a light map node can be used
  11592. * as input for this module. Used in {@link NodeMaterial}.
  11593. *
  11594. * @augments LightingNode
  11595. */
  11596. class IrradianceNode extends LightingNode {
  11597. static get type() {
  11598. return 'IrradianceNode';
  11599. }
  11600. /**
  11601. * Constructs a new irradiance node.
  11602. *
  11603. * @param {Node<vec3>} node - A node contributing irradiance.
  11604. */
  11605. constructor( node ) {
  11606. super();
  11607. /**
  11608. * A node contributing irradiance.
  11609. *
  11610. * @type {Node<vec3>}
  11611. */
  11612. this.node = node;
  11613. }
  11614. setup( builder ) {
  11615. builder.context.irradiance.addAssign( this.node );
  11616. }
  11617. }
  11618. let screenSizeVec, viewportVec;
  11619. /**
  11620. * This node provides a collection of screen related metrics.
  11621. * Depending on {@link ScreenNode#scope}, the nodes can represent
  11622. * resolution or viewport data as well as fragment or uv coordinates.
  11623. *
  11624. * @augments Node
  11625. */
  11626. class ScreenNode extends Node {
  11627. static get type() {
  11628. return 'ScreenNode';
  11629. }
  11630. /**
  11631. * Constructs a new screen node.
  11632. *
  11633. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  11634. */
  11635. constructor( scope ) {
  11636. super();
  11637. /**
  11638. * The node represents different metric depending on which scope is selected.
  11639. *
  11640. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  11641. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  11642. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  11643. * - `ScreenNode.UV`: Normalized coordinates.
  11644. *
  11645. * @type {('coordinate'|'viewport'|'size'|'uv')}
  11646. */
  11647. this.scope = scope;
  11648. /**
  11649. * This flag can be used for type testing.
  11650. *
  11651. * @type {boolean}
  11652. * @readonly
  11653. * @default true
  11654. */
  11655. this.isViewportNode = true;
  11656. }
  11657. /**
  11658. * This method is overwritten since the node type depends on the selected scope.
  11659. *
  11660. * @return {('vec2'|'vec4')} The node type.
  11661. */
  11662. getNodeType() {
  11663. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  11664. else return 'vec2';
  11665. }
  11666. /**
  11667. * This method is overwritten since the node's update type depends on the selected scope.
  11668. *
  11669. * @return {NodeUpdateType} The update type.
  11670. */
  11671. getUpdateType() {
  11672. let updateType = NodeUpdateType.NONE;
  11673. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  11674. updateType = NodeUpdateType.RENDER;
  11675. }
  11676. this.updateType = updateType;
  11677. return updateType;
  11678. }
  11679. /**
  11680. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  11681. * from the current renderer.
  11682. *
  11683. * @param {NodeFrame} frame - A reference to the current node frame.
  11684. */
  11685. update( { renderer } ) {
  11686. const renderTarget = renderer.getRenderTarget();
  11687. if ( this.scope === ScreenNode.VIEWPORT ) {
  11688. if ( renderTarget !== null ) {
  11689. viewportVec.copy( renderTarget.viewport );
  11690. } else {
  11691. renderer.getViewport( viewportVec );
  11692. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  11693. }
  11694. } else {
  11695. if ( renderTarget !== null ) {
  11696. screenSizeVec.width = renderTarget.width;
  11697. screenSizeVec.height = renderTarget.height;
  11698. } else {
  11699. renderer.getDrawingBufferSize( screenSizeVec );
  11700. }
  11701. }
  11702. }
  11703. setup( /*builder*/ ) {
  11704. const scope = this.scope;
  11705. let output = null;
  11706. if ( scope === ScreenNode.SIZE ) {
  11707. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  11708. } else if ( scope === ScreenNode.VIEWPORT ) {
  11709. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  11710. } else {
  11711. output = vec2( screenCoordinate.div( screenSize ) );
  11712. }
  11713. return output;
  11714. }
  11715. generate( builder ) {
  11716. if ( this.scope === ScreenNode.COORDINATE ) {
  11717. let coord = builder.getFragCoord();
  11718. if ( builder.isFlipY() ) {
  11719. // follow webgpu standards
  11720. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  11721. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  11722. }
  11723. return coord;
  11724. }
  11725. return super.generate( builder );
  11726. }
  11727. }
  11728. ScreenNode.COORDINATE = 'coordinate';
  11729. ScreenNode.VIEWPORT = 'viewport';
  11730. ScreenNode.SIZE = 'size';
  11731. ScreenNode.UV = 'uv';
  11732. // Screen
  11733. /**
  11734. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  11735. *
  11736. * @tsl
  11737. * @type {ScreenNode<vec2>}
  11738. */
  11739. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  11740. /**
  11741. * TSL object that represents the screen resolution in physical pixel units.
  11742. *
  11743. * @tsl
  11744. * @type {ScreenNode<vec2>}
  11745. */
  11746. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  11747. /**
  11748. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  11749. *
  11750. * @tsl
  11751. * @type {ScreenNode<vec2>}
  11752. */
  11753. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  11754. // Viewport
  11755. /**
  11756. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  11757. *
  11758. * @tsl
  11759. * @type {ScreenNode<vec4>}
  11760. */
  11761. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  11762. /**
  11763. * TSL object that represents the viewport resolution in physical pixel units.
  11764. *
  11765. * @tsl
  11766. * @type {ScreenNode<vec2>}
  11767. */
  11768. const viewportSize = viewport.zw;
  11769. /**
  11770. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  11771. *
  11772. * @tsl
  11773. * @type {ScreenNode<vec2>}
  11774. */
  11775. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  11776. /**
  11777. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  11778. *
  11779. * @tsl
  11780. * @type {ScreenNode<vec2>}
  11781. */
  11782. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  11783. // Deprecated
  11784. /**
  11785. * @deprecated since r169. Use {@link screenSize} instead.
  11786. */
  11787. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  11788. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  11789. return screenSize;
  11790. }, 'vec2' ).once() )();
  11791. /**
  11792. * @tsl
  11793. * @deprecated since r168. Use {@link screenUV} instead.
  11794. * @type {Node<vec2>}
  11795. */
  11796. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11797. console.warn( 'THREE.TSL: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  11798. return screenUV;
  11799. }, 'vec2' ).once() )();
  11800. /**
  11801. * @tsl
  11802. * @deprecated since r168. Use `screenUV.flipY()` instead.
  11803. * @type {Node<vec2>}
  11804. */
  11805. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11806. console.warn( 'THREE.TSL: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  11807. return screenUV.flipY();
  11808. }, 'vec2' ).once() )();
  11809. const _size$4 = /*@__PURE__*/ new Vector2();
  11810. /**
  11811. * A special type of texture node which represents the data of the current viewport
  11812. * as a texture. The module extracts data from the current bound framebuffer with
  11813. * a copy operation so no extra render pass is required to produce the texture data
  11814. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  11815. * variety of effects like refractive or transmissive materials.
  11816. *
  11817. * @augments TextureNode
  11818. */
  11819. class ViewportTextureNode extends TextureNode {
  11820. static get type() {
  11821. return 'ViewportTextureNode';
  11822. }
  11823. /**
  11824. * Constructs a new viewport texture node.
  11825. *
  11826. * @param {Node} [uvNode=screenUV] - The uv node.
  11827. * @param {?Node} [levelNode=null] - The level node.
  11828. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11829. */
  11830. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  11831. if ( framebufferTexture === null ) {
  11832. framebufferTexture = new FramebufferTexture();
  11833. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  11834. }
  11835. super( framebufferTexture, uvNode, levelNode );
  11836. /**
  11837. * Whether to generate mipmaps or not.
  11838. *
  11839. * @type {boolean}
  11840. * @default false
  11841. */
  11842. this.generateMipmaps = false;
  11843. /**
  11844. * This flag can be used for type testing.
  11845. *
  11846. * @type {boolean}
  11847. * @readonly
  11848. * @default true
  11849. */
  11850. this.isOutputTextureNode = true;
  11851. /**
  11852. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  11853. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  11854. *
  11855. * @type {string}
  11856. * @default 'frame'
  11857. */
  11858. this.updateBeforeType = NodeUpdateType.FRAME;
  11859. }
  11860. updateBefore( frame ) {
  11861. const renderer = frame.renderer;
  11862. renderer.getDrawingBufferSize( _size$4 );
  11863. //
  11864. const framebufferTexture = this.value;
  11865. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  11866. framebufferTexture.image.width = _size$4.width;
  11867. framebufferTexture.image.height = _size$4.height;
  11868. framebufferTexture.needsUpdate = true;
  11869. }
  11870. //
  11871. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  11872. framebufferTexture.generateMipmaps = this.generateMipmaps;
  11873. renderer.copyFramebufferToTexture( framebufferTexture );
  11874. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  11875. }
  11876. clone() {
  11877. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  11878. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  11879. return viewportTextureNode;
  11880. }
  11881. }
  11882. /**
  11883. * TSL function for creating a viewport texture node.
  11884. *
  11885. * @tsl
  11886. * @function
  11887. * @param {?Node} [uvNode=screenUV] - The uv node.
  11888. * @param {?Node} [levelNode=null] - The level node.
  11889. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11890. * @returns {ViewportTextureNode}
  11891. */
  11892. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  11893. /**
  11894. * TSL function for creating a viewport texture node with enabled mipmap generation.
  11895. *
  11896. * @tsl
  11897. * @function
  11898. * @param {?Node} [uvNode=screenUV] - The uv node.
  11899. * @param {?Node} [levelNode=null] - The level node.
  11900. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11901. * @returns {ViewportTextureNode}
  11902. */
  11903. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  11904. let sharedDepthbuffer = null;
  11905. /**
  11906. * Represents the depth of the current viewport as a texture. This module
  11907. * can be used in combination with viewport texture to achieve effects
  11908. * that require depth evaluation.
  11909. *
  11910. * @augments ViewportTextureNode
  11911. */
  11912. class ViewportDepthTextureNode extends ViewportTextureNode {
  11913. static get type() {
  11914. return 'ViewportDepthTextureNode';
  11915. }
  11916. /**
  11917. * Constructs a new viewport depth texture node.
  11918. *
  11919. * @param {Node} [uvNode=screenUV] - The uv node.
  11920. * @param {?Node} [levelNode=null] - The level node.
  11921. */
  11922. constructor( uvNode = screenUV, levelNode = null ) {
  11923. if ( sharedDepthbuffer === null ) {
  11924. sharedDepthbuffer = new DepthTexture();
  11925. }
  11926. super( uvNode, levelNode, sharedDepthbuffer );
  11927. }
  11928. }
  11929. /**
  11930. * TSL function for a viewport depth texture node.
  11931. *
  11932. * @tsl
  11933. * @function
  11934. * @param {?Node} [uvNode=screenUV] - The uv node.
  11935. * @param {?Node} [levelNode=null] - The level node.
  11936. * @returns {ViewportDepthTextureNode}
  11937. */
  11938. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  11939. /**
  11940. * This node offers a collection of features in context of the depth logic in the fragment shader.
  11941. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  11942. * fragment or for depth evaluation purposes.
  11943. *
  11944. * @augments Node
  11945. */
  11946. class ViewportDepthNode extends Node {
  11947. static get type() {
  11948. return 'ViewportDepthNode';
  11949. }
  11950. /**
  11951. * Constructs a new viewport depth node.
  11952. *
  11953. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  11954. * @param {?Node} [valueNode=null] - The value node.
  11955. */
  11956. constructor( scope, valueNode = null ) {
  11957. super( 'float' );
  11958. /**
  11959. * The node behaves differently depending on which scope is selected.
  11960. *
  11961. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  11962. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  11963. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  11964. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  11965. *
  11966. * @type {('depth'|'depthBase'|'linearDepth')}
  11967. */
  11968. this.scope = scope;
  11969. /**
  11970. * Can be used to define a custom depth value.
  11971. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  11972. *
  11973. * @type {?Node}
  11974. * @default null
  11975. */
  11976. this.valueNode = valueNode;
  11977. /**
  11978. * This flag can be used for type testing.
  11979. *
  11980. * @type {boolean}
  11981. * @readonly
  11982. * @default true
  11983. */
  11984. this.isViewportDepthNode = true;
  11985. }
  11986. generate( builder ) {
  11987. const { scope } = this;
  11988. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11989. return builder.getFragDepth();
  11990. }
  11991. return super.generate( builder );
  11992. }
  11993. setup( { camera } ) {
  11994. const { scope } = this;
  11995. const value = this.valueNode;
  11996. let node = null;
  11997. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11998. if ( value !== null ) {
  11999. node = depthBase().assign( value );
  12000. }
  12001. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12002. if ( camera.isPerspectiveCamera ) {
  12003. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12004. } else {
  12005. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12006. }
  12007. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12008. if ( value !== null ) {
  12009. if ( camera.isPerspectiveCamera ) {
  12010. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12011. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12012. } else {
  12013. node = value;
  12014. }
  12015. } else {
  12016. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12017. }
  12018. }
  12019. return node;
  12020. }
  12021. }
  12022. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12023. ViewportDepthNode.DEPTH = 'depth';
  12024. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12025. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12026. /**
  12027. * TSL function for converting a viewZ value to an orthographic depth value.
  12028. *
  12029. * @tsl
  12030. * @function
  12031. * @param {Node<float>} viewZ - The viewZ node.
  12032. * @param {Node<float>} near - The camera's near value.
  12033. * @param {Node<float>} far - The camera's far value.
  12034. * @returns {Node<float>}
  12035. */
  12036. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12037. /**
  12038. * TSL function for converting an orthographic depth value to a viewZ value.
  12039. *
  12040. * @tsl
  12041. * @function
  12042. * @param {Node<float>} depth - The orthographic depth.
  12043. * @param {Node<float>} near - The camera's near value.
  12044. * @param {Node<float>} far - The camera's far value.
  12045. * @returns {Node<float>}
  12046. */
  12047. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12048. /**
  12049. * TSL function for converting a viewZ value to a perspective depth value.
  12050. *
  12051. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12052. *
  12053. * @tsl
  12054. * @function
  12055. * @param {Node<float>} viewZ - The viewZ node.
  12056. * @param {Node<float>} near - The camera's near value.
  12057. * @param {Node<float>} far - The camera's far value.
  12058. * @returns {Node<float>}
  12059. */
  12060. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12061. /**
  12062. * TSL function for converting a perspective depth value to a viewZ value.
  12063. *
  12064. * @tsl
  12065. * @function
  12066. * @param {Node<float>} depth - The perspective depth.
  12067. * @param {Node<float>} near - The camera's near value.
  12068. * @param {Node<float>} far - The camera's far value.
  12069. * @returns {Node<float>}
  12070. */
  12071. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12072. /**
  12073. * TSL function for converting a viewZ value to a logarithmic depth value.
  12074. *
  12075. * @tsl
  12076. * @function
  12077. * @param {Node<float>} viewZ - The viewZ node.
  12078. * @param {Node<float>} near - The camera's near value.
  12079. * @param {Node<float>} far - The camera's far value.
  12080. * @returns {Node<float>}
  12081. */
  12082. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12083. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12084. // The final logarithmic depth formula used here is adapted from one described in an
  12085. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12086. // which was an improvement upon an earlier formula one described in an
  12087. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12088. // Ulrich's formula is the following:
  12089. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12090. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12091. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12092. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12093. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12094. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12095. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12096. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12097. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12098. // Outerra eventually made another improvement to their original "C-constant" variant,
  12099. // but it still does not incorporate the camera near plane (for this version,
  12100. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12101. // Here we make 4 changes to Ulrich's formula:
  12102. // 1. Clamp the camera near plane so we don't divide by 0.
  12103. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12104. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12105. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12106. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12107. // so we do the same here, hence the 'viewZ.negate()' call.
  12108. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12109. near = near.max( 1e-6 ).toVar();
  12110. const numerator = log2( viewZ.negate().div( near ) );
  12111. const denominator = log2( far.div( near ) );
  12112. return numerator.div( denominator );
  12113. };
  12114. /**
  12115. * TSL function for converting a logarithmic depth value to a viewZ value.
  12116. *
  12117. * @tsl
  12118. * @function
  12119. * @param {Node<float>} depth - The logarithmic depth.
  12120. * @param {Node<float>} near - The camera's near value.
  12121. * @param {Node<float>} far - The camera's far value.
  12122. * @returns {Node<float>}
  12123. */
  12124. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12125. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12126. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12127. // a negative viewZ).
  12128. const exponent = depth.mul( log( far.div( near ) ) );
  12129. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12130. };
  12131. /**
  12132. * TSL function for defining a value for the current fragment's depth.
  12133. *
  12134. * @tsl
  12135. * @function
  12136. * @param {Node<float>} value - The depth value to set.
  12137. * @returns {ViewportDepthNode<float>}
  12138. */
  12139. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12140. /**
  12141. * TSL object that represents the depth value for the current fragment.
  12142. *
  12143. * @tsl
  12144. * @type {ViewportDepthNode}
  12145. */
  12146. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12147. /**
  12148. * TSL function for converting a perspective depth value to linear depth.
  12149. *
  12150. * @tsl
  12151. * @function
  12152. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12153. * @returns {ViewportDepthNode<float>}
  12154. */
  12155. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12156. /**
  12157. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12158. *
  12159. * @tsl
  12160. * @type {ViewportDepthNode}
  12161. */
  12162. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12163. depth.assign = ( value ) => depthBase( value );
  12164. /**
  12165. * This node is used in {@link NodeMaterial} to setup the clipping
  12166. * which can happen hardware-accelerated (if supported) and optionally
  12167. * use alpha-to-coverage for anti-aliasing clipped edges.
  12168. *
  12169. * @augments Node
  12170. */
  12171. class ClippingNode extends Node {
  12172. static get type() {
  12173. return 'ClippingNode';
  12174. }
  12175. /**
  12176. * Constructs a new clipping node.
  12177. *
  12178. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12179. * the selected scope influences the behavior of the node and what type of code is generated.
  12180. */
  12181. constructor( scope = ClippingNode.DEFAULT ) {
  12182. super();
  12183. /**
  12184. * The node's scope. Similar to other nodes, the selected scope influences
  12185. * the behavior of the node and what type of code is generated.
  12186. *
  12187. * @type {('default'|'hardware'|'alphaToCoverage')}
  12188. */
  12189. this.scope = scope;
  12190. }
  12191. /**
  12192. * Setups the node depending on the selected scope.
  12193. *
  12194. * @param {NodeBuilder} builder - The current node builder.
  12195. * @return {Node} The result node.
  12196. */
  12197. setup( builder ) {
  12198. super.setup( builder );
  12199. const clippingContext = builder.clippingContext;
  12200. const { intersectionPlanes, unionPlanes } = clippingContext;
  12201. this.hardwareClipping = builder.material.hardwareClipping;
  12202. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12203. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12204. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12205. return this.setupHardwareClipping( unionPlanes, builder );
  12206. } else {
  12207. return this.setupDefault( intersectionPlanes, unionPlanes );
  12208. }
  12209. }
  12210. /**
  12211. * Setups alpha to coverage.
  12212. *
  12213. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12214. * @param {Array<Vector4>} unionPlanes - The union planes.
  12215. * @return {Node} The result node.
  12216. */
  12217. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  12218. return Fn( () => {
  12219. const distanceToPlane = float().toVar( 'distanceToPlane' );
  12220. const distanceGradient = float().toVar( 'distanceToGradient' );
  12221. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  12222. const numUnionPlanes = unionPlanes.length;
  12223. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12224. const clippingPlanes = uniformArray( unionPlanes );
  12225. Loop( numUnionPlanes, ( { i } ) => {
  12226. const plane = clippingPlanes.element( i );
  12227. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12228. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12229. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  12230. } );
  12231. }
  12232. const numIntersectionPlanes = intersectionPlanes.length;
  12233. if ( numIntersectionPlanes > 0 ) {
  12234. const clippingPlanes = uniformArray( intersectionPlanes );
  12235. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  12236. Loop( numIntersectionPlanes, ( { i } ) => {
  12237. const plane = clippingPlanes.element( i );
  12238. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12239. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12240. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  12241. } );
  12242. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  12243. }
  12244. diffuseColor.a.mulAssign( clipOpacity );
  12245. diffuseColor.a.equal( 0.0 ).discard();
  12246. } )();
  12247. }
  12248. /**
  12249. * Setups the default clipping.
  12250. *
  12251. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12252. * @param {Array<Vector4>} unionPlanes - The union planes.
  12253. * @return {Node} The result node.
  12254. */
  12255. setupDefault( intersectionPlanes, unionPlanes ) {
  12256. return Fn( () => {
  12257. const numUnionPlanes = unionPlanes.length;
  12258. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12259. const clippingPlanes = uniformArray( unionPlanes );
  12260. Loop( numUnionPlanes, ( { i } ) => {
  12261. const plane = clippingPlanes.element( i );
  12262. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  12263. } );
  12264. }
  12265. const numIntersectionPlanes = intersectionPlanes.length;
  12266. if ( numIntersectionPlanes > 0 ) {
  12267. const clippingPlanes = uniformArray( intersectionPlanes );
  12268. const clipped = bool( true ).toVar( 'clipped' );
  12269. Loop( numIntersectionPlanes, ( { i } ) => {
  12270. const plane = clippingPlanes.element( i );
  12271. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  12272. } );
  12273. clipped.discard();
  12274. }
  12275. } )();
  12276. }
  12277. /**
  12278. * Setups hardware clipping.
  12279. *
  12280. * @param {Array<Vector4>} unionPlanes - The union planes.
  12281. * @param {NodeBuilder} builder - The current node builder.
  12282. * @return {Node} The result node.
  12283. */
  12284. setupHardwareClipping( unionPlanes, builder ) {
  12285. const numUnionPlanes = unionPlanes.length;
  12286. builder.enableHardwareClipping( numUnionPlanes );
  12287. return Fn( () => {
  12288. const clippingPlanes = uniformArray( unionPlanes );
  12289. const hw_clip_distances = builtin( builder.getClipDistance() );
  12290. Loop( numUnionPlanes, ( { i } ) => {
  12291. const plane = clippingPlanes.element( i );
  12292. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  12293. hw_clip_distances.element( i ).assign( distance );
  12294. } );
  12295. } )();
  12296. }
  12297. }
  12298. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  12299. ClippingNode.DEFAULT = 'default';
  12300. ClippingNode.HARDWARE = 'hardware';
  12301. /**
  12302. * TSL function for setting up the default clipping logic.
  12303. *
  12304. * @tsl
  12305. * @function
  12306. * @returns {ClippingNode}
  12307. */
  12308. const clipping = () => nodeObject( new ClippingNode() );
  12309. /**
  12310. * TSL function for setting up alpha to coverage.
  12311. *
  12312. * @tsl
  12313. * @function
  12314. * @returns {ClippingNode}
  12315. */
  12316. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  12317. /**
  12318. * TSL function for setting up hardware-based clipping.
  12319. *
  12320. * @tsl
  12321. * @function
  12322. * @returns {ClippingNode}
  12323. */
  12324. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  12325. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  12326. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  12327. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12328. 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 ) ) ) ) ) );
  12329. } );
  12330. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12331. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  12332. } );
  12333. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  12334. // Find the discretized derivatives of our coordinates
  12335. const maxDeriv = max$1(
  12336. length( dFdx( position.xyz ) ),
  12337. length( dFdy( position.xyz ) )
  12338. );
  12339. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  12340. // Find two nearest log-discretized noise scales
  12341. const pixScales = vec2(
  12342. exp2( floor( log2( pixScale ) ) ),
  12343. exp2( ceil( log2( pixScale ) ) )
  12344. );
  12345. // Compute alpha thresholds at our two noise scales
  12346. const alpha = vec2(
  12347. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  12348. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  12349. );
  12350. // Factor to interpolate lerp with
  12351. const lerpFactor = fract( log2( pixScale ) );
  12352. // Interpolate alpha threshold from noise at two scales
  12353. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  12354. // Pass into CDF to compute uniformly distrib threshold
  12355. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  12356. const cases = vec3(
  12357. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  12358. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  12359. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  12360. // Find our final, uniformly distributed alpha threshold (ατ)
  12361. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  12362. // Avoids ατ == 0. Could also do ατ =1-ατ
  12363. return clamp( threshold, 1.0e-6, 1.0 );
  12364. } ).setLayout( {
  12365. name: 'getAlphaHashThreshold',
  12366. type: 'float',
  12367. inputs: [
  12368. { name: 'position', type: 'vec3' }
  12369. ]
  12370. } );
  12371. /**
  12372. * An attribute node for representing vertex colors.
  12373. *
  12374. * @augments AttributeNode
  12375. */
  12376. class VertexColorNode extends AttributeNode {
  12377. static get type() {
  12378. return 'VertexColorNode';
  12379. }
  12380. /**
  12381. * Constructs a new vertex color node.
  12382. *
  12383. * @param {number} index - The attribute index.
  12384. */
  12385. constructor( index ) {
  12386. super( null, 'vec4' );
  12387. /**
  12388. * This flag can be used for type testing.
  12389. *
  12390. * @type {boolean}
  12391. * @readonly
  12392. * @default true
  12393. */
  12394. this.isVertexColorNode = true;
  12395. /**
  12396. * The attribute index to enable more than one sets of vertex colors.
  12397. *
  12398. * @type {number}
  12399. * @default 0
  12400. */
  12401. this.index = index;
  12402. }
  12403. /**
  12404. * Overwrites the default implementation by honoring the attribute index.
  12405. *
  12406. * @param {NodeBuilder} builder - The current node builder.
  12407. * @return {string} The attribute name.
  12408. */
  12409. getAttributeName( /*builder*/ ) {
  12410. const index = this.index;
  12411. return 'color' + ( index > 0 ? index : '' );
  12412. }
  12413. generate( builder ) {
  12414. const attributeName = this.getAttributeName( builder );
  12415. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  12416. let result;
  12417. if ( geometryAttribute === true ) {
  12418. result = super.generate( builder );
  12419. } else {
  12420. // Vertex color fallback should be white
  12421. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  12422. }
  12423. return result;
  12424. }
  12425. serialize( data ) {
  12426. super.serialize( data );
  12427. data.index = this.index;
  12428. }
  12429. deserialize( data ) {
  12430. super.deserialize( data );
  12431. this.index = data.index;
  12432. }
  12433. }
  12434. /**
  12435. * TSL function for creating a reference node.
  12436. *
  12437. * @tsl
  12438. * @function
  12439. * @param {number} [index=0] - The attribute index.
  12440. * @returns {VertexColorNode}
  12441. */
  12442. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  12443. /**
  12444. * Base class for all node materials.
  12445. *
  12446. * @augments Material
  12447. */
  12448. class NodeMaterial extends Material {
  12449. static get type() {
  12450. return 'NodeMaterial';
  12451. }
  12452. /**
  12453. * Represents the type of the node material.
  12454. *
  12455. * @type {string}
  12456. */
  12457. get type() {
  12458. return this.constructor.type;
  12459. }
  12460. set type( _value ) { /* */ }
  12461. /**
  12462. * Constructs a new node material.
  12463. */
  12464. constructor() {
  12465. super();
  12466. /**
  12467. * This flag can be used for type testing.
  12468. *
  12469. * @type {boolean}
  12470. * @readonly
  12471. * @default true
  12472. */
  12473. this.isNodeMaterial = true;
  12474. /**
  12475. * Whether this material is affected by fog or not.
  12476. *
  12477. * @type {boolean}
  12478. * @default true
  12479. */
  12480. this.fog = true;
  12481. /**
  12482. * Whether this material is affected by lights or not.
  12483. *
  12484. * @type {boolean}
  12485. * @default false
  12486. */
  12487. this.lights = false;
  12488. /**
  12489. * Whether this material uses hardware clipping or not.
  12490. * This property is managed by the engine and should not be
  12491. * modified by apps.
  12492. *
  12493. * @type {boolean}
  12494. * @default false
  12495. */
  12496. this.hardwareClipping = false;
  12497. /**
  12498. * Node materials which set their `lights` property to `true`
  12499. * are affected by all lights of the scene. Sometimes selective
  12500. * lighting is wanted which means only _some_ lights in the scene
  12501. * affect a material. This can be achieved by creating an instance
  12502. * of {@link LightsNode} with a list of selective
  12503. * lights and assign the node to this property.
  12504. *
  12505. * ```js
  12506. * const customLightsNode = lights( [ light1, light2 ] );
  12507. * material.lightsNode = customLightsNode;
  12508. * ```
  12509. *
  12510. * @type {?LightsNode}
  12511. * @default null
  12512. */
  12513. this.lightsNode = null;
  12514. /**
  12515. * The environment of node materials can be defined by an environment
  12516. * map assigned to the `envMap` property or by `Scene.environment`
  12517. * if the node material is a PBR material. This node property allows to overwrite
  12518. * the default behavior and define the environment with a custom node.
  12519. *
  12520. * ```js
  12521. * material.envNode = pmremTexture( renderTarget.texture );
  12522. * ```
  12523. *
  12524. * @type {?Node<vec3>}
  12525. * @default null
  12526. */
  12527. this.envNode = null;
  12528. /**
  12529. * The lighting of node materials might be influenced by ambient occlusion.
  12530. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  12531. * and the respective `aoMapIntensity`. This node property allows to overwrite
  12532. * the default and define the ambient occlusion with a custom node instead.
  12533. *
  12534. * If you don't want to overwrite the diffuse color but modify the existing
  12535. * values instead, use {@link materialAO}.
  12536. *
  12537. * @type {?Node<float>}
  12538. * @default null
  12539. */
  12540. this.aoNode = null;
  12541. /**
  12542. * The diffuse color of node materials is by default inferred from the
  12543. * `color` and `map` properties. This node property allows to overwrite the default
  12544. * and define the diffuse color with a node instead.
  12545. *
  12546. * ```js
  12547. * material.colorNode = color( 0xff0000 ); // define red color
  12548. * ```
  12549. *
  12550. * If you don't want to overwrite the diffuse color but modify the existing
  12551. * values instead, use {@link materialColor}.
  12552. *
  12553. * ```js
  12554. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  12555. * ```
  12556. *
  12557. * @type {?Node<vec3>}
  12558. * @default null
  12559. */
  12560. this.colorNode = null;
  12561. /**
  12562. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  12563. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  12564. * and define the normals with a node instead.
  12565. *
  12566. * If you don't want to overwrite the normals but modify the existing values instead,
  12567. * use {@link materialNormal}.
  12568. *
  12569. * @type {?Node<vec3>}
  12570. * @default null
  12571. */
  12572. this.normalNode = null;
  12573. /**
  12574. * The opacity of node materials is by default inferred from the `opacity`
  12575. * and `alphaMap` properties. This node property allows to overwrite the default
  12576. * and define the opacity with a node instead.
  12577. *
  12578. * If you don't want to overwrite the normals but modify the existing
  12579. * value instead, use {@link materialOpacity}.
  12580. *
  12581. * @type {?Node<float>}
  12582. * @default null
  12583. */
  12584. this.opacityNode = null;
  12585. /**
  12586. * This node can be used to implement a variety of filter-like effects. The idea is
  12587. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  12588. * to create an arbitrary effect and then assign the node composition to this property.
  12589. * Everything behind the object using this material will now be affected by a filter.
  12590. *
  12591. * ```js
  12592. * const material = new NodeMaterial()
  12593. * material.transparent = true;
  12594. *
  12595. * // everything behind the object will be monochromatic
  12596. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  12597. * ```
  12598. *
  12599. * Backdrop computations are part of the lighting so only lit materials can use this property.
  12600. *
  12601. * @type {?Node<vec3>}
  12602. * @default null
  12603. */
  12604. this.backdropNode = null;
  12605. /**
  12606. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  12607. *
  12608. * @type {?Node<float>}
  12609. * @default null
  12610. */
  12611. this.backdropAlphaNode = null;
  12612. /**
  12613. * The alpha test of node materials is by default inferred from the `alphaTest`
  12614. * property. This node property allows to overwrite the default and define the
  12615. * alpha test with a node instead.
  12616. *
  12617. * If you don't want to overwrite the alpha test but modify the existing
  12618. * value instead, use {@link materialAlphaTest}.
  12619. *
  12620. * @type {?Node<float>}
  12621. * @default null
  12622. */
  12623. this.alphaTestNode = null;
  12624. /**
  12625. * The local vertex positions are computed based on multiple factors like the
  12626. * attribute data, morphing or skinning. This node property allows to overwrite
  12627. * the default and define local vertex positions with nodes instead.
  12628. *
  12629. * If you don't want to overwrite the vertex positions but modify the existing
  12630. * values instead, use {@link positionLocal}.
  12631. *
  12632. *```js
  12633. * material.positionNode = positionLocal.add( displace );
  12634. * ```
  12635. *
  12636. * @type {?Node<vec3>}
  12637. * @default null
  12638. */
  12639. this.positionNode = null;
  12640. /**
  12641. * This node property is intended for logic which modifies geometry data once or per animation step.
  12642. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  12643. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  12644. * can be implemented.
  12645. *
  12646. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  12647. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  12648. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  12649. * eventually assigned to `geometryNode`.
  12650. *
  12651. * @type {?Function}
  12652. * @default null
  12653. */
  12654. this.geometryNode = null;
  12655. /**
  12656. * Allows to overwrite depth values in the fragment shader.
  12657. *
  12658. * @type {?Node<float>}
  12659. * @default null
  12660. */
  12661. this.depthNode = null;
  12662. /**
  12663. * Allows to overwrite the position used for shadow map rendering which
  12664. * is by default {@link positionWorld}, the vertex position
  12665. * in world space.
  12666. *
  12667. * @type {?Node<float>}
  12668. * @default null
  12669. */
  12670. this.receivedShadowPositionNode = null;
  12671. /**
  12672. * Allows to overwrite the geometry position used for shadow map projection which
  12673. * is by default {@link positionLocal}, the vertex position in local space.
  12674. *
  12675. * @type {?Node<float>}
  12676. * @default null
  12677. */
  12678. this.castShadowPositionNode = null;
  12679. /**
  12680. * This node can be used to influence how an object using this node material
  12681. * receive shadows.
  12682. *
  12683. * ```js
  12684. * const totalShadows = float( 1 ).toVar();
  12685. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  12686. * totalShadows.mulAssign( shadow );
  12687. * //return float( 1 ); // bypass received shadows
  12688. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  12689. * } );
  12690. *
  12691. * @type {?(Function|FunctionNode<vec4>)}
  12692. * @default null
  12693. */
  12694. this.receivedShadowNode = null;
  12695. /**
  12696. * This node can be used to influence how an object using this node material
  12697. * casts shadows. To apply a color to shadows, you can simply do:
  12698. *
  12699. * ```js
  12700. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  12701. * ```
  12702. *
  12703. * Which can be nice to fake colored shadows of semi-transparent objects. It
  12704. * is also common to use the property with `Fn` function so checks are performed
  12705. * per fragment.
  12706. *
  12707. * ```js
  12708. * materialCustomShadow.castShadowNode = Fn( () => {
  12709. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  12710. * return materialColor;
  12711. * } )();
  12712. * ```
  12713. *
  12714. * @type {?Node<vec4>}
  12715. * @default null
  12716. */
  12717. this.castShadowNode = null;
  12718. /**
  12719. * This node can be used to define the final output of the material.
  12720. *
  12721. * TODO: Explain the differences to `fragmentNode`.
  12722. *
  12723. * @type {?Node<vec4>}
  12724. * @default null
  12725. */
  12726. this.outputNode = null;
  12727. /**
  12728. * MRT configuration is done on renderer or pass level. This node allows to
  12729. * overwrite what values are written into MRT targets on material level. This
  12730. * can be useful for implementing selective FX features that should only affect
  12731. * specific objects.
  12732. *
  12733. * @type {?MRTNode}
  12734. * @default null
  12735. */
  12736. this.mrtNode = null;
  12737. /**
  12738. * This node property can be used if you need complete freedom in implementing
  12739. * the fragment shader. Assigning a node will replace the built-in material
  12740. * logic used in the fragment stage.
  12741. *
  12742. * @type {?Node<vec4>}
  12743. * @default null
  12744. */
  12745. this.fragmentNode = null;
  12746. /**
  12747. * This node property can be used if you need complete freedom in implementing
  12748. * the vertex shader. Assigning a node will replace the built-in material logic
  12749. * used in the vertex stage.
  12750. *
  12751. * @type {?Node<vec4>}
  12752. * @default null
  12753. */
  12754. this.vertexNode = null;
  12755. // Deprecated properties
  12756. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  12757. get: () => {
  12758. return this.receivedShadowPositionNode;
  12759. },
  12760. set: ( value ) => {
  12761. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  12762. this.receivedShadowPositionNode = value;
  12763. }
  12764. } );
  12765. }
  12766. /**
  12767. * Allows to define a custom cache key that influence the material key computation
  12768. * for render objects.
  12769. *
  12770. * @return {string} The custom cache key.
  12771. */
  12772. customProgramCacheKey() {
  12773. return this.type + getCacheKey$1( this );
  12774. }
  12775. /**
  12776. * Builds this material with the given node builder.
  12777. *
  12778. * @param {NodeBuilder} builder - The current node builder.
  12779. */
  12780. build( builder ) {
  12781. this.setup( builder );
  12782. }
  12783. /**
  12784. * Setups a node material observer with the given builder.
  12785. *
  12786. * @param {NodeBuilder} builder - The current node builder.
  12787. * @return {NodeMaterialObserver} The node material observer.
  12788. */
  12789. setupObserver( builder ) {
  12790. return new NodeMaterialObserver( builder );
  12791. }
  12792. /**
  12793. * Setups the vertex and fragment stage of this node material.
  12794. *
  12795. * @param {NodeBuilder} builder - The current node builder.
  12796. */
  12797. setup( builder ) {
  12798. builder.context.setupNormal = () => this.setupNormal( builder );
  12799. builder.context.setupPositionView = () => this.setupPositionView( builder );
  12800. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  12801. const renderer = builder.renderer;
  12802. const renderTarget = renderer.getRenderTarget();
  12803. // < VERTEX STAGE >
  12804. builder.addStack();
  12805. const vertexNode = this.vertexNode || this.setupVertex( builder );
  12806. builder.stack.outputNode = vertexNode;
  12807. this.setupHardwareClipping( builder );
  12808. if ( this.geometryNode !== null ) {
  12809. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  12810. }
  12811. builder.addFlow( 'vertex', builder.removeStack() );
  12812. // < FRAGMENT STAGE >
  12813. builder.addStack();
  12814. let resultNode;
  12815. const clippingNode = this.setupClipping( builder );
  12816. if ( this.depthWrite === true || this.depthTest === true ) {
  12817. // only write depth if depth buffer is configured
  12818. if ( renderTarget !== null ) {
  12819. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  12820. } else {
  12821. if ( renderer.depth === true ) this.setupDepth( builder );
  12822. }
  12823. }
  12824. if ( this.fragmentNode === null ) {
  12825. this.setupDiffuseColor( builder );
  12826. this.setupVariants( builder );
  12827. const outgoingLightNode = this.setupLighting( builder );
  12828. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  12829. // force unsigned floats - useful for RenderTargets
  12830. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  12831. resultNode = this.setupOutput( builder, basicOutput );
  12832. // OUTPUT NODE
  12833. output.assign( resultNode );
  12834. //
  12835. const isCustomOutput = this.outputNode !== null;
  12836. if ( isCustomOutput ) resultNode = this.outputNode;
  12837. // MRT
  12838. if ( renderTarget !== null ) {
  12839. const mrt = renderer.getMRT();
  12840. const materialMRT = this.mrtNode;
  12841. if ( mrt !== null ) {
  12842. if ( isCustomOutput ) output.assign( resultNode );
  12843. resultNode = mrt;
  12844. if ( materialMRT !== null ) {
  12845. resultNode = mrt.merge( materialMRT );
  12846. }
  12847. } else if ( materialMRT !== null ) {
  12848. resultNode = materialMRT;
  12849. }
  12850. }
  12851. } else {
  12852. let fragmentNode = this.fragmentNode;
  12853. if ( fragmentNode.isOutputStructNode !== true ) {
  12854. fragmentNode = vec4( fragmentNode );
  12855. }
  12856. resultNode = this.setupOutput( builder, fragmentNode );
  12857. }
  12858. builder.stack.outputNode = resultNode;
  12859. builder.addFlow( 'fragment', builder.removeStack() );
  12860. // < OBSERVER >
  12861. builder.observer = this.setupObserver( builder );
  12862. }
  12863. /**
  12864. * Setups the clipping node.
  12865. *
  12866. * @param {NodeBuilder} builder - The current node builder.
  12867. * @return {ClippingNode} The clipping node.
  12868. */
  12869. setupClipping( builder ) {
  12870. if ( builder.clippingContext === null ) return null;
  12871. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  12872. let result = null;
  12873. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  12874. const samples = builder.renderer.samples;
  12875. if ( this.alphaToCoverage && samples > 1 ) {
  12876. // to be added to flow when the color/alpha value has been determined
  12877. result = clippingAlpha();
  12878. } else {
  12879. builder.stack.add( clipping() );
  12880. }
  12881. }
  12882. return result;
  12883. }
  12884. /**
  12885. * Setups the hardware clipping if available on the current device.
  12886. *
  12887. * @param {NodeBuilder} builder - The current node builder.
  12888. */
  12889. setupHardwareClipping( builder ) {
  12890. this.hardwareClipping = false;
  12891. if ( builder.clippingContext === null ) return;
  12892. const candidateCount = builder.clippingContext.unionPlanes.length;
  12893. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  12894. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  12895. builder.stack.add( hardwareClipping() );
  12896. this.hardwareClipping = true;
  12897. }
  12898. return;
  12899. }
  12900. /**
  12901. * Setups the depth of this material.
  12902. *
  12903. * @param {NodeBuilder} builder - The current node builder.
  12904. */
  12905. setupDepth( builder ) {
  12906. const { renderer, camera } = builder;
  12907. // Depth
  12908. let depthNode = this.depthNode;
  12909. if ( depthNode === null ) {
  12910. const mrt = renderer.getMRT();
  12911. if ( mrt && mrt.has( 'depth' ) ) {
  12912. depthNode = mrt.get( 'depth' );
  12913. } else if ( renderer.logarithmicDepthBuffer === true ) {
  12914. if ( camera.isPerspectiveCamera ) {
  12915. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  12916. } else {
  12917. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12918. }
  12919. }
  12920. }
  12921. if ( depthNode !== null ) {
  12922. depth.assign( depthNode ).toStack();
  12923. }
  12924. }
  12925. /**
  12926. * Setups the position node in view space. This method exists
  12927. * so derived node materials can modify the implementation e.g. sprite materials.
  12928. *
  12929. * @param {NodeBuilder} builder - The current node builder.
  12930. * @return {Node<vec3>} The position in view space.
  12931. */
  12932. setupPositionView( /*builder*/ ) {
  12933. return modelViewMatrix.mul( positionLocal ).xyz;
  12934. }
  12935. /**
  12936. * Setups the position in clip space.
  12937. *
  12938. * @param {NodeBuilder} builder - The current node builder.
  12939. * @return {Node<vec4>} The position in view space.
  12940. */
  12941. setupModelViewProjection( /*builder*/ ) {
  12942. return cameraProjectionMatrix.mul( positionView );
  12943. }
  12944. /**
  12945. * Setups the logic for the vertex stage.
  12946. *
  12947. * @param {NodeBuilder} builder - The current node builder.
  12948. * @return {Node<vec4>} The position in clip space.
  12949. */
  12950. setupVertex( builder ) {
  12951. builder.addStack();
  12952. this.setupPosition( builder );
  12953. builder.context.vertex = builder.removeStack();
  12954. return modelViewProjection;
  12955. }
  12956. /**
  12957. * Setups the computation of the position in local space.
  12958. *
  12959. * @param {NodeBuilder} builder - The current node builder.
  12960. * @return {Node<vec3>} The position in local space.
  12961. */
  12962. setupPosition( builder ) {
  12963. const { object, geometry } = builder;
  12964. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  12965. morphReference( object ).toStack();
  12966. }
  12967. if ( object.isSkinnedMesh === true ) {
  12968. skinning( object ).toStack();
  12969. }
  12970. if ( this.displacementMap ) {
  12971. const displacementMap = materialReference( 'displacementMap', 'texture' );
  12972. const displacementScale = materialReference( 'displacementScale', 'float' );
  12973. const displacementBias = materialReference( 'displacementBias', 'float' );
  12974. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  12975. }
  12976. if ( object.isBatchedMesh ) {
  12977. batch( object ).toStack();
  12978. }
  12979. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  12980. instancedMesh( object ).toStack();
  12981. }
  12982. if ( this.positionNode !== null ) {
  12983. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  12984. }
  12985. return positionLocal;
  12986. }
  12987. /**
  12988. * Setups the computation of the material's diffuse color.
  12989. *
  12990. * @param {NodeBuilder} builder - The current node builder.
  12991. * @param {BufferGeometry} geometry - The geometry.
  12992. */
  12993. setupDiffuseColor( { object, geometry } ) {
  12994. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  12995. // VERTEX COLORS
  12996. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  12997. colorNode = colorNode.mul( vertexColor() );
  12998. }
  12999. // Instanced colors
  13000. if ( object.instanceColor ) {
  13001. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  13002. colorNode = instanceColor.mul( colorNode );
  13003. }
  13004. if ( object.isBatchedMesh && object._colorsTexture ) {
  13005. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  13006. colorNode = batchColor.mul( colorNode );
  13007. }
  13008. // COLOR
  13009. diffuseColor.assign( colorNode );
  13010. // OPACITY
  13011. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13012. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  13013. // ALPHA TEST
  13014. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  13015. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  13016. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  13017. }
  13018. // ALPHA HASH
  13019. if ( this.alphaHash === true ) {
  13020. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  13021. }
  13022. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  13023. diffuseColor.a.assign( 1.0 );
  13024. }
  13025. }
  13026. /**
  13027. * Abstract interface method that can be implemented by derived materials
  13028. * to setup material-specific node variables.
  13029. *
  13030. * @abstract
  13031. * @param {NodeBuilder} builder - The current node builder.
  13032. */
  13033. setupVariants( /*builder*/ ) {
  13034. // Interface function.
  13035. }
  13036. /**
  13037. * Setups the outgoing light node variable
  13038. *
  13039. * @return {Node<vec3>} The outgoing light node.
  13040. */
  13041. setupOutgoingLight() {
  13042. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  13043. }
  13044. /**
  13045. * Setups the normal node from the material.
  13046. *
  13047. * @return {Node<vec3>} The normal node.
  13048. */
  13049. setupNormal() {
  13050. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  13051. }
  13052. /**
  13053. * Setups the environment node from the material.
  13054. *
  13055. * @param {NodeBuilder} builder - The current node builder.
  13056. * @return {Node<vec4>} The environment node.
  13057. */
  13058. setupEnvironment( /*builder*/ ) {
  13059. let node = null;
  13060. if ( this.envNode ) {
  13061. node = this.envNode;
  13062. } else if ( this.envMap ) {
  13063. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  13064. }
  13065. return node;
  13066. }
  13067. /**
  13068. * Setups the light map node from the material.
  13069. *
  13070. * @param {NodeBuilder} builder - The current node builder.
  13071. * @return {Node<vec3>} The light map node.
  13072. */
  13073. setupLightMap( builder ) {
  13074. let node = null;
  13075. if ( builder.material.lightMap ) {
  13076. node = new IrradianceNode( materialLightMap );
  13077. }
  13078. return node;
  13079. }
  13080. /**
  13081. * Setups the lights node based on the scene, environment and material.
  13082. *
  13083. * @param {NodeBuilder} builder - The current node builder.
  13084. * @return {LightsNode} The lights node.
  13085. */
  13086. setupLights( builder ) {
  13087. const materialLightsNode = [];
  13088. //
  13089. const envNode = this.setupEnvironment( builder );
  13090. if ( envNode && envNode.isLightingNode ) {
  13091. materialLightsNode.push( envNode );
  13092. }
  13093. const lightMapNode = this.setupLightMap( builder );
  13094. if ( lightMapNode && lightMapNode.isLightingNode ) {
  13095. materialLightsNode.push( lightMapNode );
  13096. }
  13097. if ( this.aoNode !== null || builder.material.aoMap ) {
  13098. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  13099. materialLightsNode.push( new AONode( aoNode ) );
  13100. }
  13101. let lightsN = this.lightsNode || builder.lightsNode;
  13102. if ( materialLightsNode.length > 0 ) {
  13103. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  13104. }
  13105. return lightsN;
  13106. }
  13107. /**
  13108. * This method should be implemented by most derived materials
  13109. * since it defines the material's lighting model.
  13110. *
  13111. * @abstract
  13112. * @param {NodeBuilder} builder - The current node builder.
  13113. * @return {LightingModel} The lighting model.
  13114. */
  13115. setupLightingModel( /*builder*/ ) {
  13116. // Interface function.
  13117. }
  13118. /**
  13119. * Setups the outgoing light node.
  13120. *
  13121. * @param {NodeBuilder} builder - The current node builder.
  13122. * @return {Node<vec3>} The outgoing light node.
  13123. */
  13124. setupLighting( builder ) {
  13125. const { material } = builder;
  13126. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  13127. // OUTGOING LIGHT
  13128. const lights = this.lights === true || this.lightsNode !== null;
  13129. const lightsNode = lights ? this.setupLights( builder ) : null;
  13130. let outgoingLightNode = this.setupOutgoingLight( builder );
  13131. if ( lightsNode && lightsNode.getScope().hasLights ) {
  13132. const lightingModel = this.setupLightingModel( builder ) || null;
  13133. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  13134. } else if ( backdropNode !== null ) {
  13135. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  13136. }
  13137. // EMISSIVE
  13138. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  13139. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  13140. outgoingLightNode = outgoingLightNode.add( emissive );
  13141. }
  13142. return outgoingLightNode;
  13143. }
  13144. /**
  13145. * Setup the fog.
  13146. *
  13147. * @param {NodeBuilder} builder - The current node builder.
  13148. * @param {Node<vec4>} outputNode - The existing output node.
  13149. * @return {Node<vec4>} The output node.
  13150. */
  13151. setupFog( builder, outputNode ) {
  13152. const fogNode = builder.fogNode;
  13153. if ( fogNode ) {
  13154. output.assign( outputNode );
  13155. outputNode = vec4( fogNode );
  13156. }
  13157. return outputNode;
  13158. }
  13159. /**
  13160. * Setups the output node.
  13161. *
  13162. * @param {NodeBuilder} builder - The current node builder.
  13163. * @param {Node<vec4>} outputNode - The existing output node.
  13164. * @return {Node<vec4>} The output node.
  13165. */
  13166. setupOutput( builder, outputNode ) {
  13167. // FOG
  13168. if ( this.fog === true ) {
  13169. outputNode = this.setupFog( builder, outputNode );
  13170. }
  13171. return outputNode;
  13172. }
  13173. /**
  13174. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  13175. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  13176. * defining all material properties of the classic type in the node type.
  13177. *
  13178. * @param {Material} material - The material to copy properties with their values to this node material.
  13179. */
  13180. setDefaultValues( material ) {
  13181. // This approach is to reuse the native refreshUniforms*
  13182. // and turn available the use of features like transmission and environment in core
  13183. for ( const property in material ) {
  13184. const value = material[ property ];
  13185. if ( this[ property ] === undefined ) {
  13186. this[ property ] = value;
  13187. if ( value && value.clone ) this[ property ] = value.clone();
  13188. }
  13189. }
  13190. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  13191. for ( const key in descriptors ) {
  13192. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  13193. descriptors[ key ].get !== undefined ) {
  13194. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  13195. }
  13196. }
  13197. }
  13198. /**
  13199. * Serializes this material to JSON.
  13200. *
  13201. * @param {?(Object|string)} meta - The meta information for serialization.
  13202. * @return {Object} The serialized node.
  13203. */
  13204. toJSON( meta ) {
  13205. const isRoot = ( meta === undefined || typeof meta === 'string' );
  13206. if ( isRoot ) {
  13207. meta = {
  13208. textures: {},
  13209. images: {},
  13210. nodes: {}
  13211. };
  13212. }
  13213. const data = Material.prototype.toJSON.call( this, meta );
  13214. const nodeChildren = getNodeChildren( this );
  13215. data.inputNodes = {};
  13216. for ( const { property, childNode } of nodeChildren ) {
  13217. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  13218. }
  13219. // TODO: Copied from Object3D.toJSON
  13220. function extractFromCache( cache ) {
  13221. const values = [];
  13222. for ( const key in cache ) {
  13223. const data = cache[ key ];
  13224. delete data.metadata;
  13225. values.push( data );
  13226. }
  13227. return values;
  13228. }
  13229. if ( isRoot ) {
  13230. const textures = extractFromCache( meta.textures );
  13231. const images = extractFromCache( meta.images );
  13232. const nodes = extractFromCache( meta.nodes );
  13233. if ( textures.length > 0 ) data.textures = textures;
  13234. if ( images.length > 0 ) data.images = images;
  13235. if ( nodes.length > 0 ) data.nodes = nodes;
  13236. }
  13237. return data;
  13238. }
  13239. /**
  13240. * Copies the properties of the given node material to this instance.
  13241. *
  13242. * @param {NodeMaterial} source - The material to copy.
  13243. * @return {NodeMaterial} A reference to this node material.
  13244. */
  13245. copy( source ) {
  13246. this.lightsNode = source.lightsNode;
  13247. this.envNode = source.envNode;
  13248. this.colorNode = source.colorNode;
  13249. this.normalNode = source.normalNode;
  13250. this.opacityNode = source.opacityNode;
  13251. this.backdropNode = source.backdropNode;
  13252. this.backdropAlphaNode = source.backdropAlphaNode;
  13253. this.alphaTestNode = source.alphaTestNode;
  13254. this.positionNode = source.positionNode;
  13255. this.geometryNode = source.geometryNode;
  13256. this.depthNode = source.depthNode;
  13257. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  13258. this.castShadowPositionNode = source.castShadowPositionNode;
  13259. this.receivedShadowNode = source.receivedShadowNode;
  13260. this.castShadowNode = source.castShadowNode;
  13261. this.outputNode = source.outputNode;
  13262. this.mrtNode = source.mrtNode;
  13263. this.fragmentNode = source.fragmentNode;
  13264. this.vertexNode = source.vertexNode;
  13265. return super.copy( source );
  13266. }
  13267. }
  13268. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  13269. /**
  13270. * Node material version of {@link LineBasicMaterial}.
  13271. *
  13272. * @augments NodeMaterial
  13273. */
  13274. class LineBasicNodeMaterial extends NodeMaterial {
  13275. static get type() {
  13276. return 'LineBasicNodeMaterial';
  13277. }
  13278. /**
  13279. * Constructs a new line basic node material.
  13280. *
  13281. * @param {Object} [parameters] - The configuration parameter.
  13282. */
  13283. constructor( parameters ) {
  13284. super();
  13285. /**
  13286. * This flag can be used for type testing.
  13287. *
  13288. * @type {boolean}
  13289. * @readonly
  13290. * @default true
  13291. */
  13292. this.isLineBasicNodeMaterial = true;
  13293. this.setDefaultValues( _defaultValues$d );
  13294. this.setValues( parameters );
  13295. }
  13296. }
  13297. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  13298. /**
  13299. * Node material version of {@link LineDashedMaterial}.
  13300. *
  13301. * @augments NodeMaterial
  13302. */
  13303. class LineDashedNodeMaterial extends NodeMaterial {
  13304. static get type() {
  13305. return 'LineDashedNodeMaterial';
  13306. }
  13307. /**
  13308. * Constructs a new line dashed node material.
  13309. *
  13310. * @param {Object} [parameters] - The configuration parameter.
  13311. */
  13312. constructor( parameters ) {
  13313. super();
  13314. /**
  13315. * This flag can be used for type testing.
  13316. *
  13317. * @type {boolean}
  13318. * @readonly
  13319. * @default true
  13320. */
  13321. this.isLineDashedNodeMaterial = true;
  13322. this.setDefaultValues( _defaultValues$c );
  13323. /**
  13324. * The dash offset.
  13325. *
  13326. * @type {number}
  13327. * @default 0
  13328. */
  13329. this.dashOffset = 0;
  13330. /**
  13331. * The offset of dash materials is by default inferred from the `dashOffset`
  13332. * property. This node property allows to overwrite the default
  13333. * and define the offset with a node instead.
  13334. *
  13335. * If you don't want to overwrite the offset but modify the existing
  13336. * value instead, use {@link materialLineDashOffset}.
  13337. *
  13338. * @type {?Node<float>}
  13339. * @default null
  13340. */
  13341. this.offsetNode = null;
  13342. /**
  13343. * The scale of dash materials is by default inferred from the `scale`
  13344. * property. This node property allows to overwrite the default
  13345. * and define the scale with a node instead.
  13346. *
  13347. * If you don't want to overwrite the scale but modify the existing
  13348. * value instead, use {@link materialLineScale}.
  13349. *
  13350. * @type {?Node<float>}
  13351. * @default null
  13352. */
  13353. this.dashScaleNode = null;
  13354. /**
  13355. * The dash size of dash materials is by default inferred from the `dashSize`
  13356. * property. This node property allows to overwrite the default
  13357. * and define the dash size with a node instead.
  13358. *
  13359. * If you don't want to overwrite the dash size but modify the existing
  13360. * value instead, use {@link materialLineDashSize}.
  13361. *
  13362. * @type {?Node<float>}
  13363. * @default null
  13364. */
  13365. this.dashSizeNode = null;
  13366. /**
  13367. * The gap size of dash materials is by default inferred from the `gapSize`
  13368. * property. This node property allows to overwrite the default
  13369. * and define the gap size with a node instead.
  13370. *
  13371. * If you don't want to overwrite the gap size but modify the existing
  13372. * value instead, use {@link materialLineGapSize}.
  13373. *
  13374. * @type {?Node<float>}
  13375. * @default null
  13376. */
  13377. this.gapSizeNode = null;
  13378. this.setValues( parameters );
  13379. }
  13380. /**
  13381. * Setups the dash specific node variables.
  13382. *
  13383. * @param {NodeBuilder} builder - The current node builder.
  13384. */
  13385. setupVariants( /* builder */ ) {
  13386. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13387. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13388. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13389. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13390. dashSize.assign( dashSizeNode );
  13391. gapSize.assign( gapSizeNode );
  13392. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  13393. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  13394. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  13395. }
  13396. }
  13397. let _sharedFramebuffer = null;
  13398. /**
  13399. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  13400. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  13401. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  13402. *
  13403. * @augments ViewportTextureNode
  13404. */
  13405. class ViewportSharedTextureNode extends ViewportTextureNode {
  13406. static get type() {
  13407. return 'ViewportSharedTextureNode';
  13408. }
  13409. /**
  13410. * Constructs a new viewport shared texture node.
  13411. *
  13412. * @param {Node} [uvNode=screenUV] - The uv node.
  13413. * @param {?Node} [levelNode=null] - The level node.
  13414. */
  13415. constructor( uvNode = screenUV, levelNode = null ) {
  13416. if ( _sharedFramebuffer === null ) {
  13417. _sharedFramebuffer = new FramebufferTexture();
  13418. }
  13419. super( uvNode, levelNode, _sharedFramebuffer );
  13420. }
  13421. updateReference() {
  13422. return this;
  13423. }
  13424. }
  13425. /**
  13426. * TSL function for creating a shared viewport texture node.
  13427. *
  13428. * @tsl
  13429. * @function
  13430. * @param {?Node} [uvNode=screenUV] - The uv node.
  13431. * @param {?Node} [levelNode=null] - The level node.
  13432. * @returns {ViewportSharedTextureNode}
  13433. */
  13434. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  13435. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  13436. /**
  13437. * This node material can be used to render lines with a size larger than one
  13438. * by representing them as instanced meshes.
  13439. *
  13440. * @augments NodeMaterial
  13441. */
  13442. class Line2NodeMaterial extends NodeMaterial {
  13443. static get type() {
  13444. return 'Line2NodeMaterial';
  13445. }
  13446. /**
  13447. * Constructs a new node material for wide line rendering.
  13448. *
  13449. * @param {Object} [parameters={}] - The configuration parameter.
  13450. */
  13451. constructor( parameters = {} ) {
  13452. super();
  13453. /**
  13454. * This flag can be used for type testing.
  13455. *
  13456. * @type {boolean}
  13457. * @readonly
  13458. * @default true
  13459. */
  13460. this.isLine2NodeMaterial = true;
  13461. this.setDefaultValues( _defaultValues$b );
  13462. /**
  13463. * Whether vertex colors should be used or not.
  13464. *
  13465. * @type {boolean}
  13466. * @default false
  13467. */
  13468. this.useColor = parameters.vertexColors;
  13469. /**
  13470. * The dash offset.
  13471. *
  13472. * @type {number}
  13473. * @default 0
  13474. */
  13475. this.dashOffset = 0;
  13476. /**
  13477. * The line width.
  13478. *
  13479. * @type {number}
  13480. * @default 0
  13481. */
  13482. this.lineWidth = 1;
  13483. /**
  13484. * Defines the lines color.
  13485. *
  13486. * @type {?Node<vec3>}
  13487. * @default null
  13488. */
  13489. this.lineColorNode = null;
  13490. /**
  13491. * Defines the offset.
  13492. *
  13493. * @type {?Node<float>}
  13494. * @default null
  13495. */
  13496. this.offsetNode = null;
  13497. /**
  13498. * Defines the dash scale.
  13499. *
  13500. * @type {?Node<float>}
  13501. * @default null
  13502. */
  13503. this.dashScaleNode = null;
  13504. /**
  13505. * Defines the dash size.
  13506. *
  13507. * @type {?Node<float>}
  13508. * @default null
  13509. */
  13510. this.dashSizeNode = null;
  13511. /**
  13512. * Defines the gap size.
  13513. *
  13514. * @type {?Node<float>}
  13515. * @default null
  13516. */
  13517. this.gapSizeNode = null;
  13518. /**
  13519. * Blending is set to `NoBlending` since transparency
  13520. * is not supported, yet.
  13521. *
  13522. * @type {number}
  13523. * @default 0
  13524. */
  13525. this.blending = NoBlending;
  13526. this._useDash = parameters.dashed;
  13527. this._useAlphaToCoverage = true;
  13528. this._useWorldUnits = false;
  13529. this.setValues( parameters );
  13530. }
  13531. /**
  13532. * Setups the vertex and fragment stage of this node material.
  13533. *
  13534. * @param {NodeBuilder} builder - The current node builder.
  13535. */
  13536. setup( builder ) {
  13537. const { renderer } = builder;
  13538. const useAlphaToCoverage = this._useAlphaToCoverage;
  13539. const useColor = this.useColor;
  13540. const useDash = this._useDash;
  13541. const useWorldUnits = this._useWorldUnits;
  13542. const trimSegment = Fn( ( { start, end } ) => {
  13543. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  13544. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  13545. const nearEstimate = b.mul( -0.5 ).div( a );
  13546. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  13547. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  13548. } ).setLayout( {
  13549. name: 'trimSegment',
  13550. type: 'vec4',
  13551. inputs: [
  13552. { name: 'start', type: 'vec4' },
  13553. { name: 'end', type: 'vec4' }
  13554. ]
  13555. } );
  13556. this.vertexNode = Fn( () => {
  13557. const instanceStart = attribute( 'instanceStart' );
  13558. const instanceEnd = attribute( 'instanceEnd' );
  13559. // camera space
  13560. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  13561. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  13562. if ( useDash ) {
  13563. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13564. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13565. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  13566. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  13567. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  13568. lineDistance = lineDistance.add( offsetNode );
  13569. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  13570. }
  13571. if ( useWorldUnits ) {
  13572. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  13573. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  13574. }
  13575. const aspect = viewport.z.div( viewport.w );
  13576. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  13577. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  13578. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  13579. // perhaps there is a more elegant solution -- WestLangley
  13580. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  13581. If( perspective, () => {
  13582. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  13583. end.assign( trimSegment( { start: start, end: end } ) );
  13584. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  13585. start.assign( trimSegment( { start: end, end: start } ) );
  13586. } );
  13587. } );
  13588. // clip space
  13589. const clipStart = cameraProjectionMatrix.mul( start );
  13590. const clipEnd = cameraProjectionMatrix.mul( end );
  13591. // ndc space
  13592. const ndcStart = clipStart.xyz.div( clipStart.w );
  13593. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  13594. // direction
  13595. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  13596. // account for clip-space aspect ratio
  13597. dir.x.assign( dir.x.mul( aspect ) );
  13598. dir.assign( dir.normalize() );
  13599. const clip = vec4().toVar();
  13600. if ( useWorldUnits ) {
  13601. // get the offset direction as perpendicular to the view vector
  13602. const worldDir = end.xyz.sub( start.xyz ).normalize();
  13603. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  13604. const worldUp = worldDir.cross( tmpFwd ).normalize();
  13605. const worldFwd = worldDir.cross( worldUp );
  13606. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  13607. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  13608. // height offset
  13609. const hw = materialLineWidth.mul( 0.5 );
  13610. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  13611. // don't extend the line if we're rendering dashes because we
  13612. // won't be rendering the endcaps
  13613. if ( ! useDash ) {
  13614. // cap extension
  13615. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  13616. // add width to the box
  13617. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  13618. // endcaps
  13619. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  13620. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  13621. } );
  13622. }
  13623. // project the worldpos
  13624. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  13625. // shift the depth of the projected points so the line
  13626. // segments overlap neatly
  13627. const clipPose = vec3().toVar();
  13628. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  13629. clip.z.assign( clipPose.z.mul( clip.w ) );
  13630. } else {
  13631. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  13632. // undo aspect ratio adjustment
  13633. dir.x.assign( dir.x.div( aspect ) );
  13634. offset.x.assign( offset.x.div( aspect ) );
  13635. // sign flip
  13636. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  13637. // endcaps
  13638. If( positionGeometry.y.lessThan( 0.0 ), () => {
  13639. offset.assign( offset.sub( dir ) );
  13640. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  13641. offset.assign( offset.add( dir ) );
  13642. } );
  13643. // adjust for linewidth
  13644. offset.assign( offset.mul( materialLineWidth ) );
  13645. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  13646. offset.assign( offset.div( viewport.w ) );
  13647. // select end
  13648. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  13649. // back to clip space
  13650. offset.assign( offset.mul( clip.w ) );
  13651. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  13652. }
  13653. return clip;
  13654. } )();
  13655. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  13656. const p13 = p1.sub( p3 );
  13657. const p43 = p4.sub( p3 );
  13658. const p21 = p2.sub( p1 );
  13659. const d1343 = p13.dot( p43 );
  13660. const d4321 = p43.dot( p21 );
  13661. const d1321 = p13.dot( p21 );
  13662. const d4343 = p43.dot( p43 );
  13663. const d2121 = p21.dot( p21 );
  13664. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  13665. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  13666. const mua = numer.div( denom ).clamp();
  13667. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  13668. return vec2( mua, mub );
  13669. } );
  13670. this.colorNode = Fn( () => {
  13671. const vUv = uv();
  13672. if ( useDash ) {
  13673. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13674. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13675. dashSize.assign( dashSizeNode );
  13676. gapSize.assign( gapSizeNode );
  13677. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  13678. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  13679. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  13680. }
  13681. const alpha = float( 1 ).toVar( 'alpha' );
  13682. if ( useWorldUnits ) {
  13683. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  13684. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  13685. // Find the closest points on the view ray and the line segment
  13686. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  13687. const lineDir = worldEnd.sub( worldStart );
  13688. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  13689. const p1 = worldStart.add( lineDir.mul( params.x ) );
  13690. const p2 = rayEnd.mul( params.y );
  13691. const delta = p1.sub( p2 );
  13692. const len = delta.length();
  13693. const norm = len.div( materialLineWidth );
  13694. if ( ! useDash ) {
  13695. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  13696. const dnorm = norm.fwidth();
  13697. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  13698. } else {
  13699. norm.greaterThan( 0.5 ).discard();
  13700. }
  13701. }
  13702. } else {
  13703. // round endcaps
  13704. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  13705. const a = vUv.x;
  13706. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  13707. const len2 = a.mul( a ).add( b.mul( b ) );
  13708. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  13709. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  13710. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  13711. } );
  13712. } else {
  13713. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  13714. const a = vUv.x;
  13715. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  13716. const len2 = a.mul( a ).add( b.mul( b ) );
  13717. len2.greaterThan( 1.0 ).discard();
  13718. } );
  13719. }
  13720. }
  13721. let lineColorNode;
  13722. if ( this.lineColorNode ) {
  13723. lineColorNode = this.lineColorNode;
  13724. } else {
  13725. if ( useColor ) {
  13726. const instanceColorStart = attribute( 'instanceColorStart' );
  13727. const instanceColorEnd = attribute( 'instanceColorEnd' );
  13728. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  13729. lineColorNode = instanceColor.mul( materialColor );
  13730. } else {
  13731. lineColorNode = materialColor;
  13732. }
  13733. }
  13734. return vec4( lineColorNode, alpha );
  13735. } )();
  13736. if ( this.transparent ) {
  13737. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13738. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  13739. }
  13740. super.setup( builder );
  13741. }
  13742. /**
  13743. * Whether the lines should sized in world units or not.
  13744. * When set to `false` the unit is pixel.
  13745. *
  13746. * @type {boolean}
  13747. * @default false
  13748. */
  13749. get worldUnits() {
  13750. return this._useWorldUnits;
  13751. }
  13752. set worldUnits( value ) {
  13753. if ( this._useWorldUnits !== value ) {
  13754. this._useWorldUnits = value;
  13755. this.needsUpdate = true;
  13756. }
  13757. }
  13758. /**
  13759. * Whether the lines should be dashed or not.
  13760. *
  13761. * @type {boolean}
  13762. * @default false
  13763. */
  13764. get dashed() {
  13765. return this._useDash;
  13766. }
  13767. set dashed( value ) {
  13768. if ( this._useDash !== value ) {
  13769. this._useDash = value;
  13770. this.needsUpdate = true;
  13771. }
  13772. }
  13773. /**
  13774. * Whether alpha to coverage should be used or not.
  13775. *
  13776. * @type {boolean}
  13777. * @default true
  13778. */
  13779. get alphaToCoverage() {
  13780. return this._useAlphaToCoverage;
  13781. }
  13782. set alphaToCoverage( value ) {
  13783. if ( this._useAlphaToCoverage !== value ) {
  13784. this._useAlphaToCoverage = value;
  13785. this.needsUpdate = true;
  13786. }
  13787. }
  13788. }
  13789. /**
  13790. * Packs a direction vector into a color value.
  13791. *
  13792. * @tsl
  13793. * @function
  13794. * @param {Node<vec3>} node - The direction to pack.
  13795. * @return {Node<vec3>} The color.
  13796. */
  13797. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  13798. /**
  13799. * Unpacks a color value into a direction vector.
  13800. *
  13801. * @tsl
  13802. * @function
  13803. * @param {Node<vec3>} node - The color to unpack.
  13804. * @return {Node<vec3>} The direction.
  13805. */
  13806. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  13807. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  13808. /**
  13809. * Node material version of {@link MeshNormalMaterial}.
  13810. *
  13811. * @augments NodeMaterial
  13812. */
  13813. class MeshNormalNodeMaterial extends NodeMaterial {
  13814. static get type() {
  13815. return 'MeshNormalNodeMaterial';
  13816. }
  13817. /**
  13818. * Constructs a new mesh normal node material.
  13819. *
  13820. * @param {Object} [parameters] - The configuration parameter.
  13821. */
  13822. constructor( parameters ) {
  13823. super();
  13824. /**
  13825. * This flag can be used for type testing.
  13826. *
  13827. * @type {boolean}
  13828. * @readonly
  13829. * @default true
  13830. */
  13831. this.isMeshNormalNodeMaterial = true;
  13832. this.setDefaultValues( _defaultValues$a );
  13833. this.setValues( parameters );
  13834. }
  13835. /**
  13836. * Overwrites the default implementation by computing the diffuse color
  13837. * based on the normal data.
  13838. */
  13839. setupDiffuseColor() {
  13840. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13841. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  13842. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( transformedNormalView ), opacityNode ), SRGBColorSpace ) );
  13843. }
  13844. }
  13845. /**
  13846. * Can be used to compute texture coordinates for projecting an
  13847. * equirectangular texture onto a mesh for using it as the scene's
  13848. * background.
  13849. *
  13850. * ```js
  13851. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  13852. * ```
  13853. *
  13854. * @augments TempNode
  13855. */
  13856. class EquirectUVNode extends TempNode {
  13857. static get type() {
  13858. return 'EquirectUVNode';
  13859. }
  13860. /**
  13861. * Constructs a new equirect uv node.
  13862. *
  13863. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  13864. */
  13865. constructor( dirNode = positionWorldDirection ) {
  13866. super( 'vec2' );
  13867. /**
  13868. * A direction vector for sampling why is by default `positionWorldDirection`.
  13869. *
  13870. * @type {Node<vec3>}
  13871. */
  13872. this.dirNode = dirNode;
  13873. }
  13874. setup() {
  13875. const dir = this.dirNode;
  13876. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  13877. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  13878. return vec2( u, v );
  13879. }
  13880. }
  13881. /**
  13882. * TSL function for creating an equirect uv node.
  13883. *
  13884. * @tsl
  13885. * @function
  13886. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  13887. * @returns {EquirectUVNode}
  13888. */
  13889. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode ).setParameterLength( 0, 1 );
  13890. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  13891. /**
  13892. * This class represents a cube render target. It is a special version
  13893. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  13894. *
  13895. * @augments WebGLCubeRenderTarget
  13896. */
  13897. class CubeRenderTarget extends WebGLCubeRenderTarget {
  13898. /**
  13899. * Constructs a new cube render target.
  13900. *
  13901. * @param {number} [size=1] - The size of the render target.
  13902. * @param {RenderTarget~Options} [options] - The configuration object.
  13903. */
  13904. constructor( size = 1, options = {} ) {
  13905. super( size, options );
  13906. /**
  13907. * This flag can be used for type testing.
  13908. *
  13909. * @type {boolean}
  13910. * @readonly
  13911. * @default true
  13912. */
  13913. this.isCubeRenderTarget = true;
  13914. }
  13915. /**
  13916. * Converts the given equirectangular texture to a cube map.
  13917. *
  13918. * @param {Renderer} renderer - The renderer.
  13919. * @param {Texture} texture - The equirectangular texture.
  13920. * @return {CubeRenderTarget} A reference to this cube render target.
  13921. */
  13922. fromEquirectangularTexture( renderer, texture$1 ) {
  13923. const currentMinFilter = texture$1.minFilter;
  13924. const currentGenerateMipmaps = texture$1.generateMipmaps;
  13925. texture$1.generateMipmaps = true;
  13926. this.texture.type = texture$1.type;
  13927. this.texture.colorSpace = texture$1.colorSpace;
  13928. this.texture.generateMipmaps = texture$1.generateMipmaps;
  13929. this.texture.minFilter = texture$1.minFilter;
  13930. this.texture.magFilter = texture$1.magFilter;
  13931. const geometry = new BoxGeometry( 5, 5, 5 );
  13932. const uvNode = equirectUV( positionWorldDirection );
  13933. const material = new NodeMaterial();
  13934. material.colorNode = texture( texture$1, uvNode, 0 );
  13935. material.side = BackSide;
  13936. material.blending = NoBlending;
  13937. const mesh = new Mesh( geometry, material );
  13938. const scene = new Scene();
  13939. scene.add( mesh );
  13940. // Avoid blurred poles
  13941. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  13942. const camera = new CubeCamera( 1, 10, this );
  13943. const currentMRT = renderer.getMRT();
  13944. renderer.setMRT( null );
  13945. camera.update( renderer, scene );
  13946. renderer.setMRT( currentMRT );
  13947. texture$1.minFilter = currentMinFilter;
  13948. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  13949. mesh.geometry.dispose();
  13950. mesh.material.dispose();
  13951. return this;
  13952. }
  13953. }
  13954. const _cache$1 = new WeakMap();
  13955. /**
  13956. * This node can be used to automatically convert environment maps in the
  13957. * equirectangular format into the cube map format.
  13958. *
  13959. * @augments TempNode
  13960. */
  13961. class CubeMapNode extends TempNode {
  13962. static get type() {
  13963. return 'CubeMapNode';
  13964. }
  13965. /**
  13966. * Constructs a new cube map node.
  13967. *
  13968. * @param {Node} envNode - The node representing the environment map.
  13969. */
  13970. constructor( envNode ) {
  13971. super( 'vec3' );
  13972. /**
  13973. * The node representing the environment map.
  13974. *
  13975. * @type {Node}
  13976. */
  13977. this.envNode = envNode;
  13978. /**
  13979. * A reference to the internal cube texture.
  13980. *
  13981. * @private
  13982. * @type {?CubeTexture}
  13983. * @default null
  13984. */
  13985. this._cubeTexture = null;
  13986. /**
  13987. * A reference to the internal cube texture node.
  13988. *
  13989. * @private
  13990. * @type {CubeTextureNode}
  13991. */
  13992. this._cubeTextureNode = cubeTexture( null );
  13993. const defaultTexture = new CubeTexture();
  13994. defaultTexture.isRenderTargetTexture = true;
  13995. /**
  13996. * A default cube texture that acts as a placeholder.
  13997. * It is used when the conversion from equirectangular to cube
  13998. * map has not finished yet for a given texture.
  13999. *
  14000. * @private
  14001. * @type {CubeTexture}
  14002. */
  14003. this._defaultTexture = defaultTexture;
  14004. /**
  14005. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14006. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  14007. *
  14008. * @type {string}
  14009. * @default 'render'
  14010. */
  14011. this.updateBeforeType = NodeUpdateType.RENDER;
  14012. }
  14013. updateBefore( frame ) {
  14014. const { renderer, material } = frame;
  14015. const envNode = this.envNode;
  14016. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14017. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14018. if ( texture && texture.isTexture ) {
  14019. const mapping = texture.mapping;
  14020. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  14021. // check for converted cubemap map
  14022. if ( _cache$1.has( texture ) ) {
  14023. const cubeMap = _cache$1.get( texture );
  14024. mapTextureMapping( cubeMap, texture.mapping );
  14025. this._cubeTexture = cubeMap;
  14026. } else {
  14027. // create cube map from equirectangular map
  14028. const image = texture.image;
  14029. if ( isEquirectangularMapReady$1( image ) ) {
  14030. const renderTarget = new CubeRenderTarget( image.height );
  14031. renderTarget.fromEquirectangularTexture( renderer, texture );
  14032. mapTextureMapping( renderTarget.texture, texture.mapping );
  14033. this._cubeTexture = renderTarget.texture;
  14034. _cache$1.set( texture, renderTarget.texture );
  14035. texture.addEventListener( 'dispose', onTextureDispose );
  14036. } else {
  14037. // default cube texture as fallback when equirectangular texture is not yet loaded
  14038. this._cubeTexture = this._defaultTexture;
  14039. }
  14040. }
  14041. //
  14042. this._cubeTextureNode.value = this._cubeTexture;
  14043. } else {
  14044. // envNode already refers to a cube map
  14045. this._cubeTextureNode = this.envNode;
  14046. }
  14047. }
  14048. }
  14049. }
  14050. setup( builder ) {
  14051. this.updateBefore( builder );
  14052. return this._cubeTextureNode;
  14053. }
  14054. }
  14055. /**
  14056. * Returns true if the given equirectangular image has been fully loaded
  14057. * and is ready for further processing.
  14058. *
  14059. * @private
  14060. * @param {Image} image - The equirectangular image to check.
  14061. * @return {boolean} Whether the image is ready or not.
  14062. */
  14063. function isEquirectangularMapReady$1( image ) {
  14064. if ( image === null || image === undefined ) return false;
  14065. return image.height > 0;
  14066. }
  14067. /**
  14068. * This function is executed when `dispose()` is called on the equirectangular
  14069. * texture. In this case, the generated cube map with its render target
  14070. * is deleted as well.
  14071. *
  14072. * @private
  14073. * @param {Object} event - The event object.
  14074. */
  14075. function onTextureDispose( event ) {
  14076. const texture = event.target;
  14077. texture.removeEventListener( 'dispose', onTextureDispose );
  14078. const renderTarget = _cache$1.get( texture );
  14079. if ( renderTarget !== undefined ) {
  14080. _cache$1.delete( texture );
  14081. renderTarget.dispose();
  14082. }
  14083. }
  14084. /**
  14085. * This function makes sure the generated cube map uses the correct
  14086. * texture mapping that corresponds to the equirectangular original.
  14087. *
  14088. * @private
  14089. * @param {Texture} texture - The cube texture.
  14090. * @param {number} mapping - The original texture mapping.
  14091. */
  14092. function mapTextureMapping( texture, mapping ) {
  14093. if ( mapping === EquirectangularReflectionMapping ) {
  14094. texture.mapping = CubeReflectionMapping;
  14095. } else if ( mapping === EquirectangularRefractionMapping ) {
  14096. texture.mapping = CubeRefractionMapping;
  14097. }
  14098. }
  14099. /**
  14100. * TSL function for creating a cube map node.
  14101. *
  14102. * @tsl
  14103. * @function
  14104. * @param {Node} envNode - The node representing the environment map.
  14105. * @returns {CubeMapNode}
  14106. */
  14107. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  14108. /**
  14109. * Represents a basic model for Image-based lighting (IBL). The environment
  14110. * is defined via environment maps in the equirectangular or cube map format.
  14111. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  14112. * or {@link MeshPhongNodeMaterial}.
  14113. *
  14114. * @augments LightingNode
  14115. */
  14116. class BasicEnvironmentNode extends LightingNode {
  14117. static get type() {
  14118. return 'BasicEnvironmentNode';
  14119. }
  14120. /**
  14121. * Constructs a new basic environment node.
  14122. *
  14123. * @param {Node} [envNode=null] - A node representing the environment.
  14124. */
  14125. constructor( envNode = null ) {
  14126. super();
  14127. /**
  14128. * A node representing the environment.
  14129. *
  14130. * @type {Node}
  14131. * @default null
  14132. */
  14133. this.envNode = envNode;
  14134. }
  14135. setup( builder ) {
  14136. // environment property is used in the finish() method of BasicLightingModel
  14137. builder.context.environment = cubeMapNode( this.envNode );
  14138. }
  14139. }
  14140. /**
  14141. * A specific version of {@link IrradianceNode} that is only relevant
  14142. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  14143. * requires a special scaling factor for the light map.
  14144. *
  14145. * @augments LightingNode
  14146. */
  14147. class BasicLightMapNode extends LightingNode {
  14148. static get type() {
  14149. return 'BasicLightMapNode';
  14150. }
  14151. /**
  14152. * Constructs a new basic light map node.
  14153. *
  14154. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  14155. */
  14156. constructor( lightMapNode = null ) {
  14157. super();
  14158. /**
  14159. * The light map node.
  14160. *
  14161. * @type {?Node<vec3>}
  14162. */
  14163. this.lightMapNode = lightMapNode;
  14164. }
  14165. setup( builder ) {
  14166. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  14167. const RECIPROCAL_PI = float( 1 / Math.PI );
  14168. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  14169. }
  14170. }
  14171. /**
  14172. * Abstract class for implementing lighting models. The module defines
  14173. * multiple methods that concrete lighting models can implement. These
  14174. * methods are executed at different points during the light evaluation
  14175. * process.
  14176. */
  14177. class LightingModel {
  14178. /**
  14179. * This method is intended for setting up lighting model and context data
  14180. * which are later used in the evaluation process.
  14181. *
  14182. * @abstract
  14183. * @param {NodeBuilder} builder - The current node builder.
  14184. */
  14185. start( builder ) {
  14186. // lights ( direct )
  14187. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  14188. // indirect
  14189. this.indirect( builder );
  14190. }
  14191. /**
  14192. * This method is intended for executing final tasks like final updates
  14193. * to the outgoing light.
  14194. *
  14195. * @abstract
  14196. * @param {NodeBuilder} builder - The current node builder.
  14197. */
  14198. finish( /*builder*/ ) { }
  14199. /**
  14200. * This method is intended for implementing the direct light term and
  14201. * executed during the build process of directional, point and spot light nodes.
  14202. *
  14203. * @abstract
  14204. * @param {Object} lightData - The light data.
  14205. * @param {NodeBuilder} builder - The current node builder.
  14206. */
  14207. direct( /*lightData, builder*/ ) { }
  14208. /**
  14209. * This method is intended for implementing the direct light term for
  14210. * rect area light nodes.
  14211. *
  14212. * @abstract
  14213. * @param {Object} lightData - The light data.
  14214. * @param {NodeBuilder} builder - The current node builder.
  14215. */
  14216. directRectArea( /*lightData, builder*/ ) {}
  14217. /**
  14218. * This method is intended for implementing the indirect light term.
  14219. *
  14220. * @abstract
  14221. * @param {NodeBuilder} builder - The current node builder.
  14222. */
  14223. indirect( /*builder*/ ) { }
  14224. /**
  14225. * This method is intended for implementing the ambient occlusion term.
  14226. * Unlike other methods, this method must be called manually by the lighting
  14227. * model in its indirect term.
  14228. *
  14229. * @abstract
  14230. * @param {NodeBuilder} builder - The current node builder.
  14231. */
  14232. ambientOcclusion( /*input, stack, builder*/ ) { }
  14233. }
  14234. /**
  14235. * Represents the lighting model for unlit materials. The only light contribution
  14236. * is baked indirect lighting modulated with ambient occlusion and the material's
  14237. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  14238. *
  14239. * @augments LightingModel
  14240. */
  14241. class BasicLightingModel extends LightingModel {
  14242. /**
  14243. * Constructs a new basic lighting model.
  14244. */
  14245. constructor() {
  14246. super();
  14247. }
  14248. /**
  14249. * Implements the baked indirect lighting with its modulation.
  14250. *
  14251. * @param {NodeBuilder} builder - The current node builder.
  14252. */
  14253. indirect( { context } ) {
  14254. const ambientOcclusion = context.ambientOcclusion;
  14255. const reflectedLight = context.reflectedLight;
  14256. const irradianceLightMap = context.irradianceLightMap;
  14257. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  14258. // accumulation (baked indirect lighting only)
  14259. if ( irradianceLightMap ) {
  14260. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  14261. } else {
  14262. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  14263. }
  14264. // modulation
  14265. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14266. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  14267. }
  14268. /**
  14269. * Implements the environment mapping.
  14270. *
  14271. * @param {NodeBuilder} builder - The current node builder.
  14272. */
  14273. finish( builder ) {
  14274. const { material, context } = builder;
  14275. const outgoingLight = context.outgoingLight;
  14276. const envNode = builder.context.environment;
  14277. if ( envNode ) {
  14278. switch ( material.combine ) {
  14279. case MultiplyOperation:
  14280. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  14281. break;
  14282. case MixOperation:
  14283. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  14284. break;
  14285. case AddOperation:
  14286. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  14287. break;
  14288. default:
  14289. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  14290. break;
  14291. }
  14292. }
  14293. }
  14294. }
  14295. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  14296. /**
  14297. * Node material version of {@link MeshBasicMaterial}.
  14298. *
  14299. * @augments NodeMaterial
  14300. */
  14301. class MeshBasicNodeMaterial extends NodeMaterial {
  14302. static get type() {
  14303. return 'MeshBasicNodeMaterial';
  14304. }
  14305. /**
  14306. * Constructs a new mesh basic node material.
  14307. *
  14308. * @param {Object} [parameters] - The configuration parameter.
  14309. */
  14310. constructor( parameters ) {
  14311. super();
  14312. /**
  14313. * This flag can be used for type testing.
  14314. *
  14315. * @type {boolean}
  14316. * @readonly
  14317. * @default true
  14318. */
  14319. this.isMeshBasicNodeMaterial = true;
  14320. /**
  14321. * Although the basic material is by definition unlit, we set
  14322. * this property to `true` since we use a lighting model to compute
  14323. * the outgoing light of the fragment shader.
  14324. *
  14325. * @type {boolean}
  14326. * @default true
  14327. */
  14328. this.lights = true;
  14329. this.setDefaultValues( _defaultValues$9 );
  14330. this.setValues( parameters );
  14331. }
  14332. /**
  14333. * Basic materials are not affected by normal and bump maps so we
  14334. * return by default {@link normalView}.
  14335. *
  14336. * @return {Node<vec3>} The normal node.
  14337. */
  14338. setupNormal() {
  14339. return normalView; // see #28839
  14340. }
  14341. /**
  14342. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14343. * to implement the default environment mapping.
  14344. *
  14345. * @param {NodeBuilder} builder - The current node builder.
  14346. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14347. */
  14348. setupEnvironment( builder ) {
  14349. const envNode = super.setupEnvironment( builder );
  14350. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14351. }
  14352. /**
  14353. * This method must be overwritten since light maps are evaluated
  14354. * with a special scaling factor for basic materials.
  14355. *
  14356. * @param {NodeBuilder} builder - The current node builder.
  14357. * @return {?BasicLightMapNode<vec3>} The light map node.
  14358. */
  14359. setupLightMap( builder ) {
  14360. let node = null;
  14361. if ( builder.material.lightMap ) {
  14362. node = new BasicLightMapNode( materialLightMap );
  14363. }
  14364. return node;
  14365. }
  14366. /**
  14367. * The material overwrites this method because `lights` is set to `true` but
  14368. * we still want to return the diffuse color as the outgoing light.
  14369. *
  14370. * @return {Node<vec3>} The outgoing light node.
  14371. */
  14372. setupOutgoingLight() {
  14373. return diffuseColor.rgb;
  14374. }
  14375. /**
  14376. * Setups the lighting model.
  14377. *
  14378. * @return {BasicLightingModel} The lighting model.
  14379. */
  14380. setupLightingModel() {
  14381. return new BasicLightingModel();
  14382. }
  14383. }
  14384. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  14385. // Original approximation by Christophe Schlick '94
  14386. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  14387. // Optimized variant (presented by Epic at SIGGRAPH '13)
  14388. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  14389. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  14390. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  14391. } ); // validated
  14392. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  14393. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  14394. } ); // validated
  14395. const G_BlinnPhong_Implicit = () => float( 0.25 );
  14396. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  14397. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  14398. } );
  14399. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14400. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14401. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  14402. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14403. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  14404. const G = G_BlinnPhong_Implicit();
  14405. const D = D_BlinnPhong( { dotNH } );
  14406. return F.mul( G ).mul( D );
  14407. } );
  14408. /**
  14409. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  14410. *
  14411. * @augments BasicLightingModel
  14412. */
  14413. class PhongLightingModel extends BasicLightingModel {
  14414. /**
  14415. * Constructs a new phong lighting model.
  14416. *
  14417. * @param {boolean} [specular=true] - Whether specular is supported or not.
  14418. */
  14419. constructor( specular = true ) {
  14420. super();
  14421. /**
  14422. * Whether specular is supported or not. Set this to `false` if you are
  14423. * looking for a Lambert-like material meaning a material for non-shiny
  14424. * surfaces, without specular highlights.
  14425. *
  14426. * @type {boolean}
  14427. * @default true
  14428. */
  14429. this.specular = specular;
  14430. }
  14431. /**
  14432. * Implements the direct lighting. The specular portion is optional an can be controlled
  14433. * with the {@link PhongLightingModel#specular} flag.
  14434. *
  14435. * @param {Object} lightData - The light data.
  14436. */
  14437. direct( { lightDirection, lightColor, reflectedLight } ) {
  14438. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14439. const irradiance = dotNL.mul( lightColor );
  14440. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14441. if ( this.specular === true ) {
  14442. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  14443. }
  14444. }
  14445. /**
  14446. * Implements the indirect lighting.
  14447. *
  14448. * @param {NodeBuilder} builder - The current node builder.
  14449. */
  14450. indirect( builder ) {
  14451. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  14452. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14453. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14454. }
  14455. }
  14456. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  14457. /**
  14458. * Node material version of {@link MeshLambertMaterial}.
  14459. *
  14460. * @augments NodeMaterial
  14461. */
  14462. class MeshLambertNodeMaterial extends NodeMaterial {
  14463. static get type() {
  14464. return 'MeshLambertNodeMaterial';
  14465. }
  14466. /**
  14467. * Constructs a new mesh lambert node material.
  14468. *
  14469. * @param {Object} [parameters] - The configuration parameter.
  14470. */
  14471. constructor( parameters ) {
  14472. super();
  14473. /**
  14474. * This flag can be used for type testing.
  14475. *
  14476. * @type {boolean}
  14477. * @readonly
  14478. * @default true
  14479. */
  14480. this.isMeshLambertNodeMaterial = true;
  14481. /**
  14482. * Set to `true` because lambert materials react on lights.
  14483. *
  14484. * @type {boolean}
  14485. * @default true
  14486. */
  14487. this.lights = true;
  14488. this.setDefaultValues( _defaultValues$8 );
  14489. this.setValues( parameters );
  14490. }
  14491. /**
  14492. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14493. * to implement the default environment mapping.
  14494. *
  14495. * @param {NodeBuilder} builder - The current node builder.
  14496. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14497. */
  14498. setupEnvironment( builder ) {
  14499. const envNode = super.setupEnvironment( builder );
  14500. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14501. }
  14502. /**
  14503. * Setups the lighting model.
  14504. *
  14505. * @return {PhongLightingModel} The lighting model.
  14506. */
  14507. setupLightingModel( /*builder*/ ) {
  14508. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  14509. }
  14510. }
  14511. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  14512. /**
  14513. * Node material version of {@link MeshPhongMaterial}.
  14514. *
  14515. * @augments NodeMaterial
  14516. */
  14517. class MeshPhongNodeMaterial extends NodeMaterial {
  14518. static get type() {
  14519. return 'MeshPhongNodeMaterial';
  14520. }
  14521. /**
  14522. * Constructs a new mesh lambert node material.
  14523. *
  14524. * @param {Object} [parameters] - The configuration parameter.
  14525. */
  14526. constructor( parameters ) {
  14527. super();
  14528. /**
  14529. * This flag can be used for type testing.
  14530. *
  14531. * @type {boolean}
  14532. * @readonly
  14533. * @default true
  14534. */
  14535. this.isMeshPhongNodeMaterial = true;
  14536. /**
  14537. * Set to `true` because phong materials react on lights.
  14538. *
  14539. * @type {boolean}
  14540. * @default true
  14541. */
  14542. this.lights = true;
  14543. /**
  14544. * The shininess of phong materials is by default inferred from the `shininess`
  14545. * property. This node property allows to overwrite the default
  14546. * and define the shininess with a node instead.
  14547. *
  14548. * If you don't want to overwrite the shininess but modify the existing
  14549. * value instead, use {@link materialShininess}.
  14550. *
  14551. * @type {?Node<float>}
  14552. * @default null
  14553. */
  14554. this.shininessNode = null;
  14555. /**
  14556. * The specular color of phong materials is by default inferred from the
  14557. * `specular` property. This node property allows to overwrite the default
  14558. * and define the specular color with a node instead.
  14559. *
  14560. * If you don't want to overwrite the specular color but modify the existing
  14561. * value instead, use {@link materialSpecular}.
  14562. *
  14563. * @type {?Node<vec3>}
  14564. * @default null
  14565. */
  14566. this.specularNode = null;
  14567. this.setDefaultValues( _defaultValues$7 );
  14568. this.setValues( parameters );
  14569. }
  14570. /**
  14571. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14572. * to implement the default environment mapping.
  14573. *
  14574. * @param {NodeBuilder} builder - The current node builder.
  14575. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14576. */
  14577. setupEnvironment( builder ) {
  14578. const envNode = super.setupEnvironment( builder );
  14579. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14580. }
  14581. /**
  14582. * Setups the lighting model.
  14583. *
  14584. * @return {PhongLightingModel} The lighting model.
  14585. */
  14586. setupLightingModel( /*builder*/ ) {
  14587. return new PhongLightingModel();
  14588. }
  14589. /**
  14590. * Setups the phong specific node variables.
  14591. *
  14592. * @param {NodeBuilder} builder - The current node builder.
  14593. */
  14594. setupVariants( /*builder*/ ) {
  14595. // SHININESS
  14596. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14597. shininess.assign( shininessNode );
  14598. // SPECULAR COLOR
  14599. const specularNode = this.specularNode || materialSpecular;
  14600. specularColor.assign( specularNode );
  14601. }
  14602. copy( source ) {
  14603. this.shininessNode = source.shininessNode;
  14604. this.specularNode = source.specularNode;
  14605. return super.copy( source );
  14606. }
  14607. }
  14608. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  14609. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  14610. return float( 0 );
  14611. }
  14612. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  14613. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  14614. return geometryRoughness;
  14615. } );
  14616. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  14617. const { roughness } = inputs;
  14618. const geometryRoughness = getGeometryRoughness();
  14619. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  14620. roughnessFactor = roughnessFactor.add( geometryRoughness );
  14621. roughnessFactor = roughnessFactor.min( 1.0 );
  14622. return roughnessFactor;
  14623. } );
  14624. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  14625. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  14626. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  14627. const a2 = alpha.pow2();
  14628. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  14629. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  14630. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  14631. } ).setLayout( {
  14632. name: 'V_GGX_SmithCorrelated',
  14633. type: 'float',
  14634. inputs: [
  14635. { name: 'alpha', type: 'float' },
  14636. { name: 'dotNL', type: 'float' },
  14637. { name: 'dotNV', type: 'float' }
  14638. ]
  14639. } ); // validated
  14640. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  14641. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  14642. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  14643. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  14644. const v = div( 0.5, gv.add( gl ) );
  14645. return v.saturate();
  14646. } ).setLayout( {
  14647. name: 'V_GGX_SmithCorrelated_Anisotropic',
  14648. type: 'float',
  14649. inputs: [
  14650. { name: 'alphaT', type: 'float', qualifier: 'in' },
  14651. { name: 'alphaB', type: 'float', qualifier: 'in' },
  14652. { name: 'dotTV', type: 'float', qualifier: 'in' },
  14653. { name: 'dotBV', type: 'float', qualifier: 'in' },
  14654. { name: 'dotTL', type: 'float', qualifier: 'in' },
  14655. { name: 'dotBL', type: 'float', qualifier: 'in' },
  14656. { name: 'dotNV', type: 'float', qualifier: 'in' },
  14657. { name: 'dotNL', type: 'float', qualifier: 'in' }
  14658. ]
  14659. } );
  14660. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  14661. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  14662. // alpha is "roughness squared" in Disney’s reparameterization
  14663. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  14664. const a2 = alpha.pow2();
  14665. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  14666. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  14667. } ).setLayout( {
  14668. name: 'D_GGX',
  14669. type: 'float',
  14670. inputs: [
  14671. { name: 'alpha', type: 'float' },
  14672. { name: 'dotNH', type: 'float' }
  14673. ]
  14674. } ); // validated
  14675. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  14676. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  14677. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  14678. const a2 = alphaT.mul( alphaB );
  14679. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  14680. const v2 = v.dot( v );
  14681. const w2 = a2.div( v2 );
  14682. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  14683. } ).setLayout( {
  14684. name: 'D_GGX_Anisotropic',
  14685. type: 'float',
  14686. inputs: [
  14687. { name: 'alphaT', type: 'float', qualifier: 'in' },
  14688. { name: 'alphaB', type: 'float', qualifier: 'in' },
  14689. { name: 'dotNH', type: 'float', qualifier: 'in' },
  14690. { name: 'dotTH', type: 'float', qualifier: 'in' },
  14691. { name: 'dotBH', type: 'float', qualifier: 'in' }
  14692. ]
  14693. } );
  14694. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  14695. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  14696. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  14697. const normalView = inputs.normalView || transformedNormalView;
  14698. const alpha = roughness.pow2(); // UE4's roughness
  14699. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14700. const dotNL = normalView.dot( lightDirection ).clamp();
  14701. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14702. const dotNH = normalView.dot( halfDir ).clamp();
  14703. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14704. let F = F_Schlick( { f0, f90, dotVH } );
  14705. let V, D;
  14706. if ( defined( USE_IRIDESCENCE ) ) {
  14707. F = iridescence.mix( F, f );
  14708. }
  14709. if ( defined( USE_ANISOTROPY ) ) {
  14710. const dotTL = anisotropyT.dot( lightDirection );
  14711. const dotTV = anisotropyT.dot( positionViewDirection );
  14712. const dotTH = anisotropyT.dot( halfDir );
  14713. const dotBL = anisotropyB.dot( lightDirection );
  14714. const dotBV = anisotropyB.dot( positionViewDirection );
  14715. const dotBH = anisotropyB.dot( halfDir );
  14716. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  14717. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  14718. } else {
  14719. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  14720. D = D_GGX( { alpha, dotNH } );
  14721. }
  14722. return F.mul( V ).mul( D );
  14723. } ); // validated
  14724. // Analytical approximation of the DFG LUT, one half of the
  14725. // split-sum approximation used in indirect specular lighting.
  14726. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  14727. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  14728. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  14729. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  14730. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  14731. const r = roughness.mul( c0 ).add( c1 );
  14732. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  14733. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  14734. return fab;
  14735. } ).setLayout( {
  14736. name: 'DFGApprox',
  14737. type: 'vec2',
  14738. inputs: [
  14739. { name: 'roughness', type: 'float' },
  14740. { name: 'dotNV', type: 'vec3' }
  14741. ]
  14742. } );
  14743. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  14744. const { dotNV, specularColor, specularF90, roughness } = inputs;
  14745. const fab = DFGApprox( { dotNV, roughness } );
  14746. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  14747. } );
  14748. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  14749. const x = dotVH.oneMinus().saturate();
  14750. const x2 = x.mul( x );
  14751. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  14752. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  14753. } ).setLayout( {
  14754. name: 'Schlick_to_F0',
  14755. type: 'vec3',
  14756. inputs: [
  14757. { name: 'f', type: 'vec3' },
  14758. { name: 'f90', type: 'float' },
  14759. { name: 'dotVH', type: 'float' }
  14760. ]
  14761. } );
  14762. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  14763. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  14764. const alpha = roughness.pow2();
  14765. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  14766. const invAlpha = float( 1.0 ).div( alpha );
  14767. const cos2h = dotNH.pow2();
  14768. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  14769. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  14770. } ).setLayout( {
  14771. name: 'D_Charlie',
  14772. type: 'float',
  14773. inputs: [
  14774. { name: 'roughness', type: 'float' },
  14775. { name: 'dotNH', type: 'float' }
  14776. ]
  14777. } );
  14778. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  14779. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  14780. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  14781. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  14782. } ).setLayout( {
  14783. name: 'V_Neubelt',
  14784. type: 'float',
  14785. inputs: [
  14786. { name: 'dotNV', type: 'float' },
  14787. { name: 'dotNL', type: 'float' }
  14788. ]
  14789. } );
  14790. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14791. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14792. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14793. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  14794. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  14795. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  14796. const V = V_Neubelt( { dotNV, dotNL } );
  14797. return sheen.mul( D ).mul( V );
  14798. } );
  14799. // Rect Area Light
  14800. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  14801. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  14802. // code: https://github.com/selfshadow/ltc_code/
  14803. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  14804. const LUT_SIZE = 64.0;
  14805. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  14806. const LUT_BIAS = 0.5 / LUT_SIZE;
  14807. const dotNV = N.dot( V ).saturate();
  14808. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  14809. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  14810. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  14811. return uv;
  14812. } ).setLayout( {
  14813. name: 'LTC_Uv',
  14814. type: 'vec2',
  14815. inputs: [
  14816. { name: 'N', type: 'vec3' },
  14817. { name: 'V', type: 'vec3' },
  14818. { name: 'roughness', type: 'float' }
  14819. ]
  14820. } );
  14821. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  14822. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  14823. // An approximation of the form factor of a horizon-clipped rectangle.
  14824. const l = f.length();
  14825. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  14826. } ).setLayout( {
  14827. name: 'LTC_ClippedSphereFormFactor',
  14828. type: 'float',
  14829. inputs: [
  14830. { name: 'f', type: 'vec3' }
  14831. ]
  14832. } );
  14833. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  14834. const x = v1.dot( v2 );
  14835. const y = x.abs().toVar();
  14836. // rational polynomial approximation to theta / sin( theta ) / 2PI
  14837. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  14838. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  14839. const v = a.div( b );
  14840. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  14841. return v1.cross( v2 ).mul( theta_sintheta );
  14842. } ).setLayout( {
  14843. name: 'LTC_EdgeVectorFormFactor',
  14844. type: 'vec3',
  14845. inputs: [
  14846. { name: 'v1', type: 'vec3' },
  14847. { name: 'v2', type: 'vec3' }
  14848. ]
  14849. } );
  14850. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  14851. // bail if point is on back side of plane of light
  14852. // assumes ccw winding order of light vertices
  14853. const v1 = p1.sub( p0 ).toVar();
  14854. const v2 = p3.sub( p0 ).toVar();
  14855. const lightNormal = v1.cross( v2 );
  14856. const result = vec3().toVar();
  14857. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  14858. // construct orthonormal basis around N
  14859. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  14860. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  14861. // compute transform
  14862. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  14863. // transform rect
  14864. // & project rect onto sphere
  14865. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  14866. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  14867. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  14868. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  14869. // calculate vector form factor
  14870. const vectorFormFactor = vec3( 0 ).toVar();
  14871. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  14872. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  14873. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  14874. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  14875. // adjust for horizon clipping
  14876. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  14877. } );
  14878. return result;
  14879. } ).setLayout( {
  14880. name: 'LTC_Evaluate',
  14881. type: 'vec3',
  14882. inputs: [
  14883. { name: 'N', type: 'vec3' },
  14884. { name: 'V', type: 'vec3' },
  14885. { name: 'P', type: 'vec3' },
  14886. { name: 'mInv', type: 'mat3' },
  14887. { name: 'p0', type: 'vec3' },
  14888. { name: 'p1', type: 'vec3' },
  14889. { name: 'p2', type: 'vec3' },
  14890. { name: 'p3', type: 'vec3' }
  14891. ]
  14892. } );
  14893. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  14894. // bail if point is on back side of plane of light
  14895. // assumes ccw winding order of light vertices
  14896. const v1 = p1.sub( p0 ).toVar();
  14897. const v2 = p3.sub( p0 ).toVar();
  14898. const lightNormal = v1.cross( v2 );
  14899. const result = vec3().toVar();
  14900. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  14901. // transform rect
  14902. // & project rect onto sphere
  14903. const coords0 = p0.sub( P ).normalize().toVar();
  14904. const coords1 = p1.sub( P ).normalize().toVar();
  14905. const coords2 = p2.sub( P ).normalize().toVar();
  14906. const coords3 = p3.sub( P ).normalize().toVar();
  14907. // calculate vector form factor
  14908. const vectorFormFactor = vec3( 0 ).toVar();
  14909. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  14910. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  14911. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  14912. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  14913. // adjust for horizon clipping
  14914. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  14915. } );
  14916. return result;
  14917. } ).setLayout( {
  14918. name: 'LTC_Evaluate',
  14919. type: 'vec3',
  14920. inputs: [
  14921. { name: 'P', type: 'vec3' },
  14922. { name: 'p0', type: 'vec3' },
  14923. { name: 'p1', type: 'vec3' },
  14924. { name: 'p2', type: 'vec3' },
  14925. { name: 'p3', type: 'vec3' }
  14926. ]
  14927. } );
  14928. // Mipped Bicubic Texture Filtering by N8
  14929. // https://www.shadertoy.com/view/Dl2SDW
  14930. const bC = 1.0 / 6.0;
  14931. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  14932. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  14933. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  14934. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  14935. const g0 = ( a ) => w0( a ).add( w1( a ) );
  14936. const g1 = ( a ) => w2( a ).add( w3( a ) );
  14937. // h0 and h1 are the two offset functions
  14938. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  14939. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  14940. const bicubic = ( textureNode, texelSize, lod ) => {
  14941. const uv = textureNode.uvNode;
  14942. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  14943. const iuv = floor( uvScaled );
  14944. const fuv = fract( uvScaled );
  14945. const g0x = g0( fuv.x );
  14946. const g1x = g1( fuv.x );
  14947. const h0x = h0( fuv.x );
  14948. const h1x = h1( fuv.x );
  14949. const h0y = h0( fuv.y );
  14950. const h1y = h1( fuv.y );
  14951. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  14952. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  14953. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  14954. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  14955. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  14956. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  14957. return a.add( b );
  14958. };
  14959. /**
  14960. * Applies mipped bicubic texture filtering to the given texture node.
  14961. *
  14962. * @tsl
  14963. * @function
  14964. * @param {TextureNode} textureNode - The texture node that should be filtered.
  14965. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  14966. * @return {Node} The filtered texture sample.
  14967. */
  14968. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  14969. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  14970. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  14971. const fLodSizeInv = div( 1.0, fLodSize );
  14972. const cLodSizeInv = div( 1.0, cLodSize );
  14973. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  14974. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  14975. return fract( lodNode ).mix( fSample, cSample );
  14976. } );
  14977. //
  14978. // Transmission
  14979. //
  14980. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  14981. // Direction of refracted light.
  14982. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  14983. // Compute rotation-independent scaling of the model matrix.
  14984. const modelScale = vec3(
  14985. length( modelMatrix[ 0 ].xyz ),
  14986. length( modelMatrix[ 1 ].xyz ),
  14987. length( modelMatrix[ 2 ].xyz )
  14988. );
  14989. // The thickness is specified in local space.
  14990. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  14991. } ).setLayout( {
  14992. name: 'getVolumeTransmissionRay',
  14993. type: 'vec3',
  14994. inputs: [
  14995. { name: 'n', type: 'vec3' },
  14996. { name: 'v', type: 'vec3' },
  14997. { name: 'thickness', type: 'float' },
  14998. { name: 'ior', type: 'float' },
  14999. { name: 'modelMatrix', type: 'mat4' }
  15000. ]
  15001. } );
  15002. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  15003. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  15004. // an IOR of 1.5 results in the default amount of microfacet refraction.
  15005. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  15006. } ).setLayout( {
  15007. name: 'applyIorToRoughness',
  15008. type: 'float',
  15009. inputs: [
  15010. { name: 'roughness', type: 'float' },
  15011. { name: 'ior', type: 'float' }
  15012. ]
  15013. } );
  15014. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  15015. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  15016. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  15017. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  15018. const transmissionSample = vTexture.sample( fragCoord );
  15019. //const transmissionSample = viewportMipTexture( fragCoord );
  15020. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  15021. return textureBicubic( transmissionSample, lod );
  15022. } );
  15023. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  15024. If( attenuationDistance.notEqual( 0 ), () => {
  15025. // Compute light attenuation using Beer's law.
  15026. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  15027. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  15028. return transmittance;
  15029. } );
  15030. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  15031. return vec3( 1.0 );
  15032. } ).setLayout( {
  15033. name: 'volumeAttenuation',
  15034. type: 'vec3',
  15035. inputs: [
  15036. { name: 'transmissionDistance', type: 'float' },
  15037. { name: 'attenuationColor', type: 'vec3' },
  15038. { name: 'attenuationDistance', type: 'float' }
  15039. ]
  15040. } );
  15041. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  15042. let transmittedLight, transmittance;
  15043. if ( dispersion ) {
  15044. transmittedLight = vec4().toVar();
  15045. transmittance = vec3().toVar();
  15046. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  15047. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  15048. Loop( { start: 0, end: 3 }, ( { i } ) => {
  15049. const ior = iors.element( i );
  15050. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15051. const refractedRayExit = position.add( transmissionRay );
  15052. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15053. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15054. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15055. refractionCoords.addAssign( 1.0 );
  15056. refractionCoords.divAssign( 2.0 );
  15057. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15058. // Sample framebuffer to get pixel the refracted ray hits.
  15059. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  15060. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  15061. transmittedLight.a.addAssign( transmissionSample.a );
  15062. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  15063. } );
  15064. transmittedLight.a.divAssign( 3.0 );
  15065. } else {
  15066. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15067. const refractedRayExit = position.add( transmissionRay );
  15068. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15069. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15070. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15071. refractionCoords.addAssign( 1.0 );
  15072. refractionCoords.divAssign( 2.0 );
  15073. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15074. // Sample framebuffer to get pixel the refracted ray hits.
  15075. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  15076. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  15077. }
  15078. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  15079. const dotNV = n.dot( v ).clamp();
  15080. // Get the specular component.
  15081. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  15082. dotNV,
  15083. specularColor,
  15084. specularF90,
  15085. roughness
  15086. } ) );
  15087. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  15088. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  15089. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  15090. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  15091. } );
  15092. //
  15093. // Iridescence
  15094. //
  15095. // XYZ to linear-sRGB color space
  15096. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  15097. 3.2404542, -0.969266, 0.0556434,
  15098. -1.5371385, 1.8760108, -0.2040259,
  15099. -0.4985314, 0.0415560, 1.0572252
  15100. );
  15101. // Assume air interface for top
  15102. // Note: We don't handle the case fresnel0 == 1
  15103. const Fresnel0ToIor = ( fresnel0 ) => {
  15104. const sqrtF0 = fresnel0.sqrt();
  15105. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  15106. };
  15107. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  15108. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  15109. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  15110. };
  15111. // Fresnel equations for dielectric/dielectric interfaces.
  15112. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  15113. // Evaluation XYZ sensitivity curves in Fourier space
  15114. const evalSensitivity = ( OPD, shift ) => {
  15115. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  15116. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  15117. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  15118. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  15119. 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() );
  15120. 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() );
  15121. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  15122. const rgb = XYZ_TO_REC709.mul( xyz );
  15123. return rgb;
  15124. };
  15125. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  15126. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  15127. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  15128. // Evaluate the cosTheta on the base layer (Snell law)
  15129. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  15130. // Handle TIR:
  15131. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  15132. If( cosTheta2Sq.lessThan( 0 ), () => {
  15133. return vec3( 1.0 );
  15134. } );
  15135. const cosTheta2 = cosTheta2Sq.sqrt();
  15136. // First interface
  15137. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  15138. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  15139. //const R21 = R12;
  15140. const T121 = R12.oneMinus();
  15141. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  15142. const phi21 = float( Math.PI ).sub( phi12 );
  15143. // Second interface
  15144. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  15145. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  15146. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  15147. const phi23 = vec3(
  15148. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15149. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15150. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  15151. );
  15152. // Phase shift
  15153. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  15154. const phi = vec3( phi21 ).add( phi23 );
  15155. // Compound terms
  15156. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  15157. const r123 = R123.sqrt();
  15158. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  15159. // Reflectance term for m = 0 (DC term amplitude)
  15160. const C0 = R12.add( Rs );
  15161. const I = C0.toVar();
  15162. // Reflectance term for m > 0 (pairs of diracs)
  15163. const Cm = Rs.sub( T121 ).toVar();
  15164. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  15165. Cm.mulAssign( r123 );
  15166. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  15167. I.addAssign( Cm.mul( Sm ) );
  15168. } );
  15169. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  15170. return I.max( vec3( 0.0 ) );
  15171. } ).setLayout( {
  15172. name: 'evalIridescence',
  15173. type: 'vec3',
  15174. inputs: [
  15175. { name: 'outsideIOR', type: 'float' },
  15176. { name: 'eta2', type: 'float' },
  15177. { name: 'cosTheta1', type: 'float' },
  15178. { name: 'thinFilmThickness', type: 'float' },
  15179. { name: 'baseF0', type: 'vec3' }
  15180. ]
  15181. } );
  15182. //
  15183. // Sheen
  15184. //
  15185. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  15186. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  15187. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  15188. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  15189. const dotNV = normal.dot( viewDir ).saturate();
  15190. const r2 = roughness.pow2();
  15191. const a = select(
  15192. roughness.lessThan( 0.25 ),
  15193. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  15194. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  15195. );
  15196. const b = select(
  15197. roughness.lessThan( 0.25 ),
  15198. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  15199. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  15200. );
  15201. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  15202. return DG.mul( 1.0 / Math.PI ).saturate();
  15203. } );
  15204. const clearcoatF0 = vec3( 0.04 );
  15205. const clearcoatF90 = float( 1 );
  15206. /**
  15207. * Represents the lighting model for a PBR material.
  15208. *
  15209. * @augments LightingModel
  15210. */
  15211. class PhysicalLightingModel extends LightingModel {
  15212. /**
  15213. * Constructs a new physical lighting model.
  15214. *
  15215. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15216. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  15217. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  15218. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15219. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  15220. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  15221. */
  15222. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  15223. super();
  15224. /**
  15225. * Whether clearcoat is supported or not.
  15226. *
  15227. * @type {boolean}
  15228. * @default false
  15229. */
  15230. this.clearcoat = clearcoat;
  15231. /**
  15232. * Whether sheen is supported or not.
  15233. *
  15234. * @type {boolean}
  15235. * @default false
  15236. */
  15237. this.sheen = sheen;
  15238. /**
  15239. * Whether iridescence is supported or not.
  15240. *
  15241. * @type {boolean}
  15242. * @default false
  15243. */
  15244. this.iridescence = iridescence;
  15245. /**
  15246. * Whether anisotropy is supported or not.
  15247. *
  15248. * @type {boolean}
  15249. * @default false
  15250. */
  15251. this.anisotropy = anisotropy;
  15252. /**
  15253. * Whether transmission is supported or not.
  15254. *
  15255. * @type {boolean}
  15256. * @default false
  15257. */
  15258. this.transmission = transmission;
  15259. /**
  15260. * Whether dispersion is supported or not.
  15261. *
  15262. * @type {boolean}
  15263. * @default false
  15264. */
  15265. this.dispersion = dispersion;
  15266. /**
  15267. * The clear coat radiance.
  15268. *
  15269. * @type {?Node}
  15270. * @default null
  15271. */
  15272. this.clearcoatRadiance = null;
  15273. /**
  15274. * The clear coat specular direct.
  15275. *
  15276. * @type {?Node}
  15277. * @default null
  15278. */
  15279. this.clearcoatSpecularDirect = null;
  15280. /**
  15281. * The clear coat specular indirect.
  15282. *
  15283. * @type {?Node}
  15284. * @default null
  15285. */
  15286. this.clearcoatSpecularIndirect = null;
  15287. /**
  15288. * The sheen specular direct.
  15289. *
  15290. * @type {?Node}
  15291. * @default null
  15292. */
  15293. this.sheenSpecularDirect = null;
  15294. /**
  15295. * The sheen specular indirect.
  15296. *
  15297. * @type {?Node}
  15298. * @default null
  15299. */
  15300. this.sheenSpecularIndirect = null;
  15301. /**
  15302. * The iridescence Fresnel.
  15303. *
  15304. * @type {?Node}
  15305. * @default null
  15306. */
  15307. this.iridescenceFresnel = null;
  15308. /**
  15309. * The iridescence F0.
  15310. *
  15311. * @type {?Node}
  15312. * @default null
  15313. */
  15314. this.iridescenceF0 = null;
  15315. }
  15316. /**
  15317. * Depending on what features are requested, the method prepares certain node variables
  15318. * which are later used for lighting computations.
  15319. *
  15320. * @param {NodeBuilder} builder - The current node builder.
  15321. */
  15322. start( builder ) {
  15323. if ( this.clearcoat === true ) {
  15324. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  15325. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  15326. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  15327. }
  15328. if ( this.sheen === true ) {
  15329. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  15330. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  15331. }
  15332. if ( this.iridescence === true ) {
  15333. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  15334. this.iridescenceFresnel = evalIridescence( {
  15335. outsideIOR: float( 1.0 ),
  15336. eta2: iridescenceIOR,
  15337. cosTheta1: dotNVi,
  15338. thinFilmThickness: iridescenceThickness,
  15339. baseF0: specularColor
  15340. } );
  15341. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  15342. }
  15343. if ( this.transmission === true ) {
  15344. const position = positionWorld;
  15345. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  15346. const n = transformedNormalWorld;
  15347. const context = builder.context;
  15348. context.backdrop = getIBLVolumeRefraction(
  15349. n,
  15350. v,
  15351. roughness,
  15352. diffuseColor,
  15353. specularColor,
  15354. specularF90, // specularF90
  15355. position, // positionWorld
  15356. modelWorldMatrix, // modelMatrix
  15357. cameraViewMatrix, // viewMatrix
  15358. cameraProjectionMatrix, // projMatrix
  15359. ior,
  15360. thickness,
  15361. attenuationColor,
  15362. attenuationDistance,
  15363. this.dispersion ? dispersion : null
  15364. );
  15365. context.backdropAlpha = transmission;
  15366. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  15367. }
  15368. super.start( builder );
  15369. }
  15370. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  15371. // Approximates multi-scattering in order to preserve energy.
  15372. // http://www.jcgt.org/published/0008/01/03/
  15373. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  15374. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15375. const fab = DFGApprox( { roughness, dotNV } );
  15376. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  15377. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15378. const Ess = fab.x.add( fab.y );
  15379. const Ems = Ess.oneMinus();
  15380. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  15381. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  15382. singleScatter.addAssign( FssEss );
  15383. multiScatter.addAssign( Fms.mul( Ems ) );
  15384. }
  15385. /**
  15386. * Implements the direct light.
  15387. *
  15388. * @param {Object} lightData - The light data.
  15389. * @param {NodeBuilder} builder - The current node builder.
  15390. */
  15391. direct( { lightDirection, lightColor, reflectedLight } ) {
  15392. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  15393. const irradiance = dotNL.mul( lightColor );
  15394. if ( this.sheen === true ) {
  15395. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  15396. }
  15397. if ( this.clearcoat === true ) {
  15398. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  15399. const ccIrradiance = dotNLcc.mul( lightColor );
  15400. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  15401. }
  15402. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15403. 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 } ) ) );
  15404. }
  15405. /**
  15406. * This method is intended for implementing the direct light term for
  15407. * rect area light nodes.
  15408. *
  15409. * @param {Object} input - The input data.
  15410. * @param {NodeBuilder} builder - The current node builder.
  15411. */
  15412. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  15413. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  15414. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  15415. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  15416. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  15417. const N = transformedNormalView;
  15418. const V = positionViewDirection;
  15419. const P = positionView.toVar();
  15420. const uv = LTC_Uv( { N, V, roughness } );
  15421. const t1 = ltc_1.sample( uv ).toVar();
  15422. const t2 = ltc_2.sample( uv ).toVar();
  15423. const mInv = mat3(
  15424. vec3( t1.x, 0, t1.y ),
  15425. vec3( 0, 1, 0 ),
  15426. vec3( t1.z, 0, t1.w )
  15427. ).toVar();
  15428. // LTC Fresnel Approximation by Stephen Hill
  15429. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  15430. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  15431. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  15432. 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 } ) ) );
  15433. }
  15434. /**
  15435. * Implements the indirect lighting.
  15436. *
  15437. * @param {NodeBuilder} builder - The current node builder.
  15438. */
  15439. indirect( builder ) {
  15440. this.indirectDiffuse( builder );
  15441. this.indirectSpecular( builder );
  15442. this.ambientOcclusion( builder );
  15443. }
  15444. /**
  15445. * Implements the indirect diffuse term.
  15446. *
  15447. * @param {NodeBuilder} builder - The current node builder.
  15448. */
  15449. indirectDiffuse( builder ) {
  15450. const { irradiance, reflectedLight } = builder.context;
  15451. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15452. }
  15453. /**
  15454. * Implements the indirect specular term.
  15455. *
  15456. * @param {NodeBuilder} builder - The current node builder.
  15457. */
  15458. indirectSpecular( builder ) {
  15459. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  15460. if ( this.sheen === true ) {
  15461. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  15462. sheen,
  15463. IBLSheenBRDF( {
  15464. normal: transformedNormalView,
  15465. viewDir: positionViewDirection,
  15466. roughness: sheenRoughness
  15467. } )
  15468. ) );
  15469. }
  15470. if ( this.clearcoat === true ) {
  15471. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15472. const clearcoatEnv = EnvironmentBRDF( {
  15473. dotNV: dotNVcc,
  15474. specularColor: clearcoatF0,
  15475. specularF90: clearcoatF90,
  15476. roughness: clearcoatRoughness
  15477. } );
  15478. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  15479. }
  15480. // Both indirect specular and indirect diffuse light accumulate here
  15481. const singleScattering = vec3().toVar( 'singleScattering' );
  15482. const multiScattering = vec3().toVar( 'multiScattering' );
  15483. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  15484. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  15485. const totalScattering = singleScattering.add( multiScattering );
  15486. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  15487. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  15488. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  15489. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  15490. }
  15491. /**
  15492. * Implements the ambient occlusion term.
  15493. *
  15494. * @param {NodeBuilder} builder - The current node builder.
  15495. */
  15496. ambientOcclusion( builder ) {
  15497. const { ambientOcclusion, reflectedLight } = builder.context;
  15498. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15499. const aoNV = dotNV.add( ambientOcclusion );
  15500. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  15501. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  15502. if ( this.clearcoat === true ) {
  15503. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  15504. }
  15505. if ( this.sheen === true ) {
  15506. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  15507. }
  15508. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15509. reflectedLight.indirectSpecular.mulAssign( aoNode );
  15510. }
  15511. /**
  15512. * Used for final lighting accumulations depending on the requested features.
  15513. *
  15514. * @param {NodeBuilder} builder - The current node builder.
  15515. */
  15516. finish( { context } ) {
  15517. const { outgoingLight } = context;
  15518. if ( this.clearcoat === true ) {
  15519. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15520. const Fcc = F_Schlick( {
  15521. dotVH: dotNVcc,
  15522. f0: clearcoatF0,
  15523. f90: clearcoatF90
  15524. } );
  15525. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  15526. outgoingLight.assign( clearcoatLight );
  15527. }
  15528. if ( this.sheen === true ) {
  15529. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  15530. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  15531. outgoingLight.assign( sheenLight );
  15532. }
  15533. }
  15534. }
  15535. // These defines must match with PMREMGenerator
  15536. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  15537. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  15538. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  15539. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  15540. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  15541. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  15542. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  15543. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  15544. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  15545. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  15546. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  15547. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  15548. // These shader functions convert between the UV coordinates of a single face of
  15549. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  15550. // sampling a textureCube (not generally normalized ).
  15551. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  15552. const absDirection = vec3( abs( direction ) ).toVar();
  15553. const face = float( -1 ).toVar();
  15554. If( absDirection.x.greaterThan( absDirection.z ), () => {
  15555. If( absDirection.x.greaterThan( absDirection.y ), () => {
  15556. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  15557. } ).Else( () => {
  15558. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15559. } );
  15560. } ).Else( () => {
  15561. If( absDirection.z.greaterThan( absDirection.y ), () => {
  15562. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  15563. } ).Else( () => {
  15564. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15565. } );
  15566. } );
  15567. return face;
  15568. } ).setLayout( {
  15569. name: 'getFace',
  15570. type: 'float',
  15571. inputs: [
  15572. { name: 'direction', type: 'vec3' }
  15573. ]
  15574. } );
  15575. // RH coordinate system; PMREM face-indexing convention
  15576. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  15577. const uv = vec2().toVar();
  15578. If( face.equal( 0.0 ), () => {
  15579. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  15580. } ).ElseIf( face.equal( 1.0 ), () => {
  15581. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  15582. } ).ElseIf( face.equal( 2.0 ), () => {
  15583. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  15584. } ).ElseIf( face.equal( 3.0 ), () => {
  15585. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  15586. } ).ElseIf( face.equal( 4.0 ), () => {
  15587. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  15588. } ).Else( () => {
  15589. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  15590. } );
  15591. return mul( 0.5, uv.add( 1.0 ) );
  15592. } ).setLayout( {
  15593. name: 'getUV',
  15594. type: 'vec2',
  15595. inputs: [
  15596. { name: 'direction', type: 'vec3' },
  15597. { name: 'face', type: 'float' }
  15598. ]
  15599. } );
  15600. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  15601. const mip = float( 0.0 ).toVar();
  15602. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  15603. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  15604. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  15605. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  15606. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  15607. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  15608. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  15609. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  15610. } ).Else( () => {
  15611. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  15612. } );
  15613. return mip;
  15614. } ).setLayout( {
  15615. name: 'roughnessToMip',
  15616. type: 'float',
  15617. inputs: [
  15618. { name: 'roughness', type: 'float' }
  15619. ]
  15620. } );
  15621. // RH coordinate system; PMREM face-indexing convention
  15622. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  15623. const uv = uv_immutable.toVar();
  15624. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  15625. const direction = vec3( uv, 1.0 ).toVar();
  15626. If( face.equal( 0.0 ), () => {
  15627. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  15628. } ).ElseIf( face.equal( 1.0 ), () => {
  15629. direction.assign( direction.xzy );
  15630. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  15631. } ).ElseIf( face.equal( 2.0 ), () => {
  15632. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  15633. } ).ElseIf( face.equal( 3.0 ), () => {
  15634. direction.assign( direction.zyx );
  15635. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  15636. } ).ElseIf( face.equal( 4.0 ), () => {
  15637. direction.assign( direction.xzy );
  15638. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  15639. } ).ElseIf( face.equal( 5.0 ), () => {
  15640. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  15641. } );
  15642. return direction;
  15643. } ).setLayout( {
  15644. name: 'getDirection',
  15645. type: 'vec3',
  15646. inputs: [
  15647. { name: 'uv', type: 'vec2' },
  15648. { name: 'face', type: 'float' }
  15649. ]
  15650. } );
  15651. //
  15652. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  15653. const roughness = float( roughness_immutable );
  15654. const sampleDir = vec3( sampleDir_immutable );
  15655. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  15656. const mipF = fract( mip );
  15657. const mipInt = floor( mip );
  15658. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  15659. If( mipF.notEqual( 0.0 ), () => {
  15660. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  15661. color0.assign( mix( color0, color1, mipF ) );
  15662. } );
  15663. return color0;
  15664. } );
  15665. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  15666. const mipInt = float( mipInt_immutable ).toVar();
  15667. const direction = vec3( direction_immutable );
  15668. const face = float( getFace( direction ) ).toVar();
  15669. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  15670. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  15671. const faceSize = float( exp2( mipInt ) ).toVar();
  15672. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  15673. If( face.greaterThan( 2.0 ), () => {
  15674. uv.y.addAssign( faceSize );
  15675. face.subAssign( 3.0 );
  15676. } );
  15677. uv.x.addAssign( face.mul( faceSize ) );
  15678. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  15679. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  15680. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  15681. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  15682. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  15683. } );
  15684. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  15685. const cosTheta = cos( theta );
  15686. // Rodrigues' axis-angle rotation
  15687. const sampleDirection = outputDirection.mul( cosTheta )
  15688. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  15689. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  15690. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  15691. } );
  15692. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  15693. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  15694. If( axis.equal( vec3( 0.0 ) ), () => {
  15695. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  15696. } );
  15697. axis.assign( normalize( axis ) );
  15698. const gl_FragColor = vec3().toVar();
  15699. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15700. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  15701. If( i.greaterThanEqual( samples ), () => {
  15702. Break();
  15703. } );
  15704. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  15705. 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 } ) ) );
  15706. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15707. } );
  15708. return vec4( gl_FragColor, 1 );
  15709. } );
  15710. const LOD_MIN = 4;
  15711. // The standard deviations (radians) associated with the extra mips. These are
  15712. // chosen to approximate a Trowbridge-Reitz distribution function times the
  15713. // geometric shadowing function. These sigma values squared must match the
  15714. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  15715. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  15716. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  15717. // samples and exit early, but not recompile the shader.
  15718. const MAX_SAMPLES = 20;
  15719. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  15720. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  15721. const _clearColor$2 = /*@__PURE__*/ new Color();
  15722. let _oldTarget = null;
  15723. let _oldActiveCubeFace = 0;
  15724. let _oldActiveMipmapLevel = 0;
  15725. // Golden Ratio
  15726. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  15727. const INV_PHI = 1 / PHI;
  15728. // Vertices of a dodecahedron (except the opposites, which represent the
  15729. // same axis), used as axis directions evenly spread on a sphere.
  15730. const _axisDirections = [
  15731. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  15732. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  15733. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  15734. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  15735. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  15736. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  15737. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  15738. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  15739. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  15740. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  15741. ];
  15742. const _origin = /*@__PURE__*/ new Vector3();
  15743. // maps blur materials to their uniforms dictionary
  15744. const _uniformsMap = new WeakMap();
  15745. // WebGPU Face indices
  15746. const _faceLib = [
  15747. 3, 1, 5,
  15748. 0, 4, 2
  15749. ];
  15750. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  15751. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  15752. /**
  15753. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  15754. * (PMREM) from a cubeMap environment texture. This allows different levels of
  15755. * blur to be quickly accessed based on material roughness. It is packed into a
  15756. * special CubeUV format that allows us to perform custom interpolation so that
  15757. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  15758. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  15759. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  15760. * higher roughness levels. In this way we maintain resolution to smoothly
  15761. * interpolate diffuse lighting while limiting sampling computation.
  15762. *
  15763. * Paper: Fast, Accurate Image-Based Lighting:
  15764. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  15765. */
  15766. class PMREMGenerator {
  15767. /**
  15768. * Constructs a new PMREM generator.
  15769. *
  15770. * @param {Renderer} renderer - The renderer.
  15771. */
  15772. constructor( renderer ) {
  15773. this._renderer = renderer;
  15774. this._pingPongRenderTarget = null;
  15775. this._lodMax = 0;
  15776. this._cubeSize = 0;
  15777. this._lodPlanes = [];
  15778. this._sizeLods = [];
  15779. this._sigmas = [];
  15780. this._lodMeshes = [];
  15781. this._blurMaterial = null;
  15782. this._cubemapMaterial = null;
  15783. this._equirectMaterial = null;
  15784. this._backgroundBox = null;
  15785. }
  15786. get _hasInitialized() {
  15787. return this._renderer.hasInitialized();
  15788. }
  15789. /**
  15790. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15791. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15792. * in radians to be applied to the scene before PMREM generation. Optional near
  15793. * and far planes ensure the scene is rendered in its entirety.
  15794. *
  15795. * @param {Scene} scene - The scene to be captured.
  15796. * @param {number} [sigma=0] - The blur radius in radians.
  15797. * @param {number} [near=0.1] - The near plane distance.
  15798. * @param {number} [far=100] - The far plane distance.
  15799. * @param {Object} [options={}] - The configuration options.
  15800. * @param {number} [options.size=256] - The texture size of the PMREM.
  15801. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  15802. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  15803. * @return {RenderTarget} The resulting PMREM.
  15804. * @see {@link PMREMGenerator#fromSceneAsync}
  15805. */
  15806. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  15807. const {
  15808. size = 256,
  15809. position = _origin,
  15810. renderTarget = null,
  15811. } = options;
  15812. this._setSize( size );
  15813. if ( this._hasInitialized === false ) {
  15814. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  15815. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  15816. options.renderTarget = cubeUVRenderTarget;
  15817. this.fromSceneAsync( scene, sigma, near, far, options );
  15818. return cubeUVRenderTarget;
  15819. }
  15820. _oldTarget = this._renderer.getRenderTarget();
  15821. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  15822. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  15823. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  15824. cubeUVRenderTarget.depthBuffer = true;
  15825. this._init( cubeUVRenderTarget );
  15826. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  15827. if ( sigma > 0 ) {
  15828. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  15829. }
  15830. this._applyPMREM( cubeUVRenderTarget );
  15831. this._cleanup( cubeUVRenderTarget );
  15832. return cubeUVRenderTarget;
  15833. }
  15834. /**
  15835. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15836. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15837. * in radians to be applied to the scene before PMREM generation. Optional near
  15838. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  15839. * is placed at the origin).
  15840. *
  15841. * @param {Scene} scene - The scene to be captured.
  15842. * @param {number} [sigma=0] - The blur radius in radians.
  15843. * @param {number} [near=0.1] - The near plane distance.
  15844. * @param {number} [far=100] - The far plane distance.
  15845. * @param {Object} [options={}] - The configuration options.
  15846. * @param {number} [options.size=256] - The texture size of the PMREM.
  15847. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  15848. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  15849. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  15850. * @see {@link PMREMGenerator#fromScene}
  15851. */
  15852. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  15853. if ( this._hasInitialized === false ) await this._renderer.init();
  15854. return this.fromScene( scene, sigma, near, far, options );
  15855. }
  15856. /**
  15857. * Generates a PMREM from an equirectangular texture, which can be either LDR
  15858. * or HDR. The ideal input image size is 1k (1024 x 512),
  15859. * as this matches best with the 256 x 256 cubemap output.
  15860. *
  15861. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  15862. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15863. * @return {RenderTarget} The resulting PMREM.
  15864. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  15865. */
  15866. fromEquirectangular( equirectangular, renderTarget = null ) {
  15867. if ( this._hasInitialized === false ) {
  15868. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  15869. this._setSizeFromTexture( equirectangular );
  15870. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  15871. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  15872. return cubeUVRenderTarget;
  15873. }
  15874. return this._fromTexture( equirectangular, renderTarget );
  15875. }
  15876. /**
  15877. * Generates a PMREM from an equirectangular texture, which can be either LDR
  15878. * or HDR. The ideal input image size is 1k (1024 x 512),
  15879. * as this matches best with the 256 x 256 cubemap output.
  15880. *
  15881. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  15882. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15883. * @return {Promise<RenderTarget>} The resulting PMREM.
  15884. * @see {@link PMREMGenerator#fromEquirectangular}
  15885. */
  15886. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  15887. if ( this._hasInitialized === false ) await this._renderer.init();
  15888. return this._fromTexture( equirectangular, renderTarget );
  15889. }
  15890. /**
  15891. * Generates a PMREM from an cubemap texture, which can be either LDR
  15892. * or HDR. The ideal input cube size is 256 x 256,
  15893. * as this matches best with the 256 x 256 cubemap output.
  15894. *
  15895. * @param {Texture} cubemap - The cubemap texture to be converted.
  15896. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15897. * @return {RenderTarget} The resulting PMREM.
  15898. * @see {@link PMREMGenerator#fromCubemapAsync}
  15899. */
  15900. fromCubemap( cubemap, renderTarget = null ) {
  15901. if ( this._hasInitialized === false ) {
  15902. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  15903. this._setSizeFromTexture( cubemap );
  15904. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  15905. this.fromCubemapAsync( cubemap, renderTarget );
  15906. return cubeUVRenderTarget;
  15907. }
  15908. return this._fromTexture( cubemap, renderTarget );
  15909. }
  15910. /**
  15911. * Generates a PMREM from an cubemap texture, which can be either LDR
  15912. * or HDR. The ideal input cube size is 256 x 256,
  15913. * with the 256 x 256 cubemap output.
  15914. *
  15915. * @param {Texture} cubemap - The cubemap texture to be converted.
  15916. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15917. * @return {Promise<RenderTarget>} The resulting PMREM.
  15918. * @see {@link PMREMGenerator#fromCubemap}
  15919. */
  15920. async fromCubemapAsync( cubemap, renderTarget = null ) {
  15921. if ( this._hasInitialized === false ) await this._renderer.init();
  15922. return this._fromTexture( cubemap, renderTarget );
  15923. }
  15924. /**
  15925. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  15926. * your texture's network fetch for increased concurrency.
  15927. *
  15928. * @returns {Promise}
  15929. */
  15930. async compileCubemapShader() {
  15931. if ( this._cubemapMaterial === null ) {
  15932. this._cubemapMaterial = _getCubemapMaterial();
  15933. await this._compileMaterial( this._cubemapMaterial );
  15934. }
  15935. }
  15936. /**
  15937. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  15938. * your texture's network fetch for increased concurrency.
  15939. *
  15940. * @returns {Promise}
  15941. */
  15942. async compileEquirectangularShader() {
  15943. if ( this._equirectMaterial === null ) {
  15944. this._equirectMaterial = _getEquirectMaterial();
  15945. await this._compileMaterial( this._equirectMaterial );
  15946. }
  15947. }
  15948. /**
  15949. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  15950. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  15951. * one of them will cause any others to also become unusable.
  15952. */
  15953. dispose() {
  15954. this._dispose();
  15955. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  15956. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  15957. if ( this._backgroundBox !== null ) {
  15958. this._backgroundBox.geometry.dispose();
  15959. this._backgroundBox.material.dispose();
  15960. }
  15961. }
  15962. // private interface
  15963. _setSizeFromTexture( texture ) {
  15964. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  15965. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  15966. } else { // Equirectangular
  15967. this._setSize( texture.image.width / 4 );
  15968. }
  15969. }
  15970. _setSize( cubeSize ) {
  15971. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  15972. this._cubeSize = Math.pow( 2, this._lodMax );
  15973. }
  15974. _dispose() {
  15975. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  15976. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  15977. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  15978. this._lodPlanes[ i ].dispose();
  15979. }
  15980. }
  15981. _cleanup( outputTarget ) {
  15982. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  15983. outputTarget.scissorTest = false;
  15984. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  15985. }
  15986. _fromTexture( texture, renderTarget ) {
  15987. this._setSizeFromTexture( texture );
  15988. _oldTarget = this._renderer.getRenderTarget();
  15989. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  15990. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  15991. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  15992. this._init( cubeUVRenderTarget );
  15993. this._textureToCubeUV( texture, cubeUVRenderTarget );
  15994. this._applyPMREM( cubeUVRenderTarget );
  15995. this._cleanup( cubeUVRenderTarget );
  15996. return cubeUVRenderTarget;
  15997. }
  15998. _allocateTarget() {
  15999. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16000. const height = 4 * this._cubeSize;
  16001. const cubeUVRenderTarget = _createRenderTarget( width, height );
  16002. return cubeUVRenderTarget;
  16003. }
  16004. _init( renderTarget ) {
  16005. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  16006. if ( this._pingPongRenderTarget !== null ) {
  16007. this._dispose();
  16008. }
  16009. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  16010. const { _lodMax } = this;
  16011. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16012. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  16013. }
  16014. }
  16015. async _compileMaterial( material ) {
  16016. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16017. await this._renderer.compile( tmpMesh, _flatCamera );
  16018. }
  16019. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  16020. const cubeCamera = _cubeCamera;
  16021. cubeCamera.near = near;
  16022. cubeCamera.far = far;
  16023. // px, py, pz, nx, ny, nz
  16024. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  16025. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  16026. const renderer = this._renderer;
  16027. const originalAutoClear = renderer.autoClear;
  16028. renderer.getClearColor( _clearColor$2 );
  16029. renderer.autoClear = false;
  16030. let backgroundBox = this._backgroundBox;
  16031. if ( backgroundBox === null ) {
  16032. const backgroundMaterial = new MeshBasicMaterial( {
  16033. name: 'PMREM.Background',
  16034. side: BackSide,
  16035. depthWrite: false,
  16036. depthTest: false
  16037. } );
  16038. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16039. }
  16040. let useSolidColor = false;
  16041. const background = scene.background;
  16042. if ( background ) {
  16043. if ( background.isColor ) {
  16044. backgroundBox.material.color.copy( background );
  16045. scene.background = null;
  16046. useSolidColor = true;
  16047. }
  16048. } else {
  16049. backgroundBox.material.color.copy( _clearColor$2 );
  16050. useSolidColor = true;
  16051. }
  16052. renderer.setRenderTarget( cubeUVRenderTarget );
  16053. renderer.clear();
  16054. if ( useSolidColor ) {
  16055. renderer.render( backgroundBox, cubeCamera );
  16056. }
  16057. for ( let i = 0; i < 6; i ++ ) {
  16058. const col = i % 3;
  16059. if ( col === 0 ) {
  16060. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16061. cubeCamera.position.set( position.x, position.y, position.z );
  16062. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  16063. } else if ( col === 1 ) {
  16064. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16065. cubeCamera.position.set( position.x, position.y, position.z );
  16066. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  16067. } else {
  16068. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16069. cubeCamera.position.set( position.x, position.y, position.z );
  16070. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  16071. }
  16072. const size = this._cubeSize;
  16073. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16074. renderer.render( scene, cubeCamera );
  16075. }
  16076. renderer.autoClear = originalAutoClear;
  16077. scene.background = background;
  16078. }
  16079. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16080. const renderer = this._renderer;
  16081. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16082. if ( isCubeTexture ) {
  16083. if ( this._cubemapMaterial === null ) {
  16084. this._cubemapMaterial = _getCubemapMaterial( texture );
  16085. }
  16086. } else {
  16087. if ( this._equirectMaterial === null ) {
  16088. this._equirectMaterial = _getEquirectMaterial( texture );
  16089. }
  16090. }
  16091. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16092. material.fragmentNode.value = texture;
  16093. const mesh = this._lodMeshes[ 0 ];
  16094. mesh.material = material;
  16095. const size = this._cubeSize;
  16096. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16097. renderer.setRenderTarget( cubeUVRenderTarget );
  16098. renderer.render( mesh, _flatCamera );
  16099. }
  16100. _applyPMREM( cubeUVRenderTarget ) {
  16101. const renderer = this._renderer;
  16102. const autoClear = renderer.autoClear;
  16103. renderer.autoClear = false;
  16104. const n = this._lodPlanes.length;
  16105. for ( let i = 1; i < n; i ++ ) {
  16106. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16107. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16108. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16109. }
  16110. renderer.autoClear = autoClear;
  16111. }
  16112. /**
  16113. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16114. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16115. * the blur latitudinally (around the poles), and then longitudinally (towards
  16116. * the poles) to approximate the orthogonally-separable blur. It is least
  16117. * accurate at the poles, but still does a decent job.
  16118. *
  16119. * @private
  16120. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  16121. * @param {number} lodIn - The input level-of-detail.
  16122. * @param {number} lodOut - The output level-of-detail.
  16123. * @param {number} sigma - The blur radius in radians.
  16124. * @param {Vector3} [poleAxis] - The pole axis.
  16125. */
  16126. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16127. const pingPongRenderTarget = this._pingPongRenderTarget;
  16128. this._halfBlur(
  16129. cubeUVRenderTarget,
  16130. pingPongRenderTarget,
  16131. lodIn,
  16132. lodOut,
  16133. sigma,
  16134. 'latitudinal',
  16135. poleAxis );
  16136. this._halfBlur(
  16137. pingPongRenderTarget,
  16138. cubeUVRenderTarget,
  16139. lodOut,
  16140. lodOut,
  16141. sigma,
  16142. 'longitudinal',
  16143. poleAxis );
  16144. }
  16145. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16146. const renderer = this._renderer;
  16147. const blurMaterial = this._blurMaterial;
  16148. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16149. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16150. }
  16151. // Number of standard deviations at which to cut off the discrete approximation.
  16152. const STANDARD_DEVIATIONS = 3;
  16153. const blurMesh = this._lodMeshes[ lodOut ];
  16154. blurMesh.material = blurMaterial;
  16155. const blurUniforms = _uniformsMap.get( blurMaterial );
  16156. const pixels = this._sizeLods[ lodIn ] - 1;
  16157. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16158. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16159. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16160. if ( samples > MAX_SAMPLES ) {
  16161. console.warn( `sigmaRadians, ${
  16162. sigmaRadians}, is too large and will clip, as it requested ${
  16163. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16164. }
  16165. const weights = [];
  16166. let sum = 0;
  16167. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16168. const x = i / sigmaPixels;
  16169. const weight = Math.exp( - x * x / 2 );
  16170. weights.push( weight );
  16171. if ( i === 0 ) {
  16172. sum += weight;
  16173. } else if ( i < samples ) {
  16174. sum += 2 * weight;
  16175. }
  16176. }
  16177. for ( let i = 0; i < weights.length; i ++ ) {
  16178. weights[ i ] = weights[ i ] / sum;
  16179. }
  16180. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  16181. blurUniforms.envMap.value = targetIn.texture;
  16182. blurUniforms.samples.value = samples;
  16183. blurUniforms.weights.array = weights;
  16184. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  16185. if ( poleAxis ) {
  16186. blurUniforms.poleAxis.value = poleAxis;
  16187. }
  16188. const { _lodMax } = this;
  16189. blurUniforms.dTheta.value = radiansPerPixel;
  16190. blurUniforms.mipInt.value = _lodMax - lodIn;
  16191. const outputSize = this._sizeLods[ lodOut ];
  16192. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  16193. const y = 4 * ( this._cubeSize - outputSize );
  16194. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  16195. renderer.setRenderTarget( targetOut );
  16196. renderer.render( blurMesh, _flatCamera );
  16197. }
  16198. }
  16199. function _createPlanes( lodMax ) {
  16200. const lodPlanes = [];
  16201. const sizeLods = [];
  16202. const sigmas = [];
  16203. const lodMeshes = [];
  16204. let lod = lodMax;
  16205. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  16206. for ( let i = 0; i < totalLods; i ++ ) {
  16207. const sizeLod = Math.pow( 2, lod );
  16208. sizeLods.push( sizeLod );
  16209. let sigma = 1.0 / sizeLod;
  16210. if ( i > lodMax - LOD_MIN ) {
  16211. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  16212. } else if ( i === 0 ) {
  16213. sigma = 0;
  16214. }
  16215. sigmas.push( sigma );
  16216. const texelSize = 1.0 / ( sizeLod - 2 );
  16217. const min = - texelSize;
  16218. const max = 1 + texelSize;
  16219. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  16220. const cubeFaces = 6;
  16221. const vertices = 6;
  16222. const positionSize = 3;
  16223. const uvSize = 2;
  16224. const faceIndexSize = 1;
  16225. const position = new Float32Array( positionSize * vertices * cubeFaces );
  16226. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  16227. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  16228. for ( let face = 0; face < cubeFaces; face ++ ) {
  16229. const x = ( face % 3 ) * 2 / 3 - 1;
  16230. const y = face > 2 ? 0 : -1;
  16231. const coordinates = [
  16232. x, y, 0,
  16233. x + 2 / 3, y, 0,
  16234. x + 2 / 3, y + 1, 0,
  16235. x, y, 0,
  16236. x + 2 / 3, y + 1, 0,
  16237. x, y + 1, 0
  16238. ];
  16239. const faceIdx = _faceLib[ face ];
  16240. position.set( coordinates, positionSize * vertices * faceIdx );
  16241. uv.set( uv1, uvSize * vertices * faceIdx );
  16242. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  16243. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  16244. }
  16245. const planes = new BufferGeometry();
  16246. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  16247. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  16248. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  16249. lodPlanes.push( planes );
  16250. lodMeshes.push( new Mesh( planes, null ) );
  16251. if ( lod > LOD_MIN ) {
  16252. lod --;
  16253. }
  16254. }
  16255. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  16256. }
  16257. function _createRenderTarget( width, height ) {
  16258. const params = {
  16259. magFilter: LinearFilter,
  16260. minFilter: LinearFilter,
  16261. generateMipmaps: false,
  16262. type: HalfFloatType,
  16263. format: RGBAFormat,
  16264. colorSpace: LinearSRGBColorSpace,
  16265. //depthBuffer: false
  16266. };
  16267. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  16268. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  16269. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  16270. cubeUVRenderTarget.texture.isPMREMTexture = true;
  16271. cubeUVRenderTarget.scissorTest = true;
  16272. return cubeUVRenderTarget;
  16273. }
  16274. function _setViewport( target, x, y, width, height ) {
  16275. target.viewport.set( x, y, width, height );
  16276. target.scissor.set( x, y, width, height );
  16277. }
  16278. function _getMaterial( type ) {
  16279. const material = new NodeMaterial();
  16280. material.depthTest = false;
  16281. material.depthWrite = false;
  16282. material.blending = NoBlending;
  16283. material.name = `PMREM_${ type }`;
  16284. return material;
  16285. }
  16286. function _getBlurShader( lodMax, width, height ) {
  16287. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  16288. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  16289. const dTheta = uniform( 0 );
  16290. const n = float( MAX_SAMPLES );
  16291. const latitudinal = uniform( 0 ); // false, bool
  16292. const samples = uniform( 1 ); // int
  16293. const envMap = texture( null );
  16294. const mipInt = uniform( 0 ); // int
  16295. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  16296. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  16297. const CUBEUV_MAX_MIP = float( lodMax );
  16298. const materialUniforms = {
  16299. n,
  16300. latitudinal,
  16301. weights,
  16302. poleAxis,
  16303. outputDirection: _outputDirection,
  16304. dTheta,
  16305. samples,
  16306. envMap,
  16307. mipInt,
  16308. CUBEUV_TEXEL_WIDTH,
  16309. CUBEUV_TEXEL_HEIGHT,
  16310. CUBEUV_MAX_MIP
  16311. };
  16312. const material = _getMaterial( 'blur' );
  16313. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  16314. _uniformsMap.set( material, materialUniforms );
  16315. return material;
  16316. }
  16317. function _getCubemapMaterial( envTexture ) {
  16318. const material = _getMaterial( 'cubemap' );
  16319. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  16320. return material;
  16321. }
  16322. function _getEquirectMaterial( envTexture ) {
  16323. const material = _getMaterial( 'equirect' );
  16324. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  16325. return material;
  16326. }
  16327. const _cache = new WeakMap();
  16328. /**
  16329. * Generates the cubeUV size based on the given image height.
  16330. *
  16331. * @private
  16332. * @param {number} imageHeight - The image height.
  16333. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  16334. */
  16335. function _generateCubeUVSize( imageHeight ) {
  16336. const maxMip = Math.log2( imageHeight ) - 2;
  16337. const texelHeight = 1.0 / imageHeight;
  16338. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  16339. return { texelWidth, texelHeight, maxMip };
  16340. }
  16341. /**
  16342. * Generates a PMREM from the given texture.
  16343. *
  16344. * @private
  16345. * @param {Texture} texture - The texture to create the PMREM for.
  16346. * @param {Renderer} renderer - The renderer.
  16347. * @param {PMREMGenerator} generator - The PMREM generator.
  16348. * @return {?Texture} The PMREM.
  16349. */
  16350. function _getPMREMFromTexture( texture, renderer, generator ) {
  16351. const cache = _getCache( renderer );
  16352. let cacheTexture = cache.get( texture );
  16353. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  16354. if ( pmremVersion !== texture.pmremVersion ) {
  16355. const image = texture.image;
  16356. if ( texture.isCubeTexture ) {
  16357. if ( isCubeMapReady( image ) ) {
  16358. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  16359. } else {
  16360. return null;
  16361. }
  16362. } else {
  16363. if ( isEquirectangularMapReady( image ) ) {
  16364. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  16365. } else {
  16366. return null;
  16367. }
  16368. }
  16369. cacheTexture.pmremVersion = texture.pmremVersion;
  16370. cache.set( texture, cacheTexture );
  16371. }
  16372. return cacheTexture.texture;
  16373. }
  16374. /**
  16375. * Returns a cache that stores generated PMREMs for the respective textures.
  16376. * A cache must be maintained per renderer since PMREMs are render target textures
  16377. * which can't be shared across render contexts.
  16378. *
  16379. * @private
  16380. * @param {Renderer} renderer - The renderer.
  16381. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  16382. */
  16383. function _getCache( renderer ) {
  16384. let rendererCache = _cache.get( renderer );
  16385. if ( rendererCache === undefined ) {
  16386. rendererCache = new WeakMap();
  16387. _cache.set( renderer, rendererCache );
  16388. }
  16389. return rendererCache;
  16390. }
  16391. /**
  16392. * This node represents a PMREM which is a special type of preprocessed
  16393. * environment map intended for PBR materials.
  16394. *
  16395. * ```js
  16396. * const material = new MeshStandardNodeMaterial();
  16397. * material.envNode = pmremTexture( envMap );
  16398. * ```
  16399. *
  16400. * @augments TempNode
  16401. */
  16402. class PMREMNode extends TempNode {
  16403. static get type() {
  16404. return 'PMREMNode';
  16405. }
  16406. /**
  16407. * Constructs a new function overloading node.
  16408. *
  16409. * @param {Texture} value - The input texture.
  16410. * @param {Node<vec2>} [uvNode=null] - The uv node.
  16411. * @param {Node<float>} [levelNode=null] - The level node.
  16412. */
  16413. constructor( value, uvNode = null, levelNode = null ) {
  16414. super( 'vec3' );
  16415. /**
  16416. * Reference to the input texture.
  16417. *
  16418. * @private
  16419. * @type {Texture}
  16420. */
  16421. this._value = value;
  16422. /**
  16423. * Reference to the generated PMREM.
  16424. *
  16425. * @private
  16426. * @type {Texture | null}
  16427. * @default null
  16428. */
  16429. this._pmrem = null;
  16430. /**
  16431. * The uv node.
  16432. *
  16433. * @type {Node<vec2>}
  16434. */
  16435. this.uvNode = uvNode;
  16436. /**
  16437. * The level node.
  16438. *
  16439. * @type {Node<float>}
  16440. */
  16441. this.levelNode = levelNode;
  16442. /**
  16443. * Reference to a PMREM generator.
  16444. *
  16445. * @private
  16446. * @type {?PMREMGenerator}
  16447. * @default null
  16448. */
  16449. this._generator = null;
  16450. const defaultTexture = new Texture();
  16451. defaultTexture.isRenderTargetTexture = true;
  16452. /**
  16453. * The texture node holding the generated PMREM.
  16454. *
  16455. * @private
  16456. * @type {TextureNode}
  16457. */
  16458. this._texture = texture( defaultTexture );
  16459. /**
  16460. * A uniform representing the PMREM's width.
  16461. *
  16462. * @private
  16463. * @type {UniformNode<float>}
  16464. */
  16465. this._width = uniform( 0 );
  16466. /**
  16467. * A uniform representing the PMREM's height.
  16468. *
  16469. * @private
  16470. * @type {UniformNode<float>}
  16471. */
  16472. this._height = uniform( 0 );
  16473. /**
  16474. * A uniform representing the PMREM's max Mip.
  16475. *
  16476. * @private
  16477. * @type {UniformNode<float>}
  16478. */
  16479. this._maxMip = uniform( 0 );
  16480. /**
  16481. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  16482. *
  16483. * @type {string}
  16484. * @default 'render'
  16485. */
  16486. this.updateBeforeType = NodeUpdateType.RENDER;
  16487. }
  16488. set value( value ) {
  16489. this._value = value;
  16490. this._pmrem = null;
  16491. }
  16492. /**
  16493. * The node's texture value.
  16494. *
  16495. * @type {Texture}
  16496. */
  16497. get value() {
  16498. return this._value;
  16499. }
  16500. /**
  16501. * Uses the given PMREM texture to update internal values.
  16502. *
  16503. * @param {Texture} texture - The PMREM texture.
  16504. */
  16505. updateFromTexture( texture ) {
  16506. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  16507. this._texture.value = texture;
  16508. this._width.value = cubeUVSize.texelWidth;
  16509. this._height.value = cubeUVSize.texelHeight;
  16510. this._maxMip.value = cubeUVSize.maxMip;
  16511. }
  16512. updateBefore( frame ) {
  16513. let pmrem = this._pmrem;
  16514. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  16515. const texture = this._value;
  16516. if ( pmremVersion !== texture.pmremVersion ) {
  16517. if ( texture.isPMREMTexture === true ) {
  16518. pmrem = texture;
  16519. } else {
  16520. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  16521. }
  16522. if ( pmrem !== null ) {
  16523. this._pmrem = pmrem;
  16524. this.updateFromTexture( pmrem );
  16525. }
  16526. }
  16527. }
  16528. setup( builder ) {
  16529. if ( this._generator === null ) {
  16530. this._generator = new PMREMGenerator( builder.renderer );
  16531. }
  16532. this.updateBefore( builder );
  16533. //
  16534. let uvNode = this.uvNode;
  16535. if ( uvNode === null && builder.context.getUV ) {
  16536. uvNode = builder.context.getUV( this );
  16537. }
  16538. //
  16539. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  16540. //
  16541. let levelNode = this.levelNode;
  16542. if ( levelNode === null && builder.context.getTextureLevel ) {
  16543. levelNode = builder.context.getTextureLevel( this );
  16544. }
  16545. //
  16546. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  16547. }
  16548. dispose() {
  16549. super.dispose();
  16550. if ( this._generator !== null ) this._generator.dispose();
  16551. }
  16552. }
  16553. /**
  16554. * Returns `true` if the given cube map image has been fully loaded.
  16555. *
  16556. * @private
  16557. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  16558. * @return {boolean} Whether the given cube map is ready or not.
  16559. */
  16560. function isCubeMapReady( image ) {
  16561. if ( image === null || image === undefined ) return false;
  16562. let count = 0;
  16563. const length = 6;
  16564. for ( let i = 0; i < length; i ++ ) {
  16565. if ( image[ i ] !== undefined ) count ++;
  16566. }
  16567. return count === length;
  16568. }
  16569. /**
  16570. * Returns `true` if the given equirectangular image has been fully loaded.
  16571. *
  16572. * @private
  16573. * @param {(Image|Object)} image - The equirectangular image.
  16574. * @return {boolean} Whether the given cube map is ready or not.
  16575. */
  16576. function isEquirectangularMapReady( image ) {
  16577. if ( image === null || image === undefined ) return false;
  16578. return image.height > 0;
  16579. }
  16580. /**
  16581. * TSL function for creating a PMREM node.
  16582. *
  16583. * @tsl
  16584. * @function
  16585. * @param {Texture} value - The input texture.
  16586. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  16587. * @param {?Node<float>} [levelNode=null] - The level node.
  16588. * @returns {PMREMNode}
  16589. */
  16590. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  16591. const _envNodeCache = new WeakMap();
  16592. /**
  16593. * Represents a physical model for Image-based lighting (IBL). The environment
  16594. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  16595. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  16596. *
  16597. * @augments LightingNode
  16598. */
  16599. class EnvironmentNode extends LightingNode {
  16600. static get type() {
  16601. return 'EnvironmentNode';
  16602. }
  16603. /**
  16604. * Constructs a new environment node.
  16605. *
  16606. * @param {Node} [envNode=null] - A node representing the environment.
  16607. */
  16608. constructor( envNode = null ) {
  16609. super();
  16610. /**
  16611. * A node representing the environment.
  16612. *
  16613. * @type {?Node}
  16614. * @default null
  16615. */
  16616. this.envNode = envNode;
  16617. }
  16618. setup( builder ) {
  16619. const { material } = builder;
  16620. let envNode = this.envNode;
  16621. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  16622. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  16623. let cacheEnvNode = _envNodeCache.get( value );
  16624. if ( cacheEnvNode === undefined ) {
  16625. cacheEnvNode = pmremTexture( value );
  16626. _envNodeCache.set( value, cacheEnvNode );
  16627. }
  16628. envNode = cacheEnvNode;
  16629. }
  16630. //
  16631. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  16632. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  16633. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  16634. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  16635. const isolateRadiance = cache( radiance );
  16636. const isolateIrradiance = cache( irradiance );
  16637. //
  16638. builder.context.radiance.addAssign( isolateRadiance );
  16639. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  16640. //
  16641. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  16642. if ( clearcoatRadiance ) {
  16643. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( materialEnvIntensity );
  16644. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  16645. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  16646. }
  16647. }
  16648. }
  16649. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  16650. let reflectVec = null;
  16651. return {
  16652. getUV: () => {
  16653. if ( reflectVec === null ) {
  16654. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  16655. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  16656. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  16657. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  16658. }
  16659. return reflectVec;
  16660. },
  16661. getTextureLevel: () => {
  16662. return roughnessNode;
  16663. }
  16664. };
  16665. };
  16666. const createIrradianceContext = ( normalWorldNode ) => {
  16667. return {
  16668. getUV: () => {
  16669. return normalWorldNode;
  16670. },
  16671. getTextureLevel: () => {
  16672. return float( 1.0 );
  16673. }
  16674. };
  16675. };
  16676. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  16677. /**
  16678. * Node material version of {@link MeshStandardMaterial}.
  16679. *
  16680. * @augments NodeMaterial
  16681. */
  16682. class MeshStandardNodeMaterial extends NodeMaterial {
  16683. static get type() {
  16684. return 'MeshStandardNodeMaterial';
  16685. }
  16686. /**
  16687. * Constructs a new mesh standard node material.
  16688. *
  16689. * @param {Object} [parameters] - The configuration parameter.
  16690. */
  16691. constructor( parameters ) {
  16692. super();
  16693. /**
  16694. * This flag can be used for type testing.
  16695. *
  16696. * @type {boolean}
  16697. * @readonly
  16698. * @default true
  16699. */
  16700. this.isMeshStandardNodeMaterial = true;
  16701. /**
  16702. * Set to `true` because standard materials react on lights.
  16703. *
  16704. * @type {boolean}
  16705. * @default true
  16706. */
  16707. this.lights = true;
  16708. /**
  16709. * The emissive color of standard materials is by default inferred from the `emissive`,
  16710. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  16711. * overwrite the default and define the emissive color with a node instead.
  16712. *
  16713. * If you don't want to overwrite the emissive color but modify the existing
  16714. * value instead, use {@link materialEmissive}.
  16715. *
  16716. * @type {?Node<vec3>}
  16717. * @default null
  16718. */
  16719. this.emissiveNode = null;
  16720. /**
  16721. * The metalness of standard materials is by default inferred from the `metalness`,
  16722. * and `metalnessMap` properties. This node property allows to
  16723. * overwrite the default and define the metalness with a node instead.
  16724. *
  16725. * If you don't want to overwrite the metalness but modify the existing
  16726. * value instead, use {@link materialMetalness}.
  16727. *
  16728. * @type {?Node<float>}
  16729. * @default null
  16730. */
  16731. this.metalnessNode = null;
  16732. /**
  16733. * The roughness of standard materials is by default inferred from the `roughness`,
  16734. * and `roughnessMap` properties. This node property allows to
  16735. * overwrite the default and define the roughness with a node instead.
  16736. *
  16737. * If you don't want to overwrite the roughness but modify the existing
  16738. * value instead, use {@link materialRoughness}.
  16739. *
  16740. * @type {?Node<float>}
  16741. * @default null
  16742. */
  16743. this.roughnessNode = null;
  16744. this.setDefaultValues( _defaultValues$6 );
  16745. this.setValues( parameters );
  16746. }
  16747. /**
  16748. * Overwritten since this type of material uses {@link EnvironmentNode}
  16749. * to implement the PBR (PMREM based) environment mapping. Besides, the
  16750. * method honors `Scene.environment`.
  16751. *
  16752. * @param {NodeBuilder} builder - The current node builder.
  16753. * @return {?EnvironmentNode<vec3>} The environment node.
  16754. */
  16755. setupEnvironment( builder ) {
  16756. let envNode = super.setupEnvironment( builder );
  16757. if ( envNode === null && builder.environmentNode ) {
  16758. envNode = builder.environmentNode;
  16759. }
  16760. return envNode ? new EnvironmentNode( envNode ) : null;
  16761. }
  16762. /**
  16763. * Setups the lighting model.
  16764. *
  16765. * @return {PhysicalLightingModel} The lighting model.
  16766. */
  16767. setupLightingModel( /*builder*/ ) {
  16768. return new PhysicalLightingModel();
  16769. }
  16770. /**
  16771. * Setups the specular related node variables.
  16772. */
  16773. setupSpecular() {
  16774. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  16775. specularColor.assign( specularColorNode );
  16776. specularF90.assign( 1.0 );
  16777. }
  16778. /**
  16779. * Setups the standard specific node variables.
  16780. *
  16781. * @param {NodeBuilder} builder - The current node builder.
  16782. */
  16783. setupVariants() {
  16784. // METALNESS
  16785. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  16786. metalness.assign( metalnessNode );
  16787. // ROUGHNESS
  16788. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  16789. roughnessNode = getRoughness( { roughness: roughnessNode } );
  16790. roughness.assign( roughnessNode );
  16791. // SPECULAR COLOR
  16792. this.setupSpecular();
  16793. // DIFFUSE COLOR
  16794. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  16795. }
  16796. copy( source ) {
  16797. this.emissiveNode = source.emissiveNode;
  16798. this.metalnessNode = source.metalnessNode;
  16799. this.roughnessNode = source.roughnessNode;
  16800. return super.copy( source );
  16801. }
  16802. }
  16803. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  16804. /**
  16805. * Node material version of {@link MeshPhysicalMaterial}.
  16806. *
  16807. * @augments MeshStandardNodeMaterial
  16808. */
  16809. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  16810. static get type() {
  16811. return 'MeshPhysicalNodeMaterial';
  16812. }
  16813. /**
  16814. * Constructs a new mesh physical node material.
  16815. *
  16816. * @param {Object} [parameters] - The configuration parameter.
  16817. */
  16818. constructor( parameters ) {
  16819. super();
  16820. /**
  16821. * This flag can be used for type testing.
  16822. *
  16823. * @type {boolean}
  16824. * @readonly
  16825. * @default true
  16826. */
  16827. this.isMeshPhysicalNodeMaterial = true;
  16828. /**
  16829. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  16830. * and `clearcoatMap` properties. This node property allows to overwrite the default
  16831. * and define the clearcoat with a node instead.
  16832. *
  16833. * If you don't want to overwrite the clearcoat but modify the existing
  16834. * value instead, use {@link materialClearcoat}.
  16835. *
  16836. * @type {?Node<float>}
  16837. * @default null
  16838. */
  16839. this.clearcoatNode = null;
  16840. /**
  16841. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  16842. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  16843. * and define the clearcoat roughness with a node instead.
  16844. *
  16845. * If you don't want to overwrite the clearcoat roughness but modify the existing
  16846. * value instead, use {@link materialClearcoatRoughness}.
  16847. *
  16848. * @type {?Node<float>}
  16849. * @default null
  16850. */
  16851. this.clearcoatRoughnessNode = null;
  16852. /**
  16853. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  16854. * property. This node property allows to overwrite the default
  16855. * and define the clearcoat normal with a node instead.
  16856. *
  16857. * If you don't want to overwrite the clearcoat normal but modify the existing
  16858. * value instead, use {@link materialClearcoatNormal}.
  16859. *
  16860. * @type {?Node<vec3>}
  16861. * @default null
  16862. */
  16863. this.clearcoatNormalNode = null;
  16864. /**
  16865. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  16866. * and `sheenColorMap` properties. This node property allows to overwrite the default
  16867. * and define the sheen with a node instead.
  16868. *
  16869. * If you don't want to overwrite the sheen but modify the existing
  16870. * value instead, use {@link materialSheen}.
  16871. *
  16872. * @type {?Node<vec3>}
  16873. * @default null
  16874. */
  16875. this.sheenNode = null;
  16876. /**
  16877. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  16878. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  16879. * and define the sheen roughness with a node instead.
  16880. *
  16881. * If you don't want to overwrite the sheen roughness but modify the existing
  16882. * value instead, use {@link materialSheenRoughness}.
  16883. *
  16884. * @type {?Node<float>}
  16885. * @default null
  16886. */
  16887. this.sheenRoughnessNode = null;
  16888. /**
  16889. * The iridescence of physical materials is by default inferred from the `iridescence`
  16890. * property. This node property allows to overwrite the default
  16891. * and define the iridescence with a node instead.
  16892. *
  16893. * If you don't want to overwrite the iridescence but modify the existing
  16894. * value instead, use {@link materialIridescence}.
  16895. *
  16896. * @type {?Node<float>}
  16897. * @default null
  16898. */
  16899. this.iridescenceNode = null;
  16900. /**
  16901. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  16902. * property. This node property allows to overwrite the default
  16903. * and define the iridescence IOR with a node instead.
  16904. *
  16905. * If you don't want to overwrite the iridescence IOR but modify the existing
  16906. * value instead, use {@link materialIridescenceIOR}.
  16907. *
  16908. * @type {?Node<float>}
  16909. * @default null
  16910. */
  16911. this.iridescenceIORNode = null;
  16912. /**
  16913. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  16914. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  16915. * and define the iridescence thickness with a node instead.
  16916. *
  16917. * If you don't want to overwrite the iridescence thickness but modify the existing
  16918. * value instead, use {@link materialIridescenceThickness}.
  16919. *
  16920. * @type {?Node<float>}
  16921. * @default null
  16922. */
  16923. this.iridescenceThicknessNode = null;
  16924. /**
  16925. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  16926. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  16927. * and define the specular intensity with a node instead.
  16928. *
  16929. * If you don't want to overwrite the specular intensity but modify the existing
  16930. * value instead, use {@link materialSpecularIntensity}.
  16931. *
  16932. * @type {?Node<float>}
  16933. * @default null
  16934. */
  16935. this.specularIntensityNode = null;
  16936. /**
  16937. * The specular color of physical materials is by default inferred from the `specularColor`
  16938. * and `specularColorMap` properties. This node property allows to overwrite the default
  16939. * and define the specular color with a node instead.
  16940. *
  16941. * If you don't want to overwrite the specular color but modify the existing
  16942. * value instead, use {@link materialSpecularColor}.
  16943. *
  16944. * @type {?Node<vec3>}
  16945. * @default null
  16946. */
  16947. this.specularColorNode = null;
  16948. /**
  16949. * The ior of physical materials is by default inferred from the `ior`
  16950. * property. This node property allows to overwrite the default
  16951. * and define the ior with a node instead.
  16952. *
  16953. * If you don't want to overwrite the ior but modify the existing
  16954. * value instead, use {@link materialIOR}.
  16955. *
  16956. * @type {?Node<float>}
  16957. * @default null
  16958. */
  16959. this.iorNode = null;
  16960. /**
  16961. * The transmission of physical materials is by default inferred from the `transmission` and
  16962. * `transmissionMap` properties. This node property allows to overwrite the default
  16963. * and define the transmission with a node instead.
  16964. *
  16965. * If you don't want to overwrite the transmission but modify the existing
  16966. * value instead, use {@link materialTransmission}.
  16967. *
  16968. * @type {?Node<float>}
  16969. * @default null
  16970. */
  16971. this.transmissionNode = null;
  16972. /**
  16973. * The thickness of physical materials is by default inferred from the `thickness` and
  16974. * `thicknessMap` properties. This node property allows to overwrite the default
  16975. * and define the thickness with a node instead.
  16976. *
  16977. * If you don't want to overwrite the thickness but modify the existing
  16978. * value instead, use {@link materialThickness}.
  16979. *
  16980. * @type {?Node<float>}
  16981. * @default null
  16982. */
  16983. this.thicknessNode = null;
  16984. /**
  16985. * The attenuation distance of physical materials is by default inferred from the
  16986. * `attenuationDistance` property. This node property allows to overwrite the default
  16987. * and define the attenuation distance with a node instead.
  16988. *
  16989. * If you don't want to overwrite the attenuation distance but modify the existing
  16990. * value instead, use {@link materialAttenuationDistance}.
  16991. *
  16992. * @type {?Node<float>}
  16993. * @default null
  16994. */
  16995. this.attenuationDistanceNode = null;
  16996. /**
  16997. * The attenuation color of physical materials is by default inferred from the
  16998. * `attenuationColor` property. This node property allows to overwrite the default
  16999. * and define the attenuation color with a node instead.
  17000. *
  17001. * If you don't want to overwrite the attenuation color but modify the existing
  17002. * value instead, use {@link materialAttenuationColor}.
  17003. *
  17004. * @type {?Node<vec3>}
  17005. * @default null
  17006. */
  17007. this.attenuationColorNode = null;
  17008. /**
  17009. * The dispersion of physical materials is by default inferred from the
  17010. * `dispersion` property. This node property allows to overwrite the default
  17011. * and define the dispersion with a node instead.
  17012. *
  17013. * If you don't want to overwrite the dispersion but modify the existing
  17014. * value instead, use {@link materialDispersion}.
  17015. *
  17016. * @type {?Node<float>}
  17017. * @default null
  17018. */
  17019. this.dispersionNode = null;
  17020. /**
  17021. * The anisotropy of physical materials is by default inferred from the
  17022. * `anisotropy` property. This node property allows to overwrite the default
  17023. * and define the anisotropy with a node instead.
  17024. *
  17025. * If you don't want to overwrite the anisotropy but modify the existing
  17026. * value instead, use {@link materialAnisotropy}.
  17027. *
  17028. * @type {?Node<float>}
  17029. * @default null
  17030. */
  17031. this.anisotropyNode = null;
  17032. this.setDefaultValues( _defaultValues$5 );
  17033. this.setValues( parameters );
  17034. }
  17035. /**
  17036. * Whether the lighting model should use clearcoat or not.
  17037. *
  17038. * @type {boolean}
  17039. * @default true
  17040. */
  17041. get useClearcoat() {
  17042. return this.clearcoat > 0 || this.clearcoatNode !== null;
  17043. }
  17044. /**
  17045. * Whether the lighting model should use iridescence or not.
  17046. *
  17047. * @type {boolean}
  17048. * @default true
  17049. */
  17050. get useIridescence() {
  17051. return this.iridescence > 0 || this.iridescenceNode !== null;
  17052. }
  17053. /**
  17054. * Whether the lighting model should use sheen or not.
  17055. *
  17056. * @type {boolean}
  17057. * @default true
  17058. */
  17059. get useSheen() {
  17060. return this.sheen > 0 || this.sheenNode !== null;
  17061. }
  17062. /**
  17063. * Whether the lighting model should use anisotropy or not.
  17064. *
  17065. * @type {boolean}
  17066. * @default true
  17067. */
  17068. get useAnisotropy() {
  17069. return this.anisotropy > 0 || this.anisotropyNode !== null;
  17070. }
  17071. /**
  17072. * Whether the lighting model should use transmission or not.
  17073. *
  17074. * @type {boolean}
  17075. * @default true
  17076. */
  17077. get useTransmission() {
  17078. return this.transmission > 0 || this.transmissionNode !== null;
  17079. }
  17080. /**
  17081. * Whether the lighting model should use dispersion or not.
  17082. *
  17083. * @type {boolean}
  17084. * @default true
  17085. */
  17086. get useDispersion() {
  17087. return this.dispersion > 0 || this.dispersionNode !== null;
  17088. }
  17089. /**
  17090. * Setups the specular related node variables.
  17091. */
  17092. setupSpecular() {
  17093. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  17094. ior.assign( iorNode );
  17095. 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 ) );
  17096. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  17097. }
  17098. /**
  17099. * Setups the lighting model.
  17100. *
  17101. * @return {PhysicalLightingModel} The lighting model.
  17102. */
  17103. setupLightingModel( /*builder*/ ) {
  17104. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  17105. }
  17106. /**
  17107. * Setups the physical specific node variables.
  17108. *
  17109. * @param {NodeBuilder} builder - The current node builder.
  17110. */
  17111. setupVariants( builder ) {
  17112. super.setupVariants( builder );
  17113. // CLEARCOAT
  17114. if ( this.useClearcoat ) {
  17115. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  17116. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  17117. clearcoat.assign( clearcoatNode );
  17118. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  17119. }
  17120. // SHEEN
  17121. if ( this.useSheen ) {
  17122. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  17123. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  17124. sheen.assign( sheenNode );
  17125. sheenRoughness.assign( sheenRoughnessNode );
  17126. }
  17127. // IRIDESCENCE
  17128. if ( this.useIridescence ) {
  17129. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  17130. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  17131. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  17132. iridescence.assign( iridescenceNode );
  17133. iridescenceIOR.assign( iridescenceIORNode );
  17134. iridescenceThickness.assign( iridescenceThicknessNode );
  17135. }
  17136. // ANISOTROPY
  17137. if ( this.useAnisotropy ) {
  17138. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  17139. anisotropy.assign( anisotropyV.length() );
  17140. If( anisotropy.equal( 0.0 ), () => {
  17141. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  17142. } ).Else( () => {
  17143. anisotropyV.divAssign( vec2( anisotropy ) );
  17144. anisotropy.assign( anisotropy.saturate() );
  17145. } );
  17146. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  17147. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  17148. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  17149. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  17150. }
  17151. // TRANSMISSION
  17152. if ( this.useTransmission ) {
  17153. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  17154. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  17155. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  17156. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  17157. transmission.assign( transmissionNode );
  17158. thickness.assign( thicknessNode );
  17159. attenuationDistance.assign( attenuationDistanceNode );
  17160. attenuationColor.assign( attenuationColorNode );
  17161. if ( this.useDispersion ) {
  17162. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  17163. dispersion.assign( dispersionNode );
  17164. }
  17165. }
  17166. }
  17167. /**
  17168. * Setups the clearcoat normal node.
  17169. *
  17170. * @return {Node<vec3>} The clearcoat normal.
  17171. */
  17172. setupClearcoatNormal() {
  17173. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  17174. }
  17175. setup( builder ) {
  17176. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  17177. super.setup( builder );
  17178. }
  17179. copy( source ) {
  17180. this.clearcoatNode = source.clearcoatNode;
  17181. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  17182. this.clearcoatNormalNode = source.clearcoatNormalNode;
  17183. this.sheenNode = source.sheenNode;
  17184. this.sheenRoughnessNode = source.sheenRoughnessNode;
  17185. this.iridescenceNode = source.iridescenceNode;
  17186. this.iridescenceIORNode = source.iridescenceIORNode;
  17187. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  17188. this.specularIntensityNode = source.specularIntensityNode;
  17189. this.specularColorNode = source.specularColorNode;
  17190. this.transmissionNode = source.transmissionNode;
  17191. this.thicknessNode = source.thicknessNode;
  17192. this.attenuationDistanceNode = source.attenuationDistanceNode;
  17193. this.attenuationColorNode = source.attenuationColorNode;
  17194. this.dispersionNode = source.dispersionNode;
  17195. this.anisotropyNode = source.anisotropyNode;
  17196. return super.copy( source );
  17197. }
  17198. }
  17199. /**
  17200. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  17201. *
  17202. * @augments PhysicalLightingModel
  17203. */
  17204. class SSSLightingModel extends PhysicalLightingModel {
  17205. /**
  17206. * Constructs a new physical lighting model.
  17207. *
  17208. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17209. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17210. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17211. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17212. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17213. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17214. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  17215. */
  17216. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  17217. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  17218. /**
  17219. * Whether the lighting model should use SSS or not.
  17220. *
  17221. * @type {boolean}
  17222. * @default false
  17223. */
  17224. this.useSSS = sss;
  17225. }
  17226. /**
  17227. * Extends the default implementation with a SSS term.
  17228. *
  17229. * 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/}
  17230. *
  17231. * @param {Object} input - The input data.
  17232. * @param {NodeBuilder} builder - The current node builder.
  17233. */
  17234. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17235. if ( this.useSSS === true ) {
  17236. const material = builder.material;
  17237. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  17238. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  17239. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  17240. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  17241. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  17242. }
  17243. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  17244. }
  17245. }
  17246. /**
  17247. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  17248. * that implements a Subsurface scattering (SSS) term.
  17249. *
  17250. * @augments MeshPhysicalNodeMaterial
  17251. */
  17252. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  17253. static get type() {
  17254. return 'MeshSSSNodeMaterial';
  17255. }
  17256. /**
  17257. * Constructs a new mesh SSS node material.
  17258. *
  17259. * @param {Object} [parameters] - The configuration parameter.
  17260. */
  17261. constructor( parameters ) {
  17262. super( parameters );
  17263. /**
  17264. * Represents the thickness color.
  17265. *
  17266. * @type {?Node<vec3>}
  17267. * @default null
  17268. */
  17269. this.thicknessColorNode = null;
  17270. /**
  17271. * Represents the distortion factor.
  17272. *
  17273. * @type {?Node<float>}
  17274. */
  17275. this.thicknessDistortionNode = float( 0.1 );
  17276. /**
  17277. * Represents the thickness ambient factor.
  17278. *
  17279. * @type {?Node<float>}
  17280. */
  17281. this.thicknessAmbientNode = float( 0.0 );
  17282. /**
  17283. * Represents the thickness attenuation.
  17284. *
  17285. * @type {?Node<float>}
  17286. */
  17287. this.thicknessAttenuationNode = float( .1 );
  17288. /**
  17289. * Represents the thickness power.
  17290. *
  17291. * @type {?Node<float>}
  17292. */
  17293. this.thicknessPowerNode = float( 2.0 );
  17294. /**
  17295. * Represents the thickness scale.
  17296. *
  17297. * @type {?Node<float>}
  17298. */
  17299. this.thicknessScaleNode = float( 10.0 );
  17300. }
  17301. /**
  17302. * Whether the lighting model should use SSS or not.
  17303. *
  17304. * @type {boolean}
  17305. * @default true
  17306. */
  17307. get useSSS() {
  17308. return this.thicknessColorNode !== null;
  17309. }
  17310. /**
  17311. * Setups the lighting model.
  17312. *
  17313. * @return {SSSLightingModel} The lighting model.
  17314. */
  17315. setupLightingModel( /*builder*/ ) {
  17316. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  17317. }
  17318. copy( source ) {
  17319. this.thicknessColorNode = source.thicknessColorNode;
  17320. this.thicknessDistortionNode = source.thicknessDistortionNode;
  17321. this.thicknessAmbientNode = source.thicknessAmbientNode;
  17322. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  17323. this.thicknessPowerNode = source.thicknessPowerNode;
  17324. this.thicknessScaleNode = source.thicknessScaleNode;
  17325. return super.copy( source );
  17326. }
  17327. }
  17328. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  17329. // dotNL will be from -1.0 to 1.0
  17330. const dotNL = normal.dot( lightDirection );
  17331. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  17332. if ( builder.material.gradientMap ) {
  17333. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  17334. return vec3( gradientMap.r );
  17335. } else {
  17336. const fw = coord.fwidth().mul( 0.5 );
  17337. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  17338. }
  17339. } );
  17340. /**
  17341. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  17342. *
  17343. * @augments LightingModel
  17344. */
  17345. class ToonLightingModel extends LightingModel {
  17346. /**
  17347. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  17348. * reduced to a small number of discrete shades to create a comic-like, flat look.
  17349. *
  17350. * @param {Object} lightData - The light data.
  17351. * @param {NodeBuilder} builder - The current node builder.
  17352. */
  17353. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17354. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  17355. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  17356. }
  17357. /**
  17358. * Implements the indirect lighting.
  17359. *
  17360. * @param {NodeBuilder} builder - The current node builder.
  17361. */
  17362. indirect( builder ) {
  17363. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  17364. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  17365. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17366. }
  17367. }
  17368. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  17369. /**
  17370. * Node material version of {@link MeshToonMaterial}.
  17371. *
  17372. * @augments NodeMaterial
  17373. */
  17374. class MeshToonNodeMaterial extends NodeMaterial {
  17375. static get type() {
  17376. return 'MeshToonNodeMaterial';
  17377. }
  17378. /**
  17379. * Constructs a new mesh toon node material.
  17380. *
  17381. * @param {Object} [parameters] - The configuration parameter.
  17382. */
  17383. constructor( parameters ) {
  17384. super();
  17385. /**
  17386. * This flag can be used for type testing.
  17387. *
  17388. * @type {boolean}
  17389. * @readonly
  17390. * @default true
  17391. */
  17392. this.isMeshToonNodeMaterial = true;
  17393. /**
  17394. * Set to `true` because toon materials react on lights.
  17395. *
  17396. * @type {boolean}
  17397. * @default true
  17398. */
  17399. this.lights = true;
  17400. this.setDefaultValues( _defaultValues$4 );
  17401. this.setValues( parameters );
  17402. }
  17403. /**
  17404. * Setups the lighting model.
  17405. *
  17406. * @return {ToonLightingModel} The lighting model.
  17407. */
  17408. setupLightingModel( /*builder*/ ) {
  17409. return new ToonLightingModel();
  17410. }
  17411. }
  17412. /**
  17413. * Can be used to compute texture coordinates for projecting a
  17414. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  17415. *
  17416. * @augments TempNode
  17417. */
  17418. class MatcapUVNode extends TempNode {
  17419. static get type() {
  17420. return 'MatcapUVNode';
  17421. }
  17422. /**
  17423. * Constructs a new matcap uv node.
  17424. */
  17425. constructor() {
  17426. super( 'vec2' );
  17427. }
  17428. setup() {
  17429. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  17430. const y = positionViewDirection.cross( x );
  17431. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  17432. }
  17433. }
  17434. /**
  17435. * TSL function for creating a matcap uv node.
  17436. *
  17437. * @tsl
  17438. * @function
  17439. * @returns {MatcapUVNode}
  17440. */
  17441. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  17442. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  17443. /**
  17444. * Node material version of {@link MeshMatcapMaterial}.
  17445. *
  17446. * @augments NodeMaterial
  17447. */
  17448. class MeshMatcapNodeMaterial extends NodeMaterial {
  17449. static get type() {
  17450. return 'MeshMatcapNodeMaterial';
  17451. }
  17452. /**
  17453. * Constructs a new mesh normal node material.
  17454. *
  17455. * @param {Object} [parameters] - The configuration parameter.
  17456. */
  17457. constructor( parameters ) {
  17458. super();
  17459. /**
  17460. * This flag can be used for type testing.
  17461. *
  17462. * @type {boolean}
  17463. * @readonly
  17464. * @default true
  17465. */
  17466. this.isMeshMatcapNodeMaterial = true;
  17467. this.setDefaultValues( _defaultValues$3 );
  17468. this.setValues( parameters );
  17469. }
  17470. /**
  17471. * Setups the matcap specific node variables.
  17472. *
  17473. * @param {NodeBuilder} builder - The current node builder.
  17474. */
  17475. setupVariants( builder ) {
  17476. const uv = matcapUV;
  17477. let matcapColor;
  17478. if ( builder.material.matcap ) {
  17479. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  17480. } else {
  17481. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  17482. }
  17483. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  17484. }
  17485. }
  17486. /**
  17487. * Applies a rotation to the given position node.
  17488. *
  17489. * @augments TempNode
  17490. */
  17491. class RotateNode extends TempNode {
  17492. static get type() {
  17493. return 'RotateNode';
  17494. }
  17495. /**
  17496. * Constructs a new rotate node.
  17497. *
  17498. * @param {Node} positionNode - The position node.
  17499. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17500. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17501. */
  17502. constructor( positionNode, rotationNode ) {
  17503. super();
  17504. /**
  17505. * The position node.
  17506. *
  17507. * @type {Node}
  17508. */
  17509. this.positionNode = positionNode;
  17510. /**
  17511. * Represents the rotation that is applied to the position node.
  17512. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17513. *
  17514. * @type {Node}
  17515. */
  17516. this.rotationNode = rotationNode;
  17517. }
  17518. /**
  17519. * The type of the {@link RotateNode#positionNode} defines the node's type.
  17520. *
  17521. * @param {NodeBuilder} builder - The current node builder.
  17522. * @return {string} The node's type.
  17523. */
  17524. getNodeType( builder ) {
  17525. return this.positionNode.getNodeType( builder );
  17526. }
  17527. setup( builder ) {
  17528. const { rotationNode, positionNode } = this;
  17529. const nodeType = this.getNodeType( builder );
  17530. if ( nodeType === 'vec2' ) {
  17531. const cosAngle = rotationNode.cos();
  17532. const sinAngle = rotationNode.sin();
  17533. const rotationMatrix = mat2(
  17534. cosAngle, sinAngle,
  17535. sinAngle.negate(), cosAngle
  17536. );
  17537. return rotationMatrix.mul( positionNode );
  17538. } else {
  17539. const rotation = rotationNode;
  17540. 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 ) );
  17541. 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 ) );
  17542. 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 ) );
  17543. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  17544. }
  17545. }
  17546. }
  17547. /**
  17548. * TSL function for creating a rotate node.
  17549. *
  17550. * @tsl
  17551. * @function
  17552. * @param {Node} positionNode - The position node.
  17553. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17554. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17555. * @returns {RotateNode}
  17556. */
  17557. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  17558. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  17559. /**
  17560. * Node material version of {@link SpriteMaterial}.
  17561. *
  17562. * @augments NodeMaterial
  17563. */
  17564. class SpriteNodeMaterial extends NodeMaterial {
  17565. static get type() {
  17566. return 'SpriteNodeMaterial';
  17567. }
  17568. /**
  17569. * Constructs a new sprite node material.
  17570. *
  17571. * @param {Object} [parameters] - The configuration parameter.
  17572. */
  17573. constructor( parameters ) {
  17574. super();
  17575. /**
  17576. * This flag can be used for type testing.
  17577. *
  17578. * @type {boolean}
  17579. * @readonly
  17580. * @default true
  17581. */
  17582. this.isSpriteNodeMaterial = true;
  17583. this._useSizeAttenuation = true;
  17584. /**
  17585. * This property makes it possible to define the position of the sprite with a
  17586. * node. That can be useful when the material is used with instanced rendering
  17587. * and node data are defined with an instanced attribute node:
  17588. * ```js
  17589. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  17590. * material.positionNode = instancedBufferAttribute( positionAttribute );
  17591. * ```
  17592. * Another possibility is to compute the instanced data with a compute shader:
  17593. * ```js
  17594. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  17595. * particleMaterial.positionNode = positionBuffer.toAttribute();
  17596. * ```
  17597. *
  17598. * @type {?Node<vec2>}
  17599. * @default null
  17600. */
  17601. this.positionNode = null;
  17602. /**
  17603. * The rotation of sprite materials is by default inferred from the `rotation`,
  17604. * property. This node property allows to overwrite the default and define
  17605. * the rotation with a node instead.
  17606. *
  17607. * If you don't want to overwrite the rotation but modify the existing
  17608. * value instead, use {@link materialRotation}.
  17609. *
  17610. * @type {?Node<float>}
  17611. * @default null
  17612. */
  17613. this.rotationNode = null;
  17614. /**
  17615. * This node property provides an additional way to scale sprites next to
  17616. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  17617. * is multiplied with the scale value of this node in the vertex shader.
  17618. *
  17619. * @type {?Node<vec2>}
  17620. * @default null
  17621. */
  17622. this.scaleNode = null;
  17623. /**
  17624. * In Sprites, the transparent property is enabled by default.
  17625. *
  17626. * @type {boolean}
  17627. * @default true
  17628. */
  17629. this.transparent = true;
  17630. this.setDefaultValues( _defaultValues$2 );
  17631. this.setValues( parameters );
  17632. }
  17633. /**
  17634. * Setups the position node in view space. This method implements
  17635. * the sprite specific vertex shader.
  17636. *
  17637. * @param {NodeBuilder} builder - The current node builder.
  17638. * @return {Node<vec3>} The position in view space.
  17639. */
  17640. setupPositionView( builder ) {
  17641. const { object, camera } = builder;
  17642. const sizeAttenuation = this.sizeAttenuation;
  17643. const { positionNode, rotationNode, scaleNode } = this;
  17644. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  17645. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  17646. if ( scaleNode !== null ) {
  17647. scale = scale.mul( vec2( scaleNode ) );
  17648. }
  17649. if ( sizeAttenuation === false ) {
  17650. if ( camera.isPerspectiveCamera ) {
  17651. scale = scale.mul( mvPosition.z.negate() );
  17652. } else {
  17653. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  17654. scale = scale.mul( orthoScale.mul( 2 ) );
  17655. }
  17656. }
  17657. let alignedPosition = positionGeometry.xy;
  17658. if ( object.center && object.center.isVector2 === true ) {
  17659. const center = reference$1( 'center', 'vec2', object );
  17660. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  17661. }
  17662. alignedPosition = alignedPosition.mul( scale );
  17663. const rotation = float( rotationNode || materialRotation );
  17664. const rotatedPosition = rotate( alignedPosition, rotation );
  17665. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  17666. }
  17667. copy( source ) {
  17668. this.positionNode = source.positionNode;
  17669. this.rotationNode = source.rotationNode;
  17670. this.scaleNode = source.scaleNode;
  17671. return super.copy( source );
  17672. }
  17673. /**
  17674. * Whether to use size attenuation or not.
  17675. *
  17676. * @type {boolean}
  17677. * @default true
  17678. */
  17679. get sizeAttenuation() {
  17680. return this._useSizeAttenuation;
  17681. }
  17682. set sizeAttenuation( value ) {
  17683. if ( this._useSizeAttenuation !== value ) {
  17684. this._useSizeAttenuation = value;
  17685. this.needsUpdate = true;
  17686. }
  17687. }
  17688. }
  17689. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  17690. /**
  17691. * Node material version of {@link PointsMaterial}.
  17692. *
  17693. * @augments SpriteNodeMaterial
  17694. */
  17695. class PointsNodeMaterial extends SpriteNodeMaterial {
  17696. static get type() {
  17697. return 'PointsNodeMaterial';
  17698. }
  17699. /**
  17700. * Constructs a new points node material.
  17701. *
  17702. * @param {Object} [parameters] - The configuration parameter.
  17703. */
  17704. constructor( parameters ) {
  17705. super();
  17706. /**
  17707. * This node property provides an additional way to set the point size.
  17708. *
  17709. * @type {?Node<vec2>}
  17710. * @default null
  17711. */
  17712. this.sizeNode = null;
  17713. /**
  17714. * This flag can be used for type testing.
  17715. *
  17716. * @type {boolean}
  17717. * @readonly
  17718. * @default true
  17719. */
  17720. this.isPointsNodeMaterial = true;
  17721. this.setDefaultValues( _defaultValues$1 );
  17722. this.setValues( parameters );
  17723. }
  17724. setupPositionView() {
  17725. const { positionNode } = this;
  17726. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  17727. }
  17728. setupVertex( builder ) {
  17729. const mvp = super.setupVertex( builder );
  17730. // skip further processing if the material is not a node material
  17731. if ( builder.material.isNodeMaterial !== true ) {
  17732. return mvp;
  17733. }
  17734. // ndc space
  17735. const { rotationNode, scaleNode, sizeNode } = this;
  17736. const alignedPosition = positionGeometry.xy.toVar();
  17737. const aspect = viewport.z.div( viewport.w );
  17738. // rotation
  17739. if ( rotationNode && rotationNode.isNode ) {
  17740. const rotation = float( rotationNode );
  17741. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  17742. }
  17743. // point size
  17744. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  17745. if ( this.sizeAttenuation === true ) {
  17746. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  17747. }
  17748. // scale
  17749. if ( scaleNode && scaleNode.isNode ) {
  17750. pointSize = pointSize.mul( vec2( scaleNode ) );
  17751. }
  17752. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  17753. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  17754. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  17755. // back to clip space
  17756. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  17757. //clipPos.xy += offset;
  17758. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  17759. return mvp;
  17760. }
  17761. /**
  17762. * Whether alpha to coverage should be used or not.
  17763. *
  17764. * @type {boolean}
  17765. * @default true
  17766. */
  17767. get alphaToCoverage() {
  17768. return this._useAlphaToCoverage;
  17769. }
  17770. set alphaToCoverage( value ) {
  17771. if ( this._useAlphaToCoverage !== value ) {
  17772. this._useAlphaToCoverage = value;
  17773. this.needsUpdate = true;
  17774. }
  17775. }
  17776. }
  17777. /**
  17778. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  17779. *
  17780. * @augments LightingModel
  17781. */
  17782. class ShadowMaskModel extends LightingModel {
  17783. /**
  17784. * Constructs a new shadow mask model.
  17785. */
  17786. constructor() {
  17787. super();
  17788. /**
  17789. * The shadow mask node.
  17790. *
  17791. * @type {Node}
  17792. */
  17793. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  17794. }
  17795. /**
  17796. * Only used to save the shadow mask.
  17797. *
  17798. * @param {Object} input - The input data.
  17799. */
  17800. direct( { lightNode } ) {
  17801. this.shadowNode.mulAssign( lightNode.shadowNode );
  17802. }
  17803. /**
  17804. * Uses the shadow mask to produce the final color.
  17805. *
  17806. * @param {NodeBuilder} builder - The current node builder.
  17807. */
  17808. finish( { context } ) {
  17809. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  17810. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  17811. }
  17812. }
  17813. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  17814. /**
  17815. * Node material version of {@link ShadowMaterial}.
  17816. *
  17817. * @augments NodeMaterial
  17818. */
  17819. class ShadowNodeMaterial extends NodeMaterial {
  17820. static get type() {
  17821. return 'ShadowNodeMaterial';
  17822. }
  17823. /**
  17824. * Constructs a new shadow node material.
  17825. *
  17826. * @param {Object} [parameters] - The configuration parameter.
  17827. */
  17828. constructor( parameters ) {
  17829. super();
  17830. /**
  17831. * This flag can be used for type testing.
  17832. *
  17833. * @type {boolean}
  17834. * @readonly
  17835. * @default true
  17836. */
  17837. this.isShadowNodeMaterial = true;
  17838. /**
  17839. * Set to `true` because so it's possible to implement
  17840. * the shadow mask effect.
  17841. *
  17842. * @type {boolean}
  17843. * @default true
  17844. */
  17845. this.lights = true;
  17846. /**
  17847. * Overwritten since shadow materials are transparent
  17848. * by default.
  17849. *
  17850. * @type {boolean}
  17851. * @default true
  17852. */
  17853. this.transparent = true;
  17854. this.setDefaultValues( _defaultValues );
  17855. this.setValues( parameters );
  17856. }
  17857. /**
  17858. * Setups the lighting model.
  17859. *
  17860. * @return {ShadowMaskModel} The lighting model.
  17861. */
  17862. setupLightingModel( /*builder*/ ) {
  17863. return new ShadowMaskModel();
  17864. }
  17865. }
  17866. const scatteringDensity = property( 'vec3' );
  17867. const linearDepthRay = property( 'vec3' );
  17868. const outgoingRayLight = property( 'vec3' );
  17869. /**
  17870. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  17871. * This model calculates the scattering and transmittance of light through a volumetric medium.
  17872. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  17873. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  17874. *
  17875. * @augments LightingModel
  17876. */
  17877. class VolumetricLightingModel extends LightingModel {
  17878. constructor() {
  17879. super();
  17880. }
  17881. start( builder ) {
  17882. const { material, context } = builder;
  17883. const startPos = property( 'vec3' );
  17884. const endPos = property( 'vec3' );
  17885. // This approach dynamically changes the direction of the ray,
  17886. // 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.
  17887. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  17888. startPos.assign( cameraPosition );
  17889. endPos.assign( positionWorld );
  17890. } ).Else( () => {
  17891. startPos.assign( positionWorld );
  17892. endPos.assign( cameraPosition );
  17893. } );
  17894. //
  17895. const viewVector = endPos.sub( startPos );
  17896. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  17897. const stepSize = viewVector.length().div( steps ).toVar();
  17898. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  17899. const distTravelled = float( 0.0 ).toVar();
  17900. const transmittance = vec3( 1 ).toVar();
  17901. if ( material.offsetNode ) {
  17902. // reduce banding
  17903. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  17904. }
  17905. Loop( steps, () => {
  17906. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  17907. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  17908. if ( material.depthNode !== null ) {
  17909. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  17910. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  17911. }
  17912. context.positionWorld = positionRay;
  17913. context.shadowPositionWorld = positionRay;
  17914. context.positionView = positionViewRay;
  17915. scatteringDensity.assign( 0 );
  17916. let scatteringNode;
  17917. if ( material.scatteringNode ) {
  17918. scatteringNode = material.scatteringNode( {
  17919. positionRay
  17920. } );
  17921. }
  17922. super.start( builder );
  17923. if ( scatteringNode ) {
  17924. scatteringDensity.mulAssign( scatteringNode );
  17925. }
  17926. // beer's law
  17927. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  17928. transmittance.mulAssign( falloff );
  17929. // move along the ray
  17930. distTravelled.addAssign( stepSize );
  17931. } );
  17932. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  17933. }
  17934. scatteringLight( lightColor, builder ) {
  17935. const sceneDepthNode = builder.context.sceneDepthNode;
  17936. if ( sceneDepthNode ) {
  17937. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  17938. scatteringDensity.addAssign( lightColor );
  17939. } );
  17940. } else {
  17941. scatteringDensity.addAssign( lightColor );
  17942. }
  17943. }
  17944. direct( { lightNode, lightColor }, builder ) {
  17945. // Ignore lights with infinite distance
  17946. if ( lightNode.light.distance === undefined ) return;
  17947. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  17948. const directLight = lightColor.xyz.toVar();
  17949. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  17950. this.scatteringLight( directLight, builder );
  17951. }
  17952. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  17953. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17954. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17955. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17956. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17957. const P = builder.context.positionView;
  17958. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  17959. this.scatteringLight( directLight, builder );
  17960. }
  17961. finish( builder ) {
  17962. builder.context.outgoingLight.assign( outgoingRayLight );
  17963. }
  17964. }
  17965. /**
  17966. * Volume node material.
  17967. *
  17968. * @augments NodeMaterial
  17969. */
  17970. class VolumeNodeMaterial extends NodeMaterial {
  17971. static get type() {
  17972. return 'VolumeNodeMaterial';
  17973. }
  17974. /**
  17975. * Constructs a new volume node material.
  17976. *
  17977. * @param {Object} [parameters] - The configuration parameter.
  17978. */
  17979. constructor( parameters ) {
  17980. super();
  17981. /**
  17982. * This flag can be used for type testing.
  17983. *
  17984. * @type {boolean}
  17985. * @readonly
  17986. * @default true
  17987. */
  17988. this.isVolumeNodeMaterial = true;
  17989. /**
  17990. * Number of steps used for raymarching.
  17991. *
  17992. * @type {number}
  17993. * @default 25
  17994. */
  17995. this.steps = 25;
  17996. /**
  17997. * Offsets the distance a ray has been traveled through a volume.
  17998. * Can be used to implement dithering to reduce banding.
  17999. *
  18000. * @type {Node<float>}
  18001. * @default null
  18002. */
  18003. this.offsetNode = null;
  18004. /**
  18005. * Node used for scattering calculations.
  18006. *
  18007. * @type {Function|FunctionNode<vec4>}
  18008. * @default null
  18009. */
  18010. this.scatteringNode = null;
  18011. this.lights = true;
  18012. this.transparent = true;
  18013. this.side = BackSide;
  18014. this.depthTest = false;
  18015. this.depthWrite = false;
  18016. this.setValues( parameters );
  18017. }
  18018. setupLightingModel() {
  18019. return new VolumetricLightingModel();
  18020. }
  18021. }
  18022. /**
  18023. * This module manages the internal animation loop of the renderer.
  18024. *
  18025. * @private
  18026. */
  18027. class Animation {
  18028. /**
  18029. * Constructs a new animation loop management component.
  18030. *
  18031. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18032. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18033. */
  18034. constructor( nodes, info ) {
  18035. /**
  18036. * Renderer component for managing nodes related logic.
  18037. *
  18038. * @type {Nodes}
  18039. */
  18040. this.nodes = nodes;
  18041. /**
  18042. * Renderer component for managing metrics and monitoring data.
  18043. *
  18044. * @type {Info}
  18045. */
  18046. this.info = info;
  18047. /**
  18048. * A reference to the context from `requestAnimationFrame()` can
  18049. * be called (usually `window`).
  18050. *
  18051. * @type {?(Window|XRSession)}
  18052. */
  18053. this._context = typeof self !== 'undefined' ? self : null;
  18054. /**
  18055. * The user-defined animation loop.
  18056. *
  18057. * @type {?Function}
  18058. * @default null
  18059. */
  18060. this._animationLoop = null;
  18061. /**
  18062. * The requestId which is returned from the `requestAnimationFrame()` call.
  18063. * Can be used to cancel the stop the animation loop.
  18064. *
  18065. * @type {?number}
  18066. * @default null
  18067. */
  18068. this._requestId = null;
  18069. }
  18070. /**
  18071. * Starts the internal animation loop.
  18072. */
  18073. start() {
  18074. const update = ( time, xrFrame ) => {
  18075. this._requestId = this._context.requestAnimationFrame( update );
  18076. if ( this.info.autoReset === true ) this.info.reset();
  18077. this.nodes.nodeFrame.update();
  18078. this.info.frame = this.nodes.nodeFrame.frameId;
  18079. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  18080. };
  18081. update();
  18082. }
  18083. /**
  18084. * Stops the internal animation loop.
  18085. */
  18086. stop() {
  18087. this._context.cancelAnimationFrame( this._requestId );
  18088. this._requestId = null;
  18089. }
  18090. /**
  18091. * Returns the user-level animation loop.
  18092. *
  18093. * @return {?Function} The animation loop.
  18094. */
  18095. getAnimationLoop() {
  18096. return this._animationLoop;
  18097. }
  18098. /**
  18099. * Defines the user-level animation loop.
  18100. *
  18101. * @param {?Function} callback - The animation loop.
  18102. */
  18103. setAnimationLoop( callback ) {
  18104. this._animationLoop = callback;
  18105. }
  18106. /**
  18107. * Returns the animation context.
  18108. *
  18109. * @return {Window|XRSession} The animation context.
  18110. */
  18111. getContext() {
  18112. return this._context;
  18113. }
  18114. /**
  18115. * Defines the context in which `requestAnimationFrame()` is executed.
  18116. *
  18117. * @param {Window|XRSession} context - The context to set.
  18118. */
  18119. setContext( context ) {
  18120. this._context = context;
  18121. }
  18122. /**
  18123. * Frees all internal resources and stops the animation loop.
  18124. */
  18125. dispose() {
  18126. this.stop();
  18127. }
  18128. }
  18129. /**
  18130. * Data structure for the renderer. It allows defining values
  18131. * with chained, hierarchical keys. Keys are meant to be
  18132. * objects since the module internally works with Weak Maps
  18133. * for performance reasons.
  18134. *
  18135. * @private
  18136. */
  18137. class ChainMap {
  18138. /**
  18139. * Constructs a new Chain Map.
  18140. */
  18141. constructor() {
  18142. /**
  18143. * The root Weak Map.
  18144. *
  18145. * @type {WeakMap}
  18146. */
  18147. this.weakMap = new WeakMap();
  18148. }
  18149. /**
  18150. * Returns the value for the given array of keys.
  18151. *
  18152. * @param {Array<Object>} keys - List of keys.
  18153. * @return {any} The value. Returns `undefined` if no value was found.
  18154. */
  18155. get( keys ) {
  18156. let map = this.weakMap;
  18157. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18158. map = map.get( keys[ i ] );
  18159. if ( map === undefined ) return undefined;
  18160. }
  18161. return map.get( keys[ keys.length - 1 ] );
  18162. }
  18163. /**
  18164. * Sets the value for the given keys.
  18165. *
  18166. * @param {Array<Object>} keys - List of keys.
  18167. * @param {any} value - The value to set.
  18168. * @return {ChainMap} A reference to this Chain Map.
  18169. */
  18170. set( keys, value ) {
  18171. let map = this.weakMap;
  18172. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18173. const key = keys[ i ];
  18174. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  18175. map = map.get( key );
  18176. }
  18177. map.set( keys[ keys.length - 1 ], value );
  18178. return this;
  18179. }
  18180. /**
  18181. * Deletes a value for the given keys.
  18182. *
  18183. * @param {Array<Object>} keys - The keys.
  18184. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  18185. */
  18186. delete( keys ) {
  18187. let map = this.weakMap;
  18188. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18189. map = map.get( keys[ i ] );
  18190. if ( map === undefined ) return false;
  18191. }
  18192. return map.delete( keys[ keys.length - 1 ] );
  18193. }
  18194. }
  18195. let _id$9 = 0;
  18196. function getKeys( obj ) {
  18197. const keys = Object.keys( obj );
  18198. let proto = Object.getPrototypeOf( obj );
  18199. while ( proto ) {
  18200. const descriptors = Object.getOwnPropertyDescriptors( proto );
  18201. for ( const key in descriptors ) {
  18202. if ( descriptors[ key ] !== undefined ) {
  18203. const descriptor = descriptors[ key ];
  18204. if ( descriptor && typeof descriptor.get === 'function' ) {
  18205. keys.push( key );
  18206. }
  18207. }
  18208. }
  18209. proto = Object.getPrototypeOf( proto );
  18210. }
  18211. return keys;
  18212. }
  18213. /**
  18214. * A render object is the renderer's representation of single entity that gets drawn
  18215. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  18216. * scene since render objects also depend from the used material, the current render context
  18217. * and the current scene's lighting.
  18218. *
  18219. * In general, the basic process of the renderer is:
  18220. *
  18221. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  18222. * - Process the render lists by calling one or more render commands for each render item.
  18223. * - For each render command, request a render object and perform the draw.
  18224. *
  18225. * The module provides an interface to get data required for the draw command like the actual
  18226. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  18227. * creating render objects should only be done when necessary.
  18228. *
  18229. * @private
  18230. */
  18231. class RenderObject {
  18232. /**
  18233. * Constructs a new render object.
  18234. *
  18235. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18236. * @param {Geometries} geometries - Renderer component for managing geometries.
  18237. * @param {Renderer} renderer - The renderer.
  18238. * @param {Object3D} object - The 3D object.
  18239. * @param {Material} material - The 3D object's material.
  18240. * @param {Scene} scene - The scene the 3D object belongs to.
  18241. * @param {Camera} camera - The camera the object should be rendered with.
  18242. * @param {LightsNode} lightsNode - The lights node.
  18243. * @param {RenderContext} renderContext - The render context.
  18244. * @param {ClippingContext} clippingContext - The clipping context.
  18245. */
  18246. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  18247. this.id = _id$9 ++;
  18248. /**
  18249. * Renderer component for managing nodes related logic.
  18250. *
  18251. * @type {Nodes}
  18252. * @private
  18253. */
  18254. this._nodes = nodes;
  18255. /**
  18256. * Renderer component for managing geometries.
  18257. *
  18258. * @type {Geometries}
  18259. * @private
  18260. */
  18261. this._geometries = geometries;
  18262. /**
  18263. * The renderer.
  18264. *
  18265. * @type {Renderer}
  18266. */
  18267. this.renderer = renderer;
  18268. /**
  18269. * The 3D object.
  18270. *
  18271. * @type {Object3D}
  18272. */
  18273. this.object = object;
  18274. /**
  18275. * The 3D object's material.
  18276. *
  18277. * @type {Material}
  18278. */
  18279. this.material = material;
  18280. /**
  18281. * The scene the 3D object belongs to.
  18282. *
  18283. * @type {Scene}
  18284. */
  18285. this.scene = scene;
  18286. /**
  18287. * The camera the 3D object should be rendered with.
  18288. *
  18289. * @type {Camera}
  18290. */
  18291. this.camera = camera;
  18292. /**
  18293. * The lights node.
  18294. *
  18295. * @type {LightsNode}
  18296. */
  18297. this.lightsNode = lightsNode;
  18298. /**
  18299. * The render context.
  18300. *
  18301. * @type {RenderContext}
  18302. */
  18303. this.context = renderContext;
  18304. /**
  18305. * The 3D object's geometry.
  18306. *
  18307. * @type {BufferGeometry}
  18308. */
  18309. this.geometry = object.geometry;
  18310. /**
  18311. * The render object's version.
  18312. *
  18313. * @type {number}
  18314. */
  18315. this.version = material.version;
  18316. /**
  18317. * The draw range of the geometry.
  18318. *
  18319. * @type {?Object}
  18320. * @default null
  18321. */
  18322. this.drawRange = null;
  18323. /**
  18324. * An array holding the buffer attributes
  18325. * of the render object. This entails attribute
  18326. * definitions on geometry and node level.
  18327. *
  18328. * @type {?Array<BufferAttribute>}
  18329. * @default null
  18330. */
  18331. this.attributes = null;
  18332. /**
  18333. * A reference to a render pipeline the render
  18334. * object is processed with.
  18335. *
  18336. * @type {RenderPipeline}
  18337. * @default null
  18338. */
  18339. this.pipeline = null;
  18340. /**
  18341. * Only relevant for objects using
  18342. * multiple materials. This represents a group entry
  18343. * from the respective `BufferGeometry`.
  18344. *
  18345. * @type {?{start: number, count: number}}
  18346. * @default null
  18347. */
  18348. this.group = null;
  18349. /**
  18350. * An array holding the vertex buffers which can
  18351. * be buffer attributes but also interleaved buffers.
  18352. *
  18353. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  18354. * @default null
  18355. */
  18356. this.vertexBuffers = null;
  18357. /**
  18358. * The parameters for the draw command.
  18359. *
  18360. * @type {?Object}
  18361. * @default null
  18362. */
  18363. this.drawParams = null;
  18364. /**
  18365. * If this render object is used inside a render bundle,
  18366. * this property points to the respective bundle group.
  18367. *
  18368. * @type {?BundleGroup}
  18369. * @default null
  18370. */
  18371. this.bundle = null;
  18372. /**
  18373. * The clipping context.
  18374. *
  18375. * @type {ClippingContext}
  18376. */
  18377. this.clippingContext = clippingContext;
  18378. /**
  18379. * The clipping context's cache key.
  18380. *
  18381. * @type {string}
  18382. */
  18383. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  18384. /**
  18385. * The initial node cache key.
  18386. *
  18387. * @type {number}
  18388. */
  18389. this.initialNodesCacheKey = this.getDynamicCacheKey();
  18390. /**
  18391. * The initial cache key.
  18392. *
  18393. * @type {number}
  18394. */
  18395. this.initialCacheKey = this.getCacheKey();
  18396. /**
  18397. * The node builder state.
  18398. *
  18399. * @type {?NodeBuilderState}
  18400. * @private
  18401. * @default null
  18402. */
  18403. this._nodeBuilderState = null;
  18404. /**
  18405. * An array of bindings.
  18406. *
  18407. * @type {?Array<BindGroup>}
  18408. * @private
  18409. * @default null
  18410. */
  18411. this._bindings = null;
  18412. /**
  18413. * Reference to the node material observer.
  18414. *
  18415. * @type {?NodeMaterialObserver}
  18416. * @private
  18417. * @default null
  18418. */
  18419. this._monitor = null;
  18420. /**
  18421. * An event listener which is defined by `RenderObjects`. It performs
  18422. * clean up tasks when `dispose()` on this render object.
  18423. *
  18424. * @method
  18425. */
  18426. this.onDispose = null;
  18427. /**
  18428. * This flag can be used for type testing.
  18429. *
  18430. * @type {boolean}
  18431. * @readonly
  18432. * @default true
  18433. */
  18434. this.isRenderObject = true;
  18435. /**
  18436. * An event listener which is executed when `dispose()` is called on
  18437. * the render object's material.
  18438. *
  18439. * @method
  18440. */
  18441. this.onMaterialDispose = () => {
  18442. this.dispose();
  18443. };
  18444. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  18445. }
  18446. /**
  18447. * Updates the clipping context.
  18448. *
  18449. * @param {ClippingContext} context - The clipping context to set.
  18450. */
  18451. updateClipping( context ) {
  18452. this.clippingContext = context;
  18453. }
  18454. /**
  18455. * Whether the clipping requires an update or not.
  18456. *
  18457. * @type {boolean}
  18458. * @readonly
  18459. */
  18460. get clippingNeedsUpdate() {
  18461. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  18462. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  18463. return true;
  18464. }
  18465. /**
  18466. * The number of clipping planes defined in context of hardware clipping.
  18467. *
  18468. * @type {number}
  18469. * @readonly
  18470. */
  18471. get hardwareClippingPlanes() {
  18472. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  18473. }
  18474. /**
  18475. * Returns the node builder state of this render object.
  18476. *
  18477. * @return {NodeBuilderState} The node builder state.
  18478. */
  18479. getNodeBuilderState() {
  18480. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  18481. }
  18482. /**
  18483. * Returns the node material observer of this render object.
  18484. *
  18485. * @return {NodeMaterialObserver} The node material observer.
  18486. */
  18487. getMonitor() {
  18488. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  18489. }
  18490. /**
  18491. * Returns an array of bind groups of this render object.
  18492. *
  18493. * @return {Array<BindGroup>} The bindings.
  18494. */
  18495. getBindings() {
  18496. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  18497. }
  18498. /**
  18499. * Returns a binding group by group name of this render object.
  18500. *
  18501. * @param {string} name - The name of the binding group.
  18502. * @return {?BindGroup} The bindings.
  18503. */
  18504. getBindingGroup( name ) {
  18505. for ( const bindingGroup of this.getBindings() ) {
  18506. if ( bindingGroup.name === name ) {
  18507. return bindingGroup;
  18508. }
  18509. }
  18510. }
  18511. /**
  18512. * Returns the index of the render object's geometry.
  18513. *
  18514. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  18515. */
  18516. getIndex() {
  18517. return this._geometries.getIndex( this );
  18518. }
  18519. /**
  18520. * Returns the indirect buffer attribute.
  18521. *
  18522. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  18523. */
  18524. getIndirect() {
  18525. return this._geometries.getIndirect( this );
  18526. }
  18527. /**
  18528. * Returns an array that acts as a key for identifying the render object in a chain map.
  18529. *
  18530. * @return {Array<Object>} An array with object references.
  18531. */
  18532. getChainArray() {
  18533. return [ this.object, this.material, this.context, this.lightsNode ];
  18534. }
  18535. /**
  18536. * This method is used when the geometry of a 3D object has been exchanged and the
  18537. * respective render object now requires an update.
  18538. *
  18539. * @param {BufferGeometry} geometry - The geometry to set.
  18540. */
  18541. setGeometry( geometry ) {
  18542. this.geometry = geometry;
  18543. this.attributes = null;
  18544. }
  18545. /**
  18546. * Returns the buffer attributes of the render object. The returned array holds
  18547. * attribute definitions on geometry and node level.
  18548. *
  18549. * @return {Array<BufferAttribute>} An array with buffer attributes.
  18550. */
  18551. getAttributes() {
  18552. if ( this.attributes !== null ) return this.attributes;
  18553. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  18554. const geometry = this.geometry;
  18555. const attributes = [];
  18556. const vertexBuffers = new Set();
  18557. for ( const nodeAttribute of nodeAttributes ) {
  18558. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  18559. if ( attribute === undefined ) continue;
  18560. attributes.push( attribute );
  18561. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18562. vertexBuffers.add( bufferAttribute );
  18563. }
  18564. this.attributes = attributes;
  18565. this.vertexBuffers = Array.from( vertexBuffers.values() );
  18566. return attributes;
  18567. }
  18568. /**
  18569. * Returns the vertex buffers of the render object.
  18570. *
  18571. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  18572. */
  18573. getVertexBuffers() {
  18574. if ( this.vertexBuffers === null ) this.getAttributes();
  18575. return this.vertexBuffers;
  18576. }
  18577. /**
  18578. * Returns the draw parameters for the render object.
  18579. *
  18580. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  18581. */
  18582. getDrawParameters() {
  18583. const { object, material, geometry, group, drawRange } = this;
  18584. const drawParams = this.drawParams || ( this.drawParams = {
  18585. vertexCount: 0,
  18586. firstVertex: 0,
  18587. instanceCount: 0,
  18588. firstInstance: 0
  18589. } );
  18590. const index = this.getIndex();
  18591. const hasIndex = ( index !== null );
  18592. let instanceCount = 1;
  18593. if ( geometry.isInstancedBufferGeometry === true ) {
  18594. instanceCount = geometry.instanceCount;
  18595. } else if ( object.count !== undefined ) {
  18596. instanceCount = Math.max( 0, object.count );
  18597. }
  18598. if ( instanceCount === 0 ) return null;
  18599. drawParams.instanceCount = instanceCount;
  18600. if ( object.isBatchedMesh === true ) return drawParams;
  18601. let rangeFactor = 1;
  18602. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  18603. rangeFactor = 2;
  18604. }
  18605. let firstVertex = drawRange.start * rangeFactor;
  18606. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  18607. if ( group !== null ) {
  18608. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  18609. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  18610. }
  18611. const position = geometry.attributes.position;
  18612. let itemCount = Infinity;
  18613. if ( hasIndex ) {
  18614. itemCount = index.count;
  18615. } else if ( position !== undefined && position !== null ) {
  18616. itemCount = position.count;
  18617. }
  18618. firstVertex = Math.max( firstVertex, 0 );
  18619. lastVertex = Math.min( lastVertex, itemCount );
  18620. const count = lastVertex - firstVertex;
  18621. if ( count < 0 || count === Infinity ) return null;
  18622. drawParams.vertexCount = count;
  18623. drawParams.firstVertex = firstVertex;
  18624. return drawParams;
  18625. }
  18626. /**
  18627. * Returns the render object's geometry cache key.
  18628. *
  18629. * The geometry cache key is part of the material cache key.
  18630. *
  18631. * @return {string} The geometry cache key.
  18632. */
  18633. getGeometryCacheKey() {
  18634. const { geometry } = this;
  18635. let cacheKey = '';
  18636. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  18637. const attribute = geometry.attributes[ name ];
  18638. cacheKey += name + ',';
  18639. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  18640. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  18641. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  18642. if ( attribute.normalized ) cacheKey += 'n,';
  18643. }
  18644. // structural equality isn't sufficient for morph targets since the
  18645. // data are maintained in textures. only if the targets are all equal
  18646. // the texture and thus the instance of `MorphNode` can be shared.
  18647. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  18648. const targets = geometry.morphAttributes[ name ];
  18649. cacheKey += 'morph-' + name + ',';
  18650. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  18651. const attribute = targets[ i ];
  18652. cacheKey += attribute.id + ',';
  18653. }
  18654. }
  18655. if ( geometry.index ) {
  18656. cacheKey += 'index,';
  18657. }
  18658. return cacheKey;
  18659. }
  18660. /**
  18661. * Returns the render object's material cache key.
  18662. *
  18663. * The material cache key is part of the render object cache key.
  18664. *
  18665. * @return {number} The material cache key.
  18666. */
  18667. getMaterialCacheKey() {
  18668. const { object, material } = this;
  18669. let cacheKey = material.customProgramCacheKey();
  18670. for ( const property of getKeys( material ) ) {
  18671. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  18672. const value = material[ property ];
  18673. let valueKey;
  18674. if ( value !== null ) {
  18675. // some material values require a formatting
  18676. const type = typeof value;
  18677. if ( type === 'number' ) {
  18678. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  18679. } else if ( type === 'object' ) {
  18680. valueKey = '{';
  18681. if ( value.isTexture ) {
  18682. valueKey += value.mapping;
  18683. }
  18684. valueKey += '}';
  18685. } else {
  18686. valueKey = String( value );
  18687. }
  18688. } else {
  18689. valueKey = String( value );
  18690. }
  18691. cacheKey += /*property + ':' +*/ valueKey + ',';
  18692. }
  18693. cacheKey += this.clippingContextCacheKey + ',';
  18694. if ( object.geometry ) {
  18695. cacheKey += this.getGeometryCacheKey();
  18696. }
  18697. if ( object.skeleton ) {
  18698. cacheKey += object.skeleton.bones.length + ',';
  18699. }
  18700. if ( object.isBatchedMesh ) {
  18701. cacheKey += object._matricesTexture.uuid + ',';
  18702. if ( object._colorsTexture !== null ) {
  18703. cacheKey += object._colorsTexture.uuid + ',';
  18704. }
  18705. }
  18706. if ( object.count > 1 ) {
  18707. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  18708. cacheKey += object.uuid + ',';
  18709. }
  18710. cacheKey += object.receiveShadow + ',';
  18711. return hashString( cacheKey );
  18712. }
  18713. /**
  18714. * Whether the geometry requires an update or not.
  18715. *
  18716. * @type {boolean}
  18717. * @readonly
  18718. */
  18719. get needsGeometryUpdate() {
  18720. return this.geometry.id !== this.object.geometry.id;
  18721. }
  18722. /**
  18723. * Whether the render object requires an update or not.
  18724. *
  18725. * Note: There are two distinct places where render objects are checked for an update.
  18726. *
  18727. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  18728. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  18729. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  18730. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  18731. * a need for a refresh due to material, geometry or object related value changes.
  18732. *
  18733. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  18734. * that performs the 'needsUpdate' check.
  18735. *
  18736. * @type {boolean}
  18737. * @readonly
  18738. */
  18739. get needsUpdate() {
  18740. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  18741. }
  18742. /**
  18743. * Returns the dynamic cache key which represents a key that is computed per draw command.
  18744. *
  18745. * @return {number} The cache key.
  18746. */
  18747. getDynamicCacheKey() {
  18748. let cacheKey = 0;
  18749. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  18750. // the renderer is inside a shadow pass.
  18751. if ( this.material.isShadowPassMaterial !== true ) {
  18752. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  18753. }
  18754. if ( this.camera.isArrayCamera ) {
  18755. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  18756. }
  18757. if ( this.object.receiveShadow ) {
  18758. cacheKey = hash$1( cacheKey, 1 );
  18759. }
  18760. return cacheKey;
  18761. }
  18762. /**
  18763. * Returns the render object's cache key.
  18764. *
  18765. * @return {number} The cache key.
  18766. */
  18767. getCacheKey() {
  18768. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  18769. }
  18770. /**
  18771. * Frees internal resources.
  18772. */
  18773. dispose() {
  18774. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  18775. this.onDispose();
  18776. }
  18777. }
  18778. const _chainKeys$5 = [];
  18779. /**
  18780. * This module manages the render objects of the renderer.
  18781. *
  18782. * @private
  18783. */
  18784. class RenderObjects {
  18785. /**
  18786. * Constructs a new render object management component.
  18787. *
  18788. * @param {Renderer} renderer - The renderer.
  18789. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18790. * @param {Geometries} geometries - Renderer component for managing geometries.
  18791. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  18792. * @param {Bindings} bindings - Renderer component for managing bindings.
  18793. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18794. */
  18795. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  18796. /**
  18797. * The renderer.
  18798. *
  18799. * @type {Renderer}
  18800. */
  18801. this.renderer = renderer;
  18802. /**
  18803. * Renderer component for managing nodes related logic.
  18804. *
  18805. * @type {Nodes}
  18806. */
  18807. this.nodes = nodes;
  18808. /**
  18809. * Renderer component for managing geometries.
  18810. *
  18811. * @type {Geometries}
  18812. */
  18813. this.geometries = geometries;
  18814. /**
  18815. * Renderer component for managing pipelines.
  18816. *
  18817. * @type {Pipelines}
  18818. */
  18819. this.pipelines = pipelines;
  18820. /**
  18821. * Renderer component for managing bindings.
  18822. *
  18823. * @type {Bindings}
  18824. */
  18825. this.bindings = bindings;
  18826. /**
  18827. * Renderer component for managing metrics and monitoring data.
  18828. *
  18829. * @type {Info}
  18830. */
  18831. this.info = info;
  18832. /**
  18833. * A dictionary that manages render contexts in chain maps
  18834. * for each pass ID.
  18835. *
  18836. * @type {Object<string,ChainMap>}
  18837. */
  18838. this.chainMaps = {};
  18839. }
  18840. /**
  18841. * Returns a render object for the given object and state data.
  18842. *
  18843. * @param {Object3D} object - The 3D object.
  18844. * @param {Material} material - The 3D object's material.
  18845. * @param {Scene} scene - The scene the 3D object belongs to.
  18846. * @param {Camera} camera - The camera the 3D object should be rendered with.
  18847. * @param {LightsNode} lightsNode - The lights node.
  18848. * @param {RenderContext} renderContext - The render context.
  18849. * @param {ClippingContext} clippingContext - The clipping context.
  18850. * @param {string} [passId] - An optional ID for identifying the pass.
  18851. * @return {RenderObject} The render object.
  18852. */
  18853. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  18854. const chainMap = this.getChainMap( passId );
  18855. // reuse chainArray
  18856. _chainKeys$5[ 0 ] = object;
  18857. _chainKeys$5[ 1 ] = material;
  18858. _chainKeys$5[ 2 ] = renderContext;
  18859. _chainKeys$5[ 3 ] = lightsNode;
  18860. let renderObject = chainMap.get( _chainKeys$5 );
  18861. if ( renderObject === undefined ) {
  18862. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  18863. chainMap.set( _chainKeys$5, renderObject );
  18864. } else {
  18865. renderObject.updateClipping( clippingContext );
  18866. if ( renderObject.needsGeometryUpdate ) {
  18867. renderObject.setGeometry( object.geometry );
  18868. }
  18869. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  18870. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  18871. renderObject.dispose();
  18872. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  18873. } else {
  18874. renderObject.version = material.version;
  18875. }
  18876. }
  18877. }
  18878. _chainKeys$5.length = 0;
  18879. return renderObject;
  18880. }
  18881. /**
  18882. * Returns a chain map for the given pass ID.
  18883. *
  18884. * @param {string} [passId='default'] - The pass ID.
  18885. * @return {ChainMap} The chain map.
  18886. */
  18887. getChainMap( passId = 'default' ) {
  18888. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  18889. }
  18890. /**
  18891. * Frees internal resources.
  18892. */
  18893. dispose() {
  18894. this.chainMaps = {};
  18895. }
  18896. /**
  18897. * Factory method for creating render objects with the given list of parameters.
  18898. *
  18899. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18900. * @param {Geometries} geometries - Renderer component for managing geometries.
  18901. * @param {Renderer} renderer - The renderer.
  18902. * @param {Object3D} object - The 3D object.
  18903. * @param {Material} material - The object's material.
  18904. * @param {Scene} scene - The scene the 3D object belongs to.
  18905. * @param {Camera} camera - The camera the object should be rendered with.
  18906. * @param {LightsNode} lightsNode - The lights node.
  18907. * @param {RenderContext} renderContext - The render context.
  18908. * @param {ClippingContext} clippingContext - The clipping context.
  18909. * @param {string} [passId] - An optional ID for identifying the pass.
  18910. * @return {RenderObject} The render object.
  18911. */
  18912. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  18913. const chainMap = this.getChainMap( passId );
  18914. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  18915. renderObject.onDispose = () => {
  18916. this.pipelines.delete( renderObject );
  18917. this.bindings.delete( renderObject );
  18918. this.nodes.delete( renderObject );
  18919. chainMap.delete( renderObject.getChainArray() );
  18920. };
  18921. return renderObject;
  18922. }
  18923. }
  18924. /**
  18925. * Data structure for the renderer. It is intended to manage
  18926. * data of objects in dictionaries.
  18927. *
  18928. * @private
  18929. */
  18930. class DataMap {
  18931. /**
  18932. * Constructs a new data map.
  18933. */
  18934. constructor() {
  18935. /**
  18936. * `DataMap` internally uses a weak map
  18937. * to manage its data.
  18938. *
  18939. * @type {WeakMap}
  18940. */
  18941. this.data = new WeakMap();
  18942. }
  18943. /**
  18944. * Returns the dictionary for the given object.
  18945. *
  18946. * @param {Object} object - The object.
  18947. * @return {Object} The dictionary.
  18948. */
  18949. get( object ) {
  18950. let map = this.data.get( object );
  18951. if ( map === undefined ) {
  18952. map = {};
  18953. this.data.set( object, map );
  18954. }
  18955. return map;
  18956. }
  18957. /**
  18958. * Deletes the dictionary for the given object.
  18959. *
  18960. * @param {Object} object - The object.
  18961. * @return {?Object} The deleted dictionary.
  18962. */
  18963. delete( object ) {
  18964. let map = null;
  18965. if ( this.data.has( object ) ) {
  18966. map = this.data.get( object );
  18967. this.data.delete( object );
  18968. }
  18969. return map;
  18970. }
  18971. /**
  18972. * Returns `true` if the given object has a dictionary defined.
  18973. *
  18974. * @param {Object} object - The object to test.
  18975. * @return {boolean} Whether a dictionary is defined or not.
  18976. */
  18977. has( object ) {
  18978. return this.data.has( object );
  18979. }
  18980. /**
  18981. * Frees internal resources.
  18982. */
  18983. dispose() {
  18984. this.data = new WeakMap();
  18985. }
  18986. }
  18987. const AttributeType = {
  18988. VERTEX: 1,
  18989. INDEX: 2,
  18990. STORAGE: 3,
  18991. INDIRECT: 4
  18992. };
  18993. // size of a chunk in bytes (STD140 layout)
  18994. const GPU_CHUNK_BYTES = 16;
  18995. // @TODO: Move to src/constants.js
  18996. const BlendColorFactor = 211;
  18997. const OneMinusBlendColorFactor = 212;
  18998. /**
  18999. * This renderer module manages geometry attributes.
  19000. *
  19001. * @private
  19002. * @augments DataMap
  19003. */
  19004. class Attributes extends DataMap {
  19005. /**
  19006. * Constructs a new attribute management component.
  19007. *
  19008. * @param {Backend} backend - The renderer's backend.
  19009. */
  19010. constructor( backend ) {
  19011. super();
  19012. /**
  19013. * The renderer's backend.
  19014. *
  19015. * @type {Backend}
  19016. */
  19017. this.backend = backend;
  19018. }
  19019. /**
  19020. * Deletes the data for the given attribute.
  19021. *
  19022. * @param {BufferAttribute} attribute - The attribute.
  19023. * @return {Object|null} The deleted attribute data.
  19024. */
  19025. delete( attribute ) {
  19026. const attributeData = super.delete( attribute );
  19027. if ( attributeData !== null ) {
  19028. this.backend.destroyAttribute( attribute );
  19029. }
  19030. return attributeData;
  19031. }
  19032. /**
  19033. * Updates the given attribute. This method creates attribute buffers
  19034. * for new attributes and updates data for existing ones.
  19035. *
  19036. * @param {BufferAttribute} attribute - The attribute to update.
  19037. * @param {number} type - The attribute type.
  19038. */
  19039. update( attribute, type ) {
  19040. const data = this.get( attribute );
  19041. if ( data.version === undefined ) {
  19042. if ( type === AttributeType.VERTEX ) {
  19043. this.backend.createAttribute( attribute );
  19044. } else if ( type === AttributeType.INDEX ) {
  19045. this.backend.createIndexAttribute( attribute );
  19046. } else if ( type === AttributeType.STORAGE ) {
  19047. this.backend.createStorageAttribute( attribute );
  19048. } else if ( type === AttributeType.INDIRECT ) {
  19049. this.backend.createIndirectStorageAttribute( attribute );
  19050. }
  19051. data.version = this._getBufferAttribute( attribute ).version;
  19052. } else {
  19053. const bufferAttribute = this._getBufferAttribute( attribute );
  19054. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  19055. this.backend.updateAttribute( attribute );
  19056. data.version = bufferAttribute.version;
  19057. }
  19058. }
  19059. }
  19060. /**
  19061. * Utility method for handling interleaved buffer attributes correctly.
  19062. * To process them, their `InterleavedBuffer` is returned.
  19063. *
  19064. * @param {BufferAttribute} attribute - The attribute.
  19065. * @return {BufferAttribute|InterleavedBuffer}
  19066. */
  19067. _getBufferAttribute( attribute ) {
  19068. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  19069. return attribute;
  19070. }
  19071. }
  19072. /**
  19073. * Returns the wireframe version for the given geometry.
  19074. *
  19075. * @private
  19076. * @function
  19077. * @param {BufferGeometry} geometry - The geometry.
  19078. * @return {number} The version.
  19079. */
  19080. function getWireframeVersion( geometry ) {
  19081. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  19082. }
  19083. /**
  19084. * Returns a wireframe index attribute for the given geometry.
  19085. *
  19086. * @private
  19087. * @function
  19088. * @param {BufferGeometry} geometry - The geometry.
  19089. * @return {BufferAttribute} The wireframe index attribute.
  19090. */
  19091. function getWireframeIndex( geometry ) {
  19092. const indices = [];
  19093. const geometryIndex = geometry.index;
  19094. const geometryPosition = geometry.attributes.position;
  19095. if ( geometryIndex !== null ) {
  19096. const array = geometryIndex.array;
  19097. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  19098. const a = array[ i + 0 ];
  19099. const b = array[ i + 1 ];
  19100. const c = array[ i + 2 ];
  19101. indices.push( a, b, b, c, c, a );
  19102. }
  19103. } else {
  19104. const array = geometryPosition.array;
  19105. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  19106. const a = i + 0;
  19107. const b = i + 1;
  19108. const c = i + 2;
  19109. indices.push( a, b, b, c, c, a );
  19110. }
  19111. }
  19112. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  19113. attribute.version = getWireframeVersion( geometry );
  19114. return attribute;
  19115. }
  19116. /**
  19117. * This renderer module manages geometries.
  19118. *
  19119. * @private
  19120. * @augments DataMap
  19121. */
  19122. class Geometries extends DataMap {
  19123. /**
  19124. * Constructs a new geometry management component.
  19125. *
  19126. * @param {Attributes} attributes - Renderer component for managing attributes.
  19127. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19128. */
  19129. constructor( attributes, info ) {
  19130. super();
  19131. /**
  19132. * Renderer component for managing attributes.
  19133. *
  19134. * @type {Attributes}
  19135. */
  19136. this.attributes = attributes;
  19137. /**
  19138. * Renderer component for managing metrics and monitoring data.
  19139. *
  19140. * @type {Info}
  19141. */
  19142. this.info = info;
  19143. /**
  19144. * Weak Map for managing attributes for wireframe rendering.
  19145. *
  19146. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  19147. */
  19148. this.wireframes = new WeakMap();
  19149. /**
  19150. * This Weak Map is used to make sure buffer attributes are
  19151. * updated only once per render call.
  19152. *
  19153. * @type {WeakMap<BufferAttribute,number>}
  19154. */
  19155. this.attributeCall = new WeakMap();
  19156. }
  19157. /**
  19158. * Returns `true` if the given render object has an initialized geometry.
  19159. *
  19160. * @param {RenderObject} renderObject - The render object.
  19161. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  19162. */
  19163. has( renderObject ) {
  19164. const geometry = renderObject.geometry;
  19165. return super.has( geometry ) && this.get( geometry ).initialized === true;
  19166. }
  19167. /**
  19168. * Prepares the geometry of the given render object for rendering.
  19169. *
  19170. * @param {RenderObject} renderObject - The render object.
  19171. */
  19172. updateForRender( renderObject ) {
  19173. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  19174. this.updateAttributes( renderObject );
  19175. }
  19176. /**
  19177. * Initializes the geometry of the given render object.
  19178. *
  19179. * @param {RenderObject} renderObject - The render object.
  19180. */
  19181. initGeometry( renderObject ) {
  19182. const geometry = renderObject.geometry;
  19183. const geometryData = this.get( geometry );
  19184. geometryData.initialized = true;
  19185. this.info.memory.geometries ++;
  19186. const onDispose = () => {
  19187. this.info.memory.geometries --;
  19188. const index = geometry.index;
  19189. const geometryAttributes = renderObject.getAttributes();
  19190. if ( index !== null ) {
  19191. this.attributes.delete( index );
  19192. }
  19193. for ( const geometryAttribute of geometryAttributes ) {
  19194. this.attributes.delete( geometryAttribute );
  19195. }
  19196. const wireframeAttribute = this.wireframes.get( geometry );
  19197. if ( wireframeAttribute !== undefined ) {
  19198. this.attributes.delete( wireframeAttribute );
  19199. }
  19200. geometry.removeEventListener( 'dispose', onDispose );
  19201. };
  19202. geometry.addEventListener( 'dispose', onDispose );
  19203. }
  19204. /**
  19205. * Updates the geometry attributes of the given render object.
  19206. *
  19207. * @param {RenderObject} renderObject - The render object.
  19208. */
  19209. updateAttributes( renderObject ) {
  19210. // attributes
  19211. const attributes = renderObject.getAttributes();
  19212. for ( const attribute of attributes ) {
  19213. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  19214. this.updateAttribute( attribute, AttributeType.STORAGE );
  19215. } else {
  19216. this.updateAttribute( attribute, AttributeType.VERTEX );
  19217. }
  19218. }
  19219. // indexes
  19220. const index = this.getIndex( renderObject );
  19221. if ( index !== null ) {
  19222. this.updateAttribute( index, AttributeType.INDEX );
  19223. }
  19224. // indirect
  19225. const indirect = renderObject.geometry.indirect;
  19226. if ( indirect !== null ) {
  19227. this.updateAttribute( indirect, AttributeType.INDIRECT );
  19228. }
  19229. }
  19230. /**
  19231. * Updates the given attribute.
  19232. *
  19233. * @param {BufferAttribute} attribute - The attribute to update.
  19234. * @param {number} type - The attribute type.
  19235. */
  19236. updateAttribute( attribute, type ) {
  19237. const callId = this.info.render.calls;
  19238. if ( ! attribute.isInterleavedBufferAttribute ) {
  19239. if ( this.attributeCall.get( attribute ) !== callId ) {
  19240. this.attributes.update( attribute, type );
  19241. this.attributeCall.set( attribute, callId );
  19242. }
  19243. } else {
  19244. if ( this.attributeCall.get( attribute ) === undefined ) {
  19245. this.attributes.update( attribute, type );
  19246. this.attributeCall.set( attribute, callId );
  19247. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  19248. this.attributes.update( attribute, type );
  19249. this.attributeCall.set( attribute.data, callId );
  19250. this.attributeCall.set( attribute, callId );
  19251. }
  19252. }
  19253. }
  19254. /**
  19255. * Returns the indirect buffer attribute of the given render object.
  19256. *
  19257. * @param {RenderObject} renderObject - The render object.
  19258. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19259. */
  19260. getIndirect( renderObject ) {
  19261. return renderObject.geometry.indirect;
  19262. }
  19263. /**
  19264. * Returns the index of the given render object's geometry. This is implemented
  19265. * in a method to return a wireframe index if necessary.
  19266. *
  19267. * @param {RenderObject} renderObject - The render object.
  19268. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19269. */
  19270. getIndex( renderObject ) {
  19271. const { geometry, material } = renderObject;
  19272. let index = geometry.index;
  19273. if ( material.wireframe === true ) {
  19274. const wireframes = this.wireframes;
  19275. let wireframeAttribute = wireframes.get( geometry );
  19276. if ( wireframeAttribute === undefined ) {
  19277. wireframeAttribute = getWireframeIndex( geometry );
  19278. wireframes.set( geometry, wireframeAttribute );
  19279. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  19280. this.attributes.delete( wireframeAttribute );
  19281. wireframeAttribute = getWireframeIndex( geometry );
  19282. wireframes.set( geometry, wireframeAttribute );
  19283. }
  19284. index = wireframeAttribute;
  19285. }
  19286. return index;
  19287. }
  19288. }
  19289. /**
  19290. * This renderer module provides a series of statistical information
  19291. * about the GPU memory and the rendering process. Useful for debugging
  19292. * and monitoring.
  19293. */
  19294. class Info {
  19295. /**
  19296. * Constructs a new info component.
  19297. */
  19298. constructor() {
  19299. /**
  19300. * Whether frame related metrics should automatically
  19301. * be resetted or not. This property should be set to `false`
  19302. * by apps which manage their own animation loop. They must
  19303. * then call `renderer.info.reset()` once per frame manually.
  19304. *
  19305. * @type {boolean}
  19306. * @default true
  19307. */
  19308. this.autoReset = true;
  19309. /**
  19310. * The current frame ID. This ID is managed
  19311. * by `NodeFrame`.
  19312. *
  19313. * @type {number}
  19314. * @readonly
  19315. * @default 0
  19316. */
  19317. this.frame = 0;
  19318. /**
  19319. * The number of render calls since the
  19320. * app has been started.
  19321. *
  19322. * @type {number}
  19323. * @readonly
  19324. * @default 0
  19325. */
  19326. this.calls = 0;
  19327. /**
  19328. * Render related metrics.
  19329. *
  19330. * @type {Object}
  19331. * @readonly
  19332. * @property {number} calls - The number of render calls since the app has been started.
  19333. * @property {number} frameCalls - The number of render calls of the current frame.
  19334. * @property {number} drawCalls - The number of draw calls of the current frame.
  19335. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  19336. * @property {number} points - The number of rendered point primitives of the current frame.
  19337. * @property {number} lines - The number of rendered line primitives of the current frame.
  19338. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  19339. */
  19340. this.render = {
  19341. calls: 0,
  19342. frameCalls: 0,
  19343. drawCalls: 0,
  19344. triangles: 0,
  19345. points: 0,
  19346. lines: 0,
  19347. timestamp: 0,
  19348. };
  19349. /**
  19350. * Compute related metrics.
  19351. *
  19352. * @type {Object}
  19353. * @readonly
  19354. * @property {number} calls - The number of compute calls since the app has been started.
  19355. * @property {number} frameCalls - The number of compute calls of the current frame.
  19356. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  19357. */
  19358. this.compute = {
  19359. calls: 0,
  19360. frameCalls: 0,
  19361. timestamp: 0
  19362. };
  19363. /**
  19364. * Memory related metrics.
  19365. *
  19366. * @type {Object}
  19367. * @readonly
  19368. * @property {number} geometries - The number of active geometries.
  19369. * @property {number} frameCalls - The number of active textures.
  19370. */
  19371. this.memory = {
  19372. geometries: 0,
  19373. textures: 0
  19374. };
  19375. }
  19376. /**
  19377. * This method should be executed per draw call and updates the corresponding metrics.
  19378. *
  19379. * @param {Object3D} object - The 3D object that is going to be rendered.
  19380. * @param {number} count - The vertex or index count.
  19381. * @param {number} instanceCount - The instance count.
  19382. */
  19383. update( object, count, instanceCount ) {
  19384. this.render.drawCalls ++;
  19385. if ( object.isMesh || object.isSprite ) {
  19386. this.render.triangles += instanceCount * ( count / 3 );
  19387. } else if ( object.isPoints ) {
  19388. this.render.points += instanceCount * count;
  19389. } else if ( object.isLineSegments ) {
  19390. this.render.lines += instanceCount * ( count / 2 );
  19391. } else if ( object.isLine ) {
  19392. this.render.lines += instanceCount * ( count - 1 );
  19393. } else {
  19394. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  19395. }
  19396. }
  19397. /**
  19398. * Resets frame related metrics.
  19399. */
  19400. reset() {
  19401. this.render.drawCalls = 0;
  19402. this.render.frameCalls = 0;
  19403. this.compute.frameCalls = 0;
  19404. this.render.triangles = 0;
  19405. this.render.points = 0;
  19406. this.render.lines = 0;
  19407. }
  19408. /**
  19409. * Performs a complete reset of the object.
  19410. */
  19411. dispose() {
  19412. this.reset();
  19413. this.calls = 0;
  19414. this.render.calls = 0;
  19415. this.compute.calls = 0;
  19416. this.render.timestamp = 0;
  19417. this.compute.timestamp = 0;
  19418. this.memory.geometries = 0;
  19419. this.memory.textures = 0;
  19420. }
  19421. }
  19422. /**
  19423. * Abstract class for representing pipelines.
  19424. *
  19425. * @private
  19426. * @abstract
  19427. */
  19428. class Pipeline {
  19429. /**
  19430. * Constructs a new pipeline.
  19431. *
  19432. * @param {string} cacheKey - The pipeline's cache key.
  19433. */
  19434. constructor( cacheKey ) {
  19435. /**
  19436. * The pipeline's cache key.
  19437. *
  19438. * @type {string}
  19439. */
  19440. this.cacheKey = cacheKey;
  19441. /**
  19442. * How often the pipeline is currently in use.
  19443. *
  19444. * @type {number}
  19445. * @default 0
  19446. */
  19447. this.usedTimes = 0;
  19448. }
  19449. }
  19450. /**
  19451. * Class for representing render pipelines.
  19452. *
  19453. * @private
  19454. * @augments Pipeline
  19455. */
  19456. class RenderPipeline extends Pipeline {
  19457. /**
  19458. * Constructs a new render pipeline.
  19459. *
  19460. * @param {string} cacheKey - The pipeline's cache key.
  19461. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  19462. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  19463. */
  19464. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  19465. super( cacheKey );
  19466. /**
  19467. * The pipeline's vertex shader.
  19468. *
  19469. * @type {ProgrammableStage}
  19470. */
  19471. this.vertexProgram = vertexProgram;
  19472. /**
  19473. * The pipeline's fragment shader.
  19474. *
  19475. * @type {ProgrammableStage}
  19476. */
  19477. this.fragmentProgram = fragmentProgram;
  19478. }
  19479. }
  19480. /**
  19481. * Class for representing compute pipelines.
  19482. *
  19483. * @private
  19484. * @augments Pipeline
  19485. */
  19486. class ComputePipeline extends Pipeline {
  19487. /**
  19488. * Constructs a new render pipeline.
  19489. *
  19490. * @param {string} cacheKey - The pipeline's cache key.
  19491. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  19492. */
  19493. constructor( cacheKey, computeProgram ) {
  19494. super( cacheKey );
  19495. /**
  19496. * The pipeline's compute shader.
  19497. *
  19498. * @type {ProgrammableStage}
  19499. */
  19500. this.computeProgram = computeProgram;
  19501. /**
  19502. * This flag can be used for type testing.
  19503. *
  19504. * @type {boolean}
  19505. * @readonly
  19506. * @default true
  19507. */
  19508. this.isComputePipeline = true;
  19509. }
  19510. }
  19511. let _id$8 = 0;
  19512. /**
  19513. * Class for representing programmable stages which are vertex,
  19514. * fragment or compute shaders. Unlike fixed-function states (like blending),
  19515. * they represent the programmable part of a pipeline.
  19516. *
  19517. * @private
  19518. */
  19519. class ProgrammableStage {
  19520. /**
  19521. * Constructs a new programmable stage.
  19522. *
  19523. * @param {string} code - The shader code.
  19524. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  19525. * @param {string} name - The name of the shader.
  19526. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19527. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19528. */
  19529. constructor( code, stage, name, transforms = null, attributes = null ) {
  19530. /**
  19531. * The id of the programmable stage.
  19532. *
  19533. * @type {number}
  19534. */
  19535. this.id = _id$8 ++;
  19536. /**
  19537. * The shader code.
  19538. *
  19539. * @type {string}
  19540. */
  19541. this.code = code;
  19542. /**
  19543. * The type of stage.
  19544. *
  19545. * @type {string}
  19546. */
  19547. this.stage = stage;
  19548. /**
  19549. * The name of the stage.
  19550. * This is used for debugging purposes.
  19551. *
  19552. * @type {string}
  19553. */
  19554. this.name = name;
  19555. /**
  19556. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19557. *
  19558. * @type {?Array<Object>}
  19559. */
  19560. this.transforms = transforms;
  19561. /**
  19562. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19563. *
  19564. * @type {?Array<Object>}
  19565. */
  19566. this.attributes = attributes;
  19567. /**
  19568. * How often the programmable stage is currently in use.
  19569. *
  19570. * @type {number}
  19571. * @default 0
  19572. */
  19573. this.usedTimes = 0;
  19574. }
  19575. }
  19576. /**
  19577. * This renderer module manages the pipelines of the renderer.
  19578. *
  19579. * @private
  19580. * @augments DataMap
  19581. */
  19582. class Pipelines extends DataMap {
  19583. /**
  19584. * Constructs a new pipeline management component.
  19585. *
  19586. * @param {Backend} backend - The renderer's backend.
  19587. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19588. */
  19589. constructor( backend, nodes ) {
  19590. super();
  19591. /**
  19592. * The renderer's backend.
  19593. *
  19594. * @type {Backend}
  19595. */
  19596. this.backend = backend;
  19597. /**
  19598. * Renderer component for managing nodes related logic.
  19599. *
  19600. * @type {Nodes}
  19601. */
  19602. this.nodes = nodes;
  19603. /**
  19604. * A references to the bindings management component.
  19605. * This reference will be set inside the `Bindings`
  19606. * constructor.
  19607. *
  19608. * @type {?Bindings}
  19609. * @default null
  19610. */
  19611. this.bindings = null;
  19612. /**
  19613. * Internal cache for maintaining pipelines.
  19614. * The key of the map is a cache key, the value the pipeline.
  19615. *
  19616. * @type {Map<string,Pipeline>}
  19617. */
  19618. this.caches = new Map();
  19619. /**
  19620. * This dictionary maintains for each shader stage type (vertex,
  19621. * fragment and compute) the programmable stage objects which
  19622. * represent the actual shader code.
  19623. *
  19624. * @type {Object<string,Map>}
  19625. */
  19626. this.programs = {
  19627. vertex: new Map(),
  19628. fragment: new Map(),
  19629. compute: new Map()
  19630. };
  19631. }
  19632. /**
  19633. * Returns a compute pipeline for the given compute node.
  19634. *
  19635. * @param {Node} computeNode - The compute node.
  19636. * @param {Array<BindGroup>} bindings - The bindings.
  19637. * @return {ComputePipeline} The compute pipeline.
  19638. */
  19639. getForCompute( computeNode, bindings ) {
  19640. const { backend } = this;
  19641. const data = this.get( computeNode );
  19642. if ( this._needsComputeUpdate( computeNode ) ) {
  19643. const previousPipeline = data.pipeline;
  19644. if ( previousPipeline ) {
  19645. previousPipeline.usedTimes --;
  19646. previousPipeline.computeProgram.usedTimes --;
  19647. }
  19648. // get shader
  19649. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  19650. // programmable stage
  19651. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  19652. if ( stageCompute === undefined ) {
  19653. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  19654. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  19655. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  19656. backend.createProgram( stageCompute );
  19657. }
  19658. // determine compute pipeline
  19659. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  19660. let pipeline = this.caches.get( cacheKey );
  19661. if ( pipeline === undefined ) {
  19662. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  19663. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  19664. }
  19665. // keep track of all used times
  19666. pipeline.usedTimes ++;
  19667. stageCompute.usedTimes ++;
  19668. //
  19669. data.version = computeNode.version;
  19670. data.pipeline = pipeline;
  19671. }
  19672. return data.pipeline;
  19673. }
  19674. /**
  19675. * Returns a render pipeline for the given render object.
  19676. *
  19677. * @param {RenderObject} renderObject - The render object.
  19678. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  19679. * @return {RenderPipeline} The render pipeline.
  19680. */
  19681. getForRender( renderObject, promises = null ) {
  19682. const { backend } = this;
  19683. const data = this.get( renderObject );
  19684. if ( this._needsRenderUpdate( renderObject ) ) {
  19685. const previousPipeline = data.pipeline;
  19686. if ( previousPipeline ) {
  19687. previousPipeline.usedTimes --;
  19688. previousPipeline.vertexProgram.usedTimes --;
  19689. previousPipeline.fragmentProgram.usedTimes --;
  19690. }
  19691. // get shader
  19692. const nodeBuilderState = renderObject.getNodeBuilderState();
  19693. const name = renderObject.material ? renderObject.material.name : '';
  19694. // programmable stages
  19695. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  19696. if ( stageVertex === undefined ) {
  19697. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  19698. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  19699. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  19700. backend.createProgram( stageVertex );
  19701. }
  19702. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  19703. if ( stageFragment === undefined ) {
  19704. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  19705. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  19706. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  19707. backend.createProgram( stageFragment );
  19708. }
  19709. // determine render pipeline
  19710. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  19711. let pipeline = this.caches.get( cacheKey );
  19712. if ( pipeline === undefined ) {
  19713. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  19714. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  19715. } else {
  19716. renderObject.pipeline = pipeline;
  19717. }
  19718. // keep track of all used times
  19719. pipeline.usedTimes ++;
  19720. stageVertex.usedTimes ++;
  19721. stageFragment.usedTimes ++;
  19722. //
  19723. data.pipeline = pipeline;
  19724. }
  19725. return data.pipeline;
  19726. }
  19727. /**
  19728. * Deletes the pipeline for the given render object.
  19729. *
  19730. * @param {RenderObject} object - The render object.
  19731. * @return {?Object} The deleted dictionary.
  19732. */
  19733. delete( object ) {
  19734. const pipeline = this.get( object ).pipeline;
  19735. if ( pipeline ) {
  19736. // pipeline
  19737. pipeline.usedTimes --;
  19738. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  19739. // programs
  19740. if ( pipeline.isComputePipeline ) {
  19741. pipeline.computeProgram.usedTimes --;
  19742. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  19743. } else {
  19744. pipeline.fragmentProgram.usedTimes --;
  19745. pipeline.vertexProgram.usedTimes --;
  19746. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  19747. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  19748. }
  19749. }
  19750. return super.delete( object );
  19751. }
  19752. /**
  19753. * Frees internal resources.
  19754. */
  19755. dispose() {
  19756. super.dispose();
  19757. this.caches = new Map();
  19758. this.programs = {
  19759. vertex: new Map(),
  19760. fragment: new Map(),
  19761. compute: new Map()
  19762. };
  19763. }
  19764. /**
  19765. * Updates the pipeline for the given render object.
  19766. *
  19767. * @param {RenderObject} renderObject - The render object.
  19768. */
  19769. updateForRender( renderObject ) {
  19770. this.getForRender( renderObject );
  19771. }
  19772. /**
  19773. * Returns a compute pipeline for the given parameters.
  19774. *
  19775. * @private
  19776. * @param {Node} computeNode - The compute node.
  19777. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  19778. * @param {string} cacheKey - The cache key.
  19779. * @param {Array<BindGroup>} bindings - The bindings.
  19780. * @return {ComputePipeline} The compute pipeline.
  19781. */
  19782. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  19783. // check for existing pipeline
  19784. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  19785. let pipeline = this.caches.get( cacheKey );
  19786. if ( pipeline === undefined ) {
  19787. pipeline = new ComputePipeline( cacheKey, stageCompute );
  19788. this.caches.set( cacheKey, pipeline );
  19789. this.backend.createComputePipeline( pipeline, bindings );
  19790. }
  19791. return pipeline;
  19792. }
  19793. /**
  19794. * Returns a render pipeline for the given parameters.
  19795. *
  19796. * @private
  19797. * @param {RenderObject} renderObject - The render object.
  19798. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  19799. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  19800. * @param {string} cacheKey - The cache key.
  19801. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  19802. * @return {ComputePipeline} The compute pipeline.
  19803. */
  19804. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  19805. // check for existing pipeline
  19806. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  19807. let pipeline = this.caches.get( cacheKey );
  19808. if ( pipeline === undefined ) {
  19809. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  19810. this.caches.set( cacheKey, pipeline );
  19811. renderObject.pipeline = pipeline;
  19812. // The `promises` array is `null` by default and only set to an empty array when
  19813. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  19814. // pending promises that resolve when the render pipelines are ready for rendering.
  19815. this.backend.createRenderPipeline( renderObject, promises );
  19816. }
  19817. return pipeline;
  19818. }
  19819. /**
  19820. * Computes a cache key representing a compute pipeline.
  19821. *
  19822. * @private
  19823. * @param {Node} computeNode - The compute node.
  19824. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  19825. * @return {string} The cache key.
  19826. */
  19827. _getComputeCacheKey( computeNode, stageCompute ) {
  19828. return computeNode.id + ',' + stageCompute.id;
  19829. }
  19830. /**
  19831. * Computes a cache key representing a render pipeline.
  19832. *
  19833. * @private
  19834. * @param {RenderObject} renderObject - The render object.
  19835. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  19836. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  19837. * @return {string} The cache key.
  19838. */
  19839. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  19840. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  19841. }
  19842. /**
  19843. * Releases the given pipeline.
  19844. *
  19845. * @private
  19846. * @param {Pipeline} pipeline - The pipeline to release.
  19847. */
  19848. _releasePipeline( pipeline ) {
  19849. this.caches.delete( pipeline.cacheKey );
  19850. }
  19851. /**
  19852. * Releases the shader program.
  19853. *
  19854. * @private
  19855. * @param {Object} program - The shader program to release.
  19856. */
  19857. _releaseProgram( program ) {
  19858. const code = program.code;
  19859. const stage = program.stage;
  19860. this.programs[ stage ].delete( code );
  19861. }
  19862. /**
  19863. * Returns `true` if the compute pipeline for the given compute node requires an update.
  19864. *
  19865. * @private
  19866. * @param {Node} computeNode - The compute node.
  19867. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  19868. */
  19869. _needsComputeUpdate( computeNode ) {
  19870. const data = this.get( computeNode );
  19871. return data.pipeline === undefined || data.version !== computeNode.version;
  19872. }
  19873. /**
  19874. * Returns `true` if the render pipeline for the given render object requires an update.
  19875. *
  19876. * @private
  19877. * @param {RenderObject} renderObject - The render object.
  19878. * @return {boolean} Whether the render object for the given render object requires an update or not.
  19879. */
  19880. _needsRenderUpdate( renderObject ) {
  19881. const data = this.get( renderObject );
  19882. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  19883. }
  19884. }
  19885. /**
  19886. * This renderer module manages the bindings of the renderer.
  19887. *
  19888. * @private
  19889. * @augments DataMap
  19890. */
  19891. class Bindings extends DataMap {
  19892. /**
  19893. * Constructs a new bindings management component.
  19894. *
  19895. * @param {Backend} backend - The renderer's backend.
  19896. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19897. * @param {Textures} textures - Renderer component for managing textures.
  19898. * @param {Attributes} attributes - Renderer component for managing attributes.
  19899. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  19900. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19901. */
  19902. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  19903. super();
  19904. /**
  19905. * The renderer's backend.
  19906. *
  19907. * @type {Backend}
  19908. */
  19909. this.backend = backend;
  19910. /**
  19911. * Renderer component for managing textures.
  19912. *
  19913. * @type {Textures}
  19914. */
  19915. this.textures = textures;
  19916. /**
  19917. * Renderer component for managing pipelines.
  19918. *
  19919. * @type {Pipelines}
  19920. */
  19921. this.pipelines = pipelines;
  19922. /**
  19923. * Renderer component for managing attributes.
  19924. *
  19925. * @type {Attributes}
  19926. */
  19927. this.attributes = attributes;
  19928. /**
  19929. * Renderer component for managing nodes related logic.
  19930. *
  19931. * @type {Nodes}
  19932. */
  19933. this.nodes = nodes;
  19934. /**
  19935. * Renderer component for managing metrics and monitoring data.
  19936. *
  19937. * @type {Info}
  19938. */
  19939. this.info = info;
  19940. this.pipelines.bindings = this; // assign bindings to pipelines
  19941. }
  19942. /**
  19943. * Returns the bind groups for the given render object.
  19944. *
  19945. * @param {RenderObject} renderObject - The render object.
  19946. * @return {Array<BindGroup>} The bind groups.
  19947. */
  19948. getForRender( renderObject ) {
  19949. const bindings = renderObject.getBindings();
  19950. for ( const bindGroup of bindings ) {
  19951. const groupData = this.get( bindGroup );
  19952. if ( groupData.bindGroup === undefined ) {
  19953. // each object defines an array of bindings (ubos, textures, samplers etc.)
  19954. this._init( bindGroup );
  19955. this.backend.createBindings( bindGroup, bindings, 0 );
  19956. groupData.bindGroup = bindGroup;
  19957. }
  19958. }
  19959. return bindings;
  19960. }
  19961. /**
  19962. * Returns the bind groups for the given compute node.
  19963. *
  19964. * @param {Node} computeNode - The compute node.
  19965. * @return {Array<BindGroup>} The bind groups.
  19966. */
  19967. getForCompute( computeNode ) {
  19968. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  19969. for ( const bindGroup of bindings ) {
  19970. const groupData = this.get( bindGroup );
  19971. if ( groupData.bindGroup === undefined ) {
  19972. this._init( bindGroup );
  19973. this.backend.createBindings( bindGroup, bindings, 0 );
  19974. groupData.bindGroup = bindGroup;
  19975. }
  19976. }
  19977. return bindings;
  19978. }
  19979. /**
  19980. * Updates the bindings for the given compute node.
  19981. *
  19982. * @param {Node} computeNode - The compute node.
  19983. */
  19984. updateForCompute( computeNode ) {
  19985. this._updateBindings( this.getForCompute( computeNode ) );
  19986. }
  19987. /**
  19988. * Updates the bindings for the given render object.
  19989. *
  19990. * @param {RenderObject} renderObject - The render object.
  19991. */
  19992. updateForRender( renderObject ) {
  19993. this._updateBindings( this.getForRender( renderObject ) );
  19994. }
  19995. /**
  19996. * Updates the given array of bindings.
  19997. *
  19998. * @param {Array<BindGroup>} bindings - The bind groups.
  19999. */
  20000. _updateBindings( bindings ) {
  20001. for ( const bindGroup of bindings ) {
  20002. this._update( bindGroup, bindings );
  20003. }
  20004. }
  20005. /**
  20006. * Initializes the given bind group.
  20007. *
  20008. * @param {BindGroup} bindGroup - The bind group to initialize.
  20009. */
  20010. _init( bindGroup ) {
  20011. for ( const binding of bindGroup.bindings ) {
  20012. if ( binding.isSampledTexture ) {
  20013. this.textures.updateTexture( binding.texture );
  20014. } else if ( binding.isStorageBuffer ) {
  20015. const attribute = binding.attribute;
  20016. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20017. this.attributes.update( attribute, attributeType );
  20018. }
  20019. }
  20020. }
  20021. /**
  20022. * Updates the given bind group.
  20023. *
  20024. * @param {BindGroup} bindGroup - The bind group to update.
  20025. * @param {Array<BindGroup>} bindings - The bind groups.
  20026. */
  20027. _update( bindGroup, bindings ) {
  20028. const { backend } = this;
  20029. let needsBindingsUpdate = false;
  20030. let cacheBindings = true;
  20031. let cacheIndex = 0;
  20032. let version = 0;
  20033. // iterate over all bindings and check if buffer updates or a new binding group is required
  20034. for ( const binding of bindGroup.bindings ) {
  20035. if ( binding.isNodeUniformsGroup ) {
  20036. const updated = this.nodes.updateGroup( binding );
  20037. // every uniforms group is a uniform buffer. So if no update is required,
  20038. // we move one with the next binding. Otherwise the next if block will update the group.
  20039. if ( updated === false ) continue;
  20040. }
  20041. if ( binding.isStorageBuffer ) {
  20042. const attribute = binding.attribute;
  20043. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20044. this.attributes.update( attribute, attributeType );
  20045. }
  20046. if ( binding.isUniformBuffer ) {
  20047. const updated = binding.update();
  20048. if ( updated ) {
  20049. backend.updateBinding( binding );
  20050. }
  20051. } else if ( binding.isSampler ) {
  20052. binding.update();
  20053. } else if ( binding.isSampledTexture ) {
  20054. const texturesTextureData = this.textures.get( binding.texture );
  20055. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  20056. const updated = binding.update();
  20057. const texture = binding.texture;
  20058. if ( updated ) {
  20059. this.textures.updateTexture( texture );
  20060. }
  20061. const textureData = backend.get( texture );
  20062. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  20063. cacheBindings = false;
  20064. } else {
  20065. cacheIndex = cacheIndex * 10 + texture.id;
  20066. version += texture.version;
  20067. }
  20068. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  20069. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  20070. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  20071. this.textures.updateTexture( texture );
  20072. needsBindingsUpdate = true;
  20073. }
  20074. if ( texture.isStorageTexture === true ) {
  20075. const textureData = this.get( texture );
  20076. if ( binding.store === true ) {
  20077. textureData.needsMipmap = true;
  20078. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  20079. this.backend.generateMipmaps( texture );
  20080. textureData.needsMipmap = false;
  20081. }
  20082. }
  20083. }
  20084. }
  20085. if ( needsBindingsUpdate === true ) {
  20086. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  20087. }
  20088. }
  20089. }
  20090. /**
  20091. * Default sorting function for opaque render items.
  20092. *
  20093. * @private
  20094. * @function
  20095. * @param {Object} a - The first render item.
  20096. * @param {Object} b - The second render item.
  20097. * @return {number} A numeric value which defines the sort order.
  20098. */
  20099. function painterSortStable( a, b ) {
  20100. if ( a.groupOrder !== b.groupOrder ) {
  20101. return a.groupOrder - b.groupOrder;
  20102. } else if ( a.renderOrder !== b.renderOrder ) {
  20103. return a.renderOrder - b.renderOrder;
  20104. } else if ( a.z !== b.z ) {
  20105. return a.z - b.z;
  20106. } else {
  20107. return a.id - b.id;
  20108. }
  20109. }
  20110. /**
  20111. * Default sorting function for transparent render items.
  20112. *
  20113. * @private
  20114. * @function
  20115. * @param {Object} a - The first render item.
  20116. * @param {Object} b - The second render item.
  20117. * @return {number} A numeric value which defines the sort order.
  20118. */
  20119. function reversePainterSortStable( a, b ) {
  20120. if ( a.groupOrder !== b.groupOrder ) {
  20121. return a.groupOrder - b.groupOrder;
  20122. } else if ( a.renderOrder !== b.renderOrder ) {
  20123. return a.renderOrder - b.renderOrder;
  20124. } else if ( a.z !== b.z ) {
  20125. return b.z - a.z;
  20126. } else {
  20127. return a.id - b.id;
  20128. }
  20129. }
  20130. /**
  20131. * Returns `true` if the given transparent material requires a double pass.
  20132. *
  20133. * @private
  20134. * @function
  20135. * @param {Material} material - The transparent material.
  20136. * @return {boolean} Whether the given material requires a double pass or not.
  20137. */
  20138. function needsDoublePass( material ) {
  20139. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  20140. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  20141. }
  20142. /**
  20143. * When the renderer analyzes the scene at the beginning of a render call,
  20144. * it stores 3D object for further processing in render lists. Depending on the
  20145. * properties of a 3D objects (like their transformation or material state), the
  20146. * objects are maintained in ordered lists for the actual rendering.
  20147. *
  20148. * Render lists are unique per scene and camera combination.
  20149. *
  20150. * @private
  20151. * @augments Pipeline
  20152. */
  20153. class RenderList {
  20154. /**
  20155. * Constructs a render list.
  20156. *
  20157. * @param {Lighting} lighting - The lighting management component.
  20158. * @param {Scene} scene - The scene.
  20159. * @param {Camera} camera - The camera the scene is rendered with.
  20160. */
  20161. constructor( lighting, scene, camera ) {
  20162. /**
  20163. * 3D objects are transformed into render items and stored in this array.
  20164. *
  20165. * @type {Array<Object>}
  20166. */
  20167. this.renderItems = [];
  20168. /**
  20169. * The current render items index.
  20170. *
  20171. * @type {number}
  20172. * @default 0
  20173. */
  20174. this.renderItemsIndex = 0;
  20175. /**
  20176. * A list with opaque render items.
  20177. *
  20178. * @type {Array<Object>}
  20179. */
  20180. this.opaque = [];
  20181. /**
  20182. * A list with transparent render items which require
  20183. * double pass rendering (e.g. transmissive objects).
  20184. *
  20185. * @type {Array<Object>}
  20186. */
  20187. this.transparentDoublePass = [];
  20188. /**
  20189. * A list with transparent render items.
  20190. *
  20191. * @type {Array<Object>}
  20192. */
  20193. this.transparent = [];
  20194. /**
  20195. * A list with transparent render bundle data.
  20196. *
  20197. * @type {Array<Object>}
  20198. */
  20199. this.bundles = [];
  20200. /**
  20201. * The render list's lights node. This node is later
  20202. * relevant for the actual analytical light nodes which
  20203. * compute the scene's lighting in the shader.
  20204. *
  20205. * @type {LightsNode}
  20206. */
  20207. this.lightsNode = lighting.getNode( scene, camera );
  20208. /**
  20209. * The scene's lights stored in an array. This array
  20210. * is used to setup the lights node.
  20211. *
  20212. * @type {Array<Light>}
  20213. */
  20214. this.lightsArray = [];
  20215. /**
  20216. * The scene.
  20217. *
  20218. * @type {Scene}
  20219. */
  20220. this.scene = scene;
  20221. /**
  20222. * The camera the scene is rendered with.
  20223. *
  20224. * @type {Camera}
  20225. */
  20226. this.camera = camera;
  20227. /**
  20228. * How many objects perform occlusion query tests.
  20229. *
  20230. * @type {number}
  20231. * @default 0
  20232. */
  20233. this.occlusionQueryCount = 0;
  20234. }
  20235. /**
  20236. * This method is called right at the beginning of a render call
  20237. * before the scene is analyzed. It prepares the internal data
  20238. * structures for the upcoming render lists generation.
  20239. *
  20240. * @return {RenderList} A reference to this render list.
  20241. */
  20242. begin() {
  20243. this.renderItemsIndex = 0;
  20244. this.opaque.length = 0;
  20245. this.transparentDoublePass.length = 0;
  20246. this.transparent.length = 0;
  20247. this.bundles.length = 0;
  20248. this.lightsArray.length = 0;
  20249. this.occlusionQueryCount = 0;
  20250. return this;
  20251. }
  20252. /**
  20253. * Returns a render item for the giving render item state. The state is defined
  20254. * by a series of object-related parameters.
  20255. *
  20256. * The method avoids object creation by holding render items and reusing them in
  20257. * subsequent render calls (just with different property values).
  20258. *
  20259. * @param {Object3D} object - The 3D object.
  20260. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20261. * @param {Material} material - The 3D object's material.
  20262. * @param {number} groupOrder - The current group order.
  20263. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20264. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20265. * @param {ClippingContext} clippingContext - The current clipping context.
  20266. * @return {Object} The render item.
  20267. */
  20268. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20269. let renderItem = this.renderItems[ this.renderItemsIndex ];
  20270. if ( renderItem === undefined ) {
  20271. renderItem = {
  20272. id: object.id,
  20273. object: object,
  20274. geometry: geometry,
  20275. material: material,
  20276. groupOrder: groupOrder,
  20277. renderOrder: object.renderOrder,
  20278. z: z,
  20279. group: group,
  20280. clippingContext: clippingContext
  20281. };
  20282. this.renderItems[ this.renderItemsIndex ] = renderItem;
  20283. } else {
  20284. renderItem.id = object.id;
  20285. renderItem.object = object;
  20286. renderItem.geometry = geometry;
  20287. renderItem.material = material;
  20288. renderItem.groupOrder = groupOrder;
  20289. renderItem.renderOrder = object.renderOrder;
  20290. renderItem.z = z;
  20291. renderItem.group = group;
  20292. renderItem.clippingContext = clippingContext;
  20293. }
  20294. this.renderItemsIndex ++;
  20295. return renderItem;
  20296. }
  20297. /**
  20298. * Pushes the given object as a render item to the internal render lists.
  20299. * The selected lists depend on the object properties.
  20300. *
  20301. * @param {Object3D} object - The 3D object.
  20302. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20303. * @param {Material} material - The 3D object's material.
  20304. * @param {number} groupOrder - The current group order.
  20305. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20306. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20307. * @param {ClippingContext} clippingContext - The current clipping context.
  20308. */
  20309. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20310. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20311. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  20312. if ( material.transparent === true || material.transmission > 0 ) {
  20313. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  20314. this.transparent.push( renderItem );
  20315. } else {
  20316. this.opaque.push( renderItem );
  20317. }
  20318. }
  20319. /**
  20320. * Inserts the given object as a render item at the start of the internal render lists.
  20321. * The selected lists depend on the object properties.
  20322. *
  20323. * @param {Object3D} object - The 3D object.
  20324. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20325. * @param {Material} material - The 3D object's material.
  20326. * @param {number} groupOrder - The current group order.
  20327. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20328. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20329. * @param {ClippingContext} clippingContext - The current clipping context.
  20330. */
  20331. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20332. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20333. if ( material.transparent === true || material.transmission > 0 ) {
  20334. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  20335. this.transparent.unshift( renderItem );
  20336. } else {
  20337. this.opaque.unshift( renderItem );
  20338. }
  20339. }
  20340. /**
  20341. * Pushes render bundle group data into the render list.
  20342. *
  20343. * @param {Object} group - Bundle group data.
  20344. */
  20345. pushBundle( group ) {
  20346. this.bundles.push( group );
  20347. }
  20348. /**
  20349. * Pushes a light into the render list.
  20350. *
  20351. * @param {Light} light - The light.
  20352. */
  20353. pushLight( light ) {
  20354. this.lightsArray.push( light );
  20355. }
  20356. /**
  20357. * Sorts the internal render lists.
  20358. *
  20359. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  20360. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  20361. */
  20362. sort( customOpaqueSort, customTransparentSort ) {
  20363. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  20364. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  20365. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  20366. }
  20367. /**
  20368. * This method performs finalizing tasks right after the render lists
  20369. * have been generated.
  20370. */
  20371. finish() {
  20372. // update lights
  20373. this.lightsNode.setLights( this.lightsArray );
  20374. // Clear references from inactive renderItems in the list
  20375. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  20376. const renderItem = this.renderItems[ i ];
  20377. if ( renderItem.id === null ) break;
  20378. renderItem.id = null;
  20379. renderItem.object = null;
  20380. renderItem.geometry = null;
  20381. renderItem.material = null;
  20382. renderItem.groupOrder = null;
  20383. renderItem.renderOrder = null;
  20384. renderItem.z = null;
  20385. renderItem.group = null;
  20386. renderItem.clippingContext = null;
  20387. }
  20388. }
  20389. }
  20390. const _chainKeys$4 = [];
  20391. /**
  20392. * This renderer module manages the render lists which are unique
  20393. * per scene and camera combination.
  20394. *
  20395. * @private
  20396. */
  20397. class RenderLists {
  20398. /**
  20399. * Constructs a render lists management component.
  20400. *
  20401. * @param {Lighting} lighting - The lighting management component.
  20402. */
  20403. constructor( lighting ) {
  20404. /**
  20405. * The lighting management component.
  20406. *
  20407. * @type {Lighting}
  20408. */
  20409. this.lighting = lighting;
  20410. /**
  20411. * The internal chain map which holds the render lists.
  20412. *
  20413. * @type {ChainMap}
  20414. */
  20415. this.lists = new ChainMap();
  20416. }
  20417. /**
  20418. * Returns a render list for the given scene and camera.
  20419. *
  20420. * @param {Scene} scene - The scene.
  20421. * @param {Camera} camera - The camera.
  20422. * @return {RenderList} The render list.
  20423. */
  20424. get( scene, camera ) {
  20425. const lists = this.lists;
  20426. _chainKeys$4[ 0 ] = scene;
  20427. _chainKeys$4[ 1 ] = camera;
  20428. let list = lists.get( _chainKeys$4 );
  20429. if ( list === undefined ) {
  20430. list = new RenderList( this.lighting, scene, camera );
  20431. lists.set( _chainKeys$4, list );
  20432. }
  20433. _chainKeys$4.length = 0;
  20434. return list;
  20435. }
  20436. /**
  20437. * Frees all internal resources.
  20438. */
  20439. dispose() {
  20440. this.lists = new ChainMap();
  20441. }
  20442. }
  20443. let _id$7 = 0;
  20444. /**
  20445. * Any render or compute command is executed in a specific context that defines
  20446. * the state of the renderer and its backend. Typical examples for such context
  20447. * data are the current clear values or data from the active framebuffer. This
  20448. * module is used to represent these contexts as objects.
  20449. *
  20450. * @private
  20451. */
  20452. class RenderContext {
  20453. /**
  20454. * Constructs a new render context.
  20455. */
  20456. constructor() {
  20457. /**
  20458. * The context's ID.
  20459. *
  20460. * @type {number}
  20461. */
  20462. this.id = _id$7 ++;
  20463. /**
  20464. * Whether the current active framebuffer has a color attachment.
  20465. *
  20466. * @type {boolean}
  20467. * @default true
  20468. */
  20469. this.color = true;
  20470. /**
  20471. * Whether the color attachment should be cleared or not.
  20472. *
  20473. * @type {boolean}
  20474. * @default true
  20475. */
  20476. this.clearColor = true;
  20477. /**
  20478. * The clear color value.
  20479. *
  20480. * @type {Object}
  20481. * @default true
  20482. */
  20483. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  20484. /**
  20485. * Whether the current active framebuffer has a depth attachment.
  20486. *
  20487. * @type {boolean}
  20488. * @default true
  20489. */
  20490. this.depth = true;
  20491. /**
  20492. * Whether the depth attachment should be cleared or not.
  20493. *
  20494. * @type {boolean}
  20495. * @default true
  20496. */
  20497. this.clearDepth = true;
  20498. /**
  20499. * The clear depth value.
  20500. *
  20501. * @type {number}
  20502. * @default 1
  20503. */
  20504. this.clearDepthValue = 1;
  20505. /**
  20506. * Whether the current active framebuffer has a stencil attachment.
  20507. *
  20508. * @type {boolean}
  20509. * @default false
  20510. */
  20511. this.stencil = false;
  20512. /**
  20513. * Whether the stencil attachment should be cleared or not.
  20514. *
  20515. * @type {boolean}
  20516. * @default true
  20517. */
  20518. this.clearStencil = true;
  20519. /**
  20520. * The clear stencil value.
  20521. *
  20522. * @type {number}
  20523. * @default 1
  20524. */
  20525. this.clearStencilValue = 1;
  20526. /**
  20527. * By default the viewport encloses the entire framebuffer If a smaller
  20528. * viewport is manually defined, this property is to `true` by the renderer.
  20529. *
  20530. * @type {boolean}
  20531. * @default false
  20532. */
  20533. this.viewport = false;
  20534. /**
  20535. * The viewport value. This value is in physical pixels meaning it incorporates
  20536. * the renderer's pixel ratio. The viewport property of render targets or
  20537. * the renderer is in logical pixels.
  20538. *
  20539. * @type {Vector4}
  20540. */
  20541. this.viewportValue = new Vector4();
  20542. /**
  20543. * When the scissor test is active and scissor rectangle smaller than the
  20544. * framebuffers dimensions, this property is to `true` by the renderer.
  20545. *
  20546. * @type {boolean}
  20547. * @default false
  20548. */
  20549. this.scissor = false;
  20550. /**
  20551. * The scissor rectangle.
  20552. *
  20553. * @type {Vector4}
  20554. */
  20555. this.scissorValue = new Vector4();
  20556. /**
  20557. * The active render target.
  20558. *
  20559. * @type {?RenderTarget}
  20560. * @default null
  20561. */
  20562. this.renderTarget = null;
  20563. /**
  20564. * The textures of the active render target.
  20565. * `null` when no render target is set.
  20566. *
  20567. * @type {?Array<Texture>}
  20568. * @default null
  20569. */
  20570. this.textures = null;
  20571. /**
  20572. * The depth texture of the active render target.
  20573. * `null` when no render target is set.
  20574. *
  20575. * @type {?DepthTexture}
  20576. * @default null
  20577. */
  20578. this.depthTexture = null;
  20579. /**
  20580. * The active cube face.
  20581. *
  20582. * @type {number}
  20583. * @default 0
  20584. */
  20585. this.activeCubeFace = 0;
  20586. /**
  20587. * The active mipmap level.
  20588. *
  20589. * @type {number}
  20590. * @default 0
  20591. */
  20592. this.activeMipmapLevel = 0;
  20593. /**
  20594. * The number of MSAA samples. This value is always `1` when
  20595. * MSAA isn't used.
  20596. *
  20597. * @type {number}
  20598. * @default 1
  20599. */
  20600. this.sampleCount = 1;
  20601. /**
  20602. * The active render target's width in physical pixels.
  20603. *
  20604. * @type {number}
  20605. * @default 0
  20606. */
  20607. this.width = 0;
  20608. /**
  20609. * The active render target's height in physical pixels.
  20610. *
  20611. * @type {number}
  20612. * @default 0
  20613. */
  20614. this.height = 0;
  20615. /**
  20616. * The occlusion query count.
  20617. *
  20618. * @type {number}
  20619. * @default 0
  20620. */
  20621. this.occlusionQueryCount = 0;
  20622. /**
  20623. * The current clipping context.
  20624. *
  20625. * @type {?ClippingContext}
  20626. * @default null
  20627. */
  20628. this.clippingContext = null;
  20629. /**
  20630. * This flag can be used for type testing.
  20631. *
  20632. * @type {boolean}
  20633. * @readonly
  20634. * @default true
  20635. */
  20636. this.isRenderContext = true;
  20637. }
  20638. /**
  20639. * Returns the cache key of this render context.
  20640. *
  20641. * @return {number} The cache key.
  20642. */
  20643. getCacheKey() {
  20644. return getCacheKey( this );
  20645. }
  20646. }
  20647. /**
  20648. * Computes a cache key for the given render context. This key
  20649. * should identify the render target state so it is possible to
  20650. * configure the correct attachments in the respective backend.
  20651. *
  20652. * @param {RenderContext} renderContext - The render context.
  20653. * @return {number} The cache key.
  20654. */
  20655. function getCacheKey( renderContext ) {
  20656. const { textures, activeCubeFace } = renderContext;
  20657. const values = [ activeCubeFace ];
  20658. for ( const texture of textures ) {
  20659. values.push( texture.id );
  20660. }
  20661. return hashArray( values );
  20662. }
  20663. const _chainKeys$3 = [];
  20664. const _defaultScene = /*@__PURE__*/ new Scene();
  20665. const _defaultCamera = /*@__PURE__*/ new Camera();
  20666. /**
  20667. * This module manages the render contexts of the renderer.
  20668. *
  20669. * @private
  20670. */
  20671. class RenderContexts {
  20672. /**
  20673. * Constructs a new render context management component.
  20674. */
  20675. constructor() {
  20676. /**
  20677. * A dictionary that manages render contexts in chain maps
  20678. * for each attachment state.
  20679. *
  20680. * @type {Object<string,ChainMap>}
  20681. */
  20682. this.chainMaps = {};
  20683. }
  20684. /**
  20685. * Returns a render context for the given scene, camera and render target.
  20686. *
  20687. * @param {Scene} scene - The scene.
  20688. * @param {Camera} camera - The camera that is used to render the scene.
  20689. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  20690. * @return {RenderContext} The render context.
  20691. */
  20692. get( scene, camera, renderTarget = null ) {
  20693. _chainKeys$3[ 0 ] = scene;
  20694. _chainKeys$3[ 1 ] = camera;
  20695. let attachmentState;
  20696. if ( renderTarget === null ) {
  20697. attachmentState = 'default';
  20698. } else {
  20699. const format = renderTarget.texture.format;
  20700. const count = renderTarget.textures.length;
  20701. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  20702. }
  20703. const chainMap = this._getChainMap( attachmentState );
  20704. let renderState = chainMap.get( _chainKeys$3 );
  20705. if ( renderState === undefined ) {
  20706. renderState = new RenderContext();
  20707. chainMap.set( _chainKeys$3, renderState );
  20708. }
  20709. _chainKeys$3.length = 0;
  20710. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  20711. return renderState;
  20712. }
  20713. /**
  20714. * Returns a render context intended for clear operations.
  20715. *
  20716. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  20717. * @return {RenderContext} The render context.
  20718. */
  20719. getForClear( renderTarget = null ) {
  20720. return this.get( _defaultScene, _defaultCamera, renderTarget );
  20721. }
  20722. /**
  20723. * Returns a chain map for the given attachment state.
  20724. *
  20725. * @private
  20726. * @param {string} attachmentState - The attachment state.
  20727. * @return {ChainMap} The chain map.
  20728. */
  20729. _getChainMap( attachmentState ) {
  20730. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  20731. }
  20732. /**
  20733. * Frees internal resources.
  20734. */
  20735. dispose() {
  20736. this.chainMaps = {};
  20737. }
  20738. }
  20739. const _size$3 = /*@__PURE__*/ new Vector3();
  20740. /**
  20741. * This module manages the textures of the renderer.
  20742. *
  20743. * @private
  20744. * @augments DataMap
  20745. */
  20746. class Textures extends DataMap {
  20747. /**
  20748. * Constructs a new texture management component.
  20749. *
  20750. * @param {Renderer} renderer - The renderer.
  20751. * @param {Backend} backend - The renderer's backend.
  20752. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20753. */
  20754. constructor( renderer, backend, info ) {
  20755. super();
  20756. /**
  20757. * The renderer.
  20758. *
  20759. * @type {Renderer}
  20760. */
  20761. this.renderer = renderer;
  20762. /**
  20763. * The backend.
  20764. *
  20765. * @type {Backend}
  20766. */
  20767. this.backend = backend;
  20768. /**
  20769. * Renderer component for managing metrics and monitoring data.
  20770. *
  20771. * @type {Info}
  20772. */
  20773. this.info = info;
  20774. }
  20775. /**
  20776. * Updates the given render target. Based on the given render target configuration,
  20777. * it updates the texture states representing the attachments of the framebuffer.
  20778. *
  20779. * @param {RenderTarget} renderTarget - The render target to update.
  20780. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  20781. */
  20782. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  20783. const renderTargetData = this.get( renderTarget );
  20784. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  20785. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  20786. const textures = renderTarget.textures;
  20787. const size = this.getSize( textures[ 0 ] );
  20788. const mipWidth = size.width >> activeMipmapLevel;
  20789. const mipHeight = size.height >> activeMipmapLevel;
  20790. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  20791. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  20792. let textureNeedsUpdate = false;
  20793. if ( depthTexture === undefined && useDepthTexture ) {
  20794. depthTexture = new DepthTexture();
  20795. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  20796. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  20797. depthTexture.image.width = mipWidth;
  20798. depthTexture.image.height = mipHeight;
  20799. depthTexture.image.depth = size.depth;
  20800. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  20801. }
  20802. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  20803. textureNeedsUpdate = true;
  20804. if ( depthTexture ) {
  20805. depthTexture.needsUpdate = true;
  20806. depthTexture.image.width = mipWidth;
  20807. depthTexture.image.height = mipHeight;
  20808. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  20809. }
  20810. }
  20811. renderTargetData.width = size.width;
  20812. renderTargetData.height = size.height;
  20813. renderTargetData.textures = textures;
  20814. renderTargetData.depthTexture = depthTexture || null;
  20815. renderTargetData.depth = renderTarget.depthBuffer;
  20816. renderTargetData.stencil = renderTarget.stencilBuffer;
  20817. renderTargetData.renderTarget = renderTarget;
  20818. if ( renderTargetData.sampleCount !== sampleCount ) {
  20819. textureNeedsUpdate = true;
  20820. if ( depthTexture ) {
  20821. depthTexture.needsUpdate = true;
  20822. }
  20823. renderTargetData.sampleCount = sampleCount;
  20824. }
  20825. //
  20826. const options = { sampleCount };
  20827. // XR render targets require no texture updates
  20828. if ( renderTarget.isXRRenderTarget !== true ) {
  20829. for ( let i = 0; i < textures.length; i ++ ) {
  20830. const texture = textures[ i ];
  20831. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  20832. this.updateTexture( texture, options );
  20833. }
  20834. if ( depthTexture ) {
  20835. this.updateTexture( depthTexture, options );
  20836. }
  20837. }
  20838. // dispose handler
  20839. if ( renderTargetData.initialized !== true ) {
  20840. renderTargetData.initialized = true;
  20841. // dispose
  20842. const onDispose = () => {
  20843. renderTarget.removeEventListener( 'dispose', onDispose );
  20844. for ( let i = 0; i < textures.length; i ++ ) {
  20845. this._destroyTexture( textures[ i ] );
  20846. }
  20847. if ( depthTexture ) {
  20848. this._destroyTexture( depthTexture );
  20849. }
  20850. this.delete( renderTarget );
  20851. };
  20852. renderTarget.addEventListener( 'dispose', onDispose );
  20853. }
  20854. }
  20855. /**
  20856. * Updates the given texture. Depending on the texture state, this method
  20857. * triggers the upload of texture data to the GPU memory. If the texture data are
  20858. * not yet ready for the upload, it uses default texture data for as a placeholder.
  20859. *
  20860. * @param {Texture} texture - The texture to update.
  20861. * @param {Object} [options={}] - The options.
  20862. */
  20863. updateTexture( texture, options = {} ) {
  20864. const textureData = this.get( texture );
  20865. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  20866. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  20867. const backend = this.backend;
  20868. if ( isRenderTarget && textureData.initialized === true ) {
  20869. // it's an update
  20870. backend.destroySampler( texture );
  20871. backend.destroyTexture( texture );
  20872. }
  20873. //
  20874. if ( texture.isFramebufferTexture ) {
  20875. const renderTarget = this.renderer.getRenderTarget();
  20876. if ( renderTarget ) {
  20877. texture.type = renderTarget.texture.type;
  20878. } else {
  20879. texture.type = UnsignedByteType;
  20880. }
  20881. }
  20882. //
  20883. const { width, height, depth } = this.getSize( texture );
  20884. options.width = width;
  20885. options.height = height;
  20886. options.depth = depth;
  20887. options.needsMipmaps = this.needsMipmaps( texture );
  20888. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  20889. //
  20890. if ( isRenderTarget || texture.isStorageTexture === true ) {
  20891. backend.createSampler( texture );
  20892. backend.createTexture( texture, options );
  20893. textureData.generation = texture.version;
  20894. } else {
  20895. const needsCreate = textureData.initialized !== true;
  20896. if ( needsCreate ) backend.createSampler( texture );
  20897. if ( texture.version > 0 ) {
  20898. const image = texture.image;
  20899. if ( image === undefined ) {
  20900. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  20901. } else if ( image.complete === false ) {
  20902. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  20903. } else {
  20904. if ( texture.images ) {
  20905. const images = [];
  20906. for ( const image of texture.images ) {
  20907. images.push( image );
  20908. }
  20909. options.images = images;
  20910. } else {
  20911. options.image = image;
  20912. }
  20913. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  20914. backend.createTexture( texture, options );
  20915. textureData.isDefaultTexture = false;
  20916. textureData.generation = texture.version;
  20917. }
  20918. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  20919. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  20920. }
  20921. } else {
  20922. // async update
  20923. backend.createDefaultTexture( texture );
  20924. textureData.isDefaultTexture = true;
  20925. textureData.generation = texture.version;
  20926. }
  20927. }
  20928. // dispose handler
  20929. if ( textureData.initialized !== true ) {
  20930. textureData.initialized = true;
  20931. textureData.generation = texture.version;
  20932. //
  20933. this.info.memory.textures ++;
  20934. // dispose
  20935. const onDispose = () => {
  20936. texture.removeEventListener( 'dispose', onDispose );
  20937. this._destroyTexture( texture );
  20938. };
  20939. texture.addEventListener( 'dispose', onDispose );
  20940. }
  20941. //
  20942. textureData.version = texture.version;
  20943. }
  20944. /**
  20945. * Computes the size of the given texture and writes the result
  20946. * into the target vector. This vector is also returned by the
  20947. * method.
  20948. *
  20949. * If no texture data are available for the compute yet, the method
  20950. * returns default size values.
  20951. *
  20952. * @param {Texture} texture - The texture to compute the size for.
  20953. * @param {Vector3} target - The target vector.
  20954. * @return {Vector3} The target vector.
  20955. */
  20956. getSize( texture, target = _size$3 ) {
  20957. let image = texture.images ? texture.images[ 0 ] : texture.image;
  20958. if ( image ) {
  20959. if ( image.image !== undefined ) image = image.image;
  20960. target.width = image.width || 1;
  20961. target.height = image.height || 1;
  20962. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  20963. } else {
  20964. target.width = target.height = target.depth = 1;
  20965. }
  20966. return target;
  20967. }
  20968. /**
  20969. * Computes the number of mipmap levels for the given texture.
  20970. *
  20971. * @param {Texture} texture - The texture.
  20972. * @param {number} width - The texture's width.
  20973. * @param {number} height - The texture's height.
  20974. * @return {number} The number of mipmap levels.
  20975. */
  20976. getMipLevels( texture, width, height ) {
  20977. let mipLevelCount;
  20978. if ( texture.isCompressedTexture ) {
  20979. if ( texture.mipmaps ) {
  20980. mipLevelCount = texture.mipmaps.length;
  20981. } else {
  20982. mipLevelCount = 1;
  20983. }
  20984. } else {
  20985. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  20986. }
  20987. return mipLevelCount;
  20988. }
  20989. /**
  20990. * Returns `true` if the given texture requires mipmaps.
  20991. *
  20992. * @param {Texture} texture - The texture.
  20993. * @return {boolean} Whether mipmaps are required or not.
  20994. */
  20995. needsMipmaps( texture ) {
  20996. return texture.isCompressedTexture === true || texture.generateMipmaps;
  20997. }
  20998. /**
  20999. * Frees internal resource when the given texture isn't
  21000. * required anymore.
  21001. *
  21002. * @param {Texture} texture - The texture to destroy.
  21003. */
  21004. _destroyTexture( texture ) {
  21005. if ( this.has( texture ) === true ) {
  21006. this.backend.destroySampler( texture );
  21007. this.backend.destroyTexture( texture );
  21008. this.delete( texture );
  21009. this.info.memory.textures --;
  21010. }
  21011. }
  21012. }
  21013. /**
  21014. * A four-component version of {@link Color} which is internally
  21015. * used by the renderer to represents clear color with alpha as
  21016. * one object.
  21017. *
  21018. * @private
  21019. * @augments Color
  21020. */
  21021. class Color4 extends Color {
  21022. /**
  21023. * Constructs a new four-component color.
  21024. * You can also pass a single THREE.Color, hex or
  21025. * string argument to this constructor.
  21026. *
  21027. * @param {number|string} [r=1] - The red value.
  21028. * @param {number} [g=1] - The green value.
  21029. * @param {number} [b=1] - The blue value.
  21030. * @param {number} [a=1] - The alpha value.
  21031. */
  21032. constructor( r, g, b, a = 1 ) {
  21033. super( r, g, b );
  21034. this.a = a;
  21035. }
  21036. /**
  21037. * Overwrites the default to honor alpha.
  21038. * You can also pass a single THREE.Color, hex or
  21039. * string argument to this method.
  21040. *
  21041. * @param {number|string|Color} r - The red value.
  21042. * @param {number} g - The green value.
  21043. * @param {number} b - The blue value.
  21044. * @param {number} [a=1] - The alpha value.
  21045. * @return {Color4} A reference to this object.
  21046. */
  21047. set( r, g, b, a = 1 ) {
  21048. this.a = a;
  21049. return super.set( r, g, b );
  21050. }
  21051. /**
  21052. * Overwrites the default to honor alpha.
  21053. *
  21054. * @param {Color4} color - The color to copy.
  21055. * @return {Color4} A reference to this object.
  21056. */
  21057. copy( color ) {
  21058. if ( color.a !== undefined ) this.a = color.a;
  21059. return super.copy( color );
  21060. }
  21061. /**
  21062. * Overwrites the default to honor alpha.
  21063. *
  21064. * @return {Color4} The cloned color.
  21065. */
  21066. clone() {
  21067. return new this.constructor( this.r, this.g, this.b, this.a );
  21068. }
  21069. }
  21070. /**
  21071. * Special version of {@link PropertyNode} which is used for parameters.
  21072. *
  21073. * @augments PropertyNode
  21074. */
  21075. class ParameterNode extends PropertyNode {
  21076. static get type() {
  21077. return 'ParameterNode';
  21078. }
  21079. /**
  21080. * Constructs a new parameter node.
  21081. *
  21082. * @param {string} nodeType - The type of the node.
  21083. * @param {?string} [name=null] - The name of the parameter in the shader.
  21084. */
  21085. constructor( nodeType, name = null ) {
  21086. super( nodeType, name );
  21087. /**
  21088. * This flag can be used for type testing.
  21089. *
  21090. * @type {boolean}
  21091. * @readonly
  21092. * @default true
  21093. */
  21094. this.isParameterNode = true;
  21095. }
  21096. getHash() {
  21097. return this.uuid;
  21098. }
  21099. generate() {
  21100. return this.name;
  21101. }
  21102. }
  21103. /**
  21104. * TSL function for creating a parameter node.
  21105. *
  21106. * @tsl
  21107. * @function
  21108. * @param {string} type - The type of the node.
  21109. * @param {?string} name - The name of the parameter in the shader.
  21110. * @returns {ParameterNode}
  21111. */
  21112. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  21113. /**
  21114. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  21115. * They are usually needed in cases like `If`, `Else`.
  21116. *
  21117. * @augments Node
  21118. */
  21119. class StackNode extends Node {
  21120. static get type() {
  21121. return 'StackNode';
  21122. }
  21123. /**
  21124. * Constructs a new stack node.
  21125. *
  21126. * @param {?StackNode} [parent=null] - The parent stack node.
  21127. */
  21128. constructor( parent = null ) {
  21129. super();
  21130. /**
  21131. * List of nodes.
  21132. *
  21133. * @type {Array<Node>}
  21134. */
  21135. this.nodes = [];
  21136. /**
  21137. * The output node.
  21138. *
  21139. * @type {?Node}
  21140. * @default null
  21141. */
  21142. this.outputNode = null;
  21143. /**
  21144. * The parent stack node.
  21145. *
  21146. * @type {?StackNode}
  21147. * @default null
  21148. */
  21149. this.parent = parent;
  21150. /**
  21151. * The current conditional node.
  21152. *
  21153. * @private
  21154. * @type {ConditionalNode}
  21155. * @default null
  21156. */
  21157. this._currentCond = null;
  21158. /**
  21159. * The expression node. Only
  21160. * relevant for Switch/Case.
  21161. *
  21162. * @private
  21163. * @type {Node}
  21164. * @default null
  21165. */
  21166. this._expressionNode = null;
  21167. /**
  21168. * This flag can be used for type testing.
  21169. *
  21170. * @type {boolean}
  21171. * @readonly
  21172. * @default true
  21173. */
  21174. this.isStackNode = true;
  21175. }
  21176. getNodeType( builder ) {
  21177. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  21178. }
  21179. getMemberType( builder, name ) {
  21180. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  21181. }
  21182. /**
  21183. * Adds a node to this stack.
  21184. *
  21185. * @param {Node} node - The node to add.
  21186. * @return {StackNode} A reference to this stack node.
  21187. */
  21188. add( node ) {
  21189. this.nodes.push( node );
  21190. return this;
  21191. }
  21192. /**
  21193. * Represent an `if` statement in TSL.
  21194. *
  21195. * @param {Node} boolNode - Represents the condition.
  21196. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21197. * @return {StackNode} A reference to this stack node.
  21198. */
  21199. If( boolNode, method ) {
  21200. const methodNode = new ShaderNode( method );
  21201. this._currentCond = select( boolNode, methodNode );
  21202. return this.add( this._currentCond );
  21203. }
  21204. /**
  21205. * Represent an `elseif` statement in TSL.
  21206. *
  21207. * @param {Node} boolNode - Represents the condition.
  21208. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21209. * @return {StackNode} A reference to this stack node.
  21210. */
  21211. ElseIf( boolNode, method ) {
  21212. const methodNode = new ShaderNode( method );
  21213. const ifNode = select( boolNode, methodNode );
  21214. this._currentCond.elseNode = ifNode;
  21215. this._currentCond = ifNode;
  21216. return this;
  21217. }
  21218. /**
  21219. * Represent an `else` statement in TSL.
  21220. *
  21221. * @param {Function} method - TSL code which is executed in the `else` case.
  21222. * @return {StackNode} A reference to this stack node.
  21223. */
  21224. Else( method ) {
  21225. this._currentCond.elseNode = new ShaderNode( method );
  21226. return this;
  21227. }
  21228. /**
  21229. * Represents a `switch` statement in TSL.
  21230. *
  21231. * @param {any} expression - Represents the expression.
  21232. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21233. * @return {StackNode} A reference to this stack node.
  21234. */
  21235. Switch( expression ) {
  21236. this._expressionNode = nodeObject( expression );
  21237. return this;
  21238. }
  21239. /**
  21240. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  21241. * The last parameter must be the callback method that should be executed in the `true` case.
  21242. *
  21243. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  21244. * @return {StackNode} A reference to this stack node.
  21245. */
  21246. Case( ...params ) {
  21247. const caseNodes = [];
  21248. // extract case nodes from the parameter list
  21249. if ( params.length >= 2 ) {
  21250. for ( let i = 0; i < params.length - 1; i ++ ) {
  21251. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  21252. }
  21253. } else {
  21254. throw new Error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  21255. }
  21256. // extract method
  21257. const method = params[ params.length - 1 ];
  21258. const methodNode = new ShaderNode( method );
  21259. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  21260. let caseNode = caseNodes[ 0 ];
  21261. for ( let i = 1; i < caseNodes.length; i ++ ) {
  21262. caseNode = caseNode.or( caseNodes[ i ] );
  21263. }
  21264. // build condition
  21265. const condNode = select( caseNode, methodNode );
  21266. if ( this._currentCond === null ) {
  21267. this._currentCond = condNode;
  21268. return this.add( this._currentCond );
  21269. } else {
  21270. this._currentCond.elseNode = condNode;
  21271. this._currentCond = condNode;
  21272. return this;
  21273. }
  21274. }
  21275. /**
  21276. * Represents the default code block of a Switch/Case statement.
  21277. *
  21278. * @param {Function} method - TSL code which is executed in the `else` case.
  21279. * @return {StackNode} A reference to this stack node.
  21280. */
  21281. Default( method ) {
  21282. this.Else( method );
  21283. return this;
  21284. }
  21285. build( builder, ...params ) {
  21286. const previousStack = getCurrentStack();
  21287. setCurrentStack( this );
  21288. for ( const node of this.nodes ) {
  21289. node.build( builder, 'void' );
  21290. }
  21291. setCurrentStack( previousStack );
  21292. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  21293. }
  21294. // Deprecated
  21295. /**
  21296. * @function
  21297. * @deprecated since r168. Use {@link StackNode#Else} instead.
  21298. *
  21299. * @param {...any} params
  21300. * @returns {StackNode}
  21301. */
  21302. else( ...params ) { // @deprecated, r168
  21303. console.warn( 'THREE.TSL: .else() has been renamed to .Else().' );
  21304. return this.Else( ...params );
  21305. }
  21306. /**
  21307. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  21308. *
  21309. * @param {...any} params
  21310. * @returns {StackNode}
  21311. */
  21312. elseif( ...params ) { // @deprecated, r168
  21313. console.warn( 'THREE.TSL: .elseif() has been renamed to .ElseIf().' );
  21314. return this.ElseIf( ...params );
  21315. }
  21316. }
  21317. /**
  21318. * TSL function for creating a stack node.
  21319. *
  21320. * @tsl
  21321. * @function
  21322. * @param {?StackNode} [parent=null] - The parent stack node.
  21323. * @returns {StackNode}
  21324. */
  21325. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  21326. /**
  21327. * Generates a layout for struct members.
  21328. * This function takes an object representing struct members and returns an array of member layouts.
  21329. * Each member layout includes the member's name, type, and whether it is atomic.
  21330. *
  21331. * @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.
  21332. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  21333. */
  21334. function getMembersLayout( members ) {
  21335. return Object.entries( members ).map( ( [ name, value ] ) => {
  21336. if ( typeof value === 'string' ) {
  21337. return { name, type: value, atomic: false };
  21338. }
  21339. return { name, type: value.type, atomic: value.atomic || false };
  21340. } );
  21341. }
  21342. /**
  21343. * Represents a struct type node in the node-based system.
  21344. * This class is used to define and manage the layout and types of struct members.
  21345. * It extends the base Node class and provides methods to get the length of the struct,
  21346. * retrieve member types, and generate the struct type for a builder.
  21347. *
  21348. * @augments Node
  21349. */
  21350. class StructTypeNode extends Node {
  21351. static get type() {
  21352. return 'StructTypeNode';
  21353. }
  21354. /**
  21355. * Creates an instance of StructTypeNode.
  21356. *
  21357. * @param {Object} membersLayout - The layout of the members for the struct.
  21358. * @param {?string} [name=null] - The optional name of the struct.
  21359. */
  21360. constructor( membersLayout, name = null ) {
  21361. super( 'struct' );
  21362. /**
  21363. * The layout of the members for the struct
  21364. *
  21365. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  21366. */
  21367. this.membersLayout = getMembersLayout( membersLayout );
  21368. /**
  21369. * The name of the struct.
  21370. *
  21371. * @type {?string}
  21372. * @default null
  21373. */
  21374. this.name = name;
  21375. /**
  21376. * This flag can be used for type testing.
  21377. *
  21378. * @type {boolean}
  21379. * @readonly
  21380. * @default true
  21381. */
  21382. this.isStructLayoutNode = true;
  21383. }
  21384. /**
  21385. * Returns the length of the struct.
  21386. * The length is calculated by summing the lengths of the struct's members.
  21387. *
  21388. * @returns {number} The length of the struct.
  21389. */
  21390. getLength() {
  21391. let length = 0;
  21392. for ( const member of this.membersLayout ) {
  21393. length += getLengthFromType( member.type );
  21394. }
  21395. return length;
  21396. }
  21397. getMemberType( builder, name ) {
  21398. const member = this.membersLayout.find( m => m.name === name );
  21399. return member ? member.type : 'void';
  21400. }
  21401. getNodeType( builder ) {
  21402. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  21403. return structType.name;
  21404. }
  21405. setup( builder ) {
  21406. builder.addInclude( this );
  21407. }
  21408. generate( builder ) {
  21409. return this.getNodeType( builder );
  21410. }
  21411. }
  21412. /**
  21413. * StructNode allows to create custom structures with multiple members.
  21414. * This can also be used to define structures in attribute and uniform data.
  21415. *
  21416. * ```js
  21417. * // Define a custom struct
  21418. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  21419. *
  21420. * // Create a new instance of the struct
  21421. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  21422. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  21423. *
  21424. * // Access the struct members
  21425. * const min = bb.get( 'min' );
  21426. *
  21427. * // Assign a new value to a member
  21428. * min.assign( vec3() );
  21429. * ```
  21430. * @augments Node
  21431. */
  21432. class StructNode extends Node {
  21433. static get type() {
  21434. return 'StructNode';
  21435. }
  21436. constructor( structLayoutNode, values ) {
  21437. super( 'vec3' );
  21438. this.structLayoutNode = structLayoutNode;
  21439. this.values = values;
  21440. this.isStructNode = true;
  21441. }
  21442. getNodeType( builder ) {
  21443. return this.structLayoutNode.getNodeType( builder );
  21444. }
  21445. getMemberType( builder, name ) {
  21446. return this.structLayoutNode.getMemberType( builder, name );
  21447. }
  21448. generate( builder ) {
  21449. const nodeVar = builder.getVarFromNode( this );
  21450. const structType = nodeVar.type;
  21451. const propertyName = builder.getPropertyName( nodeVar );
  21452. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  21453. return nodeVar.name;
  21454. }
  21455. }
  21456. /**
  21457. * TSL function for creating a struct node.
  21458. *
  21459. * @tsl
  21460. * @function
  21461. * @param {Object} membersLayout - The layout of the struct members.
  21462. * @param {?string} [name=null] - The name of the struct.
  21463. * @returns {Function} The struct function.
  21464. */
  21465. const struct = ( membersLayout, name = null ) => {
  21466. const structLayout = new StructTypeNode( membersLayout, name );
  21467. const struct = ( ...params ) => {
  21468. let values = null;
  21469. if ( params.length > 0 ) {
  21470. if ( params[ 0 ].isNode ) {
  21471. values = {};
  21472. const names = Object.keys( membersLayout );
  21473. for ( let i = 0; i < params.length; i ++ ) {
  21474. values[ names[ i ] ] = params[ i ];
  21475. }
  21476. } else {
  21477. values = params[ 0 ];
  21478. }
  21479. }
  21480. return nodeObject( new StructNode( structLayout, values ) );
  21481. };
  21482. struct.layout = structLayout;
  21483. struct.isStruct = true;
  21484. return struct;
  21485. };
  21486. /**
  21487. * This node can be used to define multiple outputs in a shader programs.
  21488. *
  21489. * @augments Node
  21490. */
  21491. class OutputStructNode extends Node {
  21492. static get type() {
  21493. return 'OutputStructNode';
  21494. }
  21495. /**
  21496. * Constructs a new output struct node. The constructor can be invoked with an
  21497. * arbitrary number of nodes representing the members.
  21498. *
  21499. * @param {...Node} members - A parameter list of nodes.
  21500. */
  21501. constructor( ...members ) {
  21502. super();
  21503. /**
  21504. * An array of nodes which defines the output.
  21505. *
  21506. * @type {Array<Node>}
  21507. */
  21508. this.members = members;
  21509. /**
  21510. * This flag can be used for type testing.
  21511. *
  21512. * @type {boolean}
  21513. * @readonly
  21514. * @default true
  21515. */
  21516. this.isOutputStructNode = true;
  21517. }
  21518. getNodeType( builder ) {
  21519. const properties = builder.getNodeProperties( this );
  21520. if ( properties.membersLayout === undefined ) {
  21521. const members = this.members;
  21522. const membersLayout = [];
  21523. for ( let i = 0; i < members.length; i ++ ) {
  21524. const name = 'm' + i;
  21525. const type = members[ i ].getNodeType( builder );
  21526. membersLayout.push( { name, type, index: i } );
  21527. }
  21528. properties.membersLayout = membersLayout;
  21529. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  21530. }
  21531. return properties.structType.name;
  21532. }
  21533. generate( builder ) {
  21534. const propertyName = builder.getOutputStructName();
  21535. const members = this.members;
  21536. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  21537. for ( let i = 0; i < members.length; i ++ ) {
  21538. const snippet = members[ i ].build( builder );
  21539. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  21540. }
  21541. return propertyName;
  21542. }
  21543. }
  21544. /**
  21545. * TSL function for creating an output struct node.
  21546. *
  21547. * @tsl
  21548. * @function
  21549. * @param {...Node} members - A parameter list of nodes.
  21550. * @returns {OutputStructNode}
  21551. */
  21552. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  21553. /**
  21554. * Returns the MRT texture index for the given name.
  21555. *
  21556. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  21557. * @param {string} name - The name of the MRT texture which index is requested.
  21558. * @return {number} The texture index.
  21559. */
  21560. function getTextureIndex( textures, name ) {
  21561. for ( let i = 0; i < textures.length; i ++ ) {
  21562. if ( textures[ i ].name === name ) {
  21563. return i;
  21564. }
  21565. }
  21566. return -1;
  21567. }
  21568. /**
  21569. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  21570. * post-processing is shown below:
  21571. * ```js
  21572. * const mrtNode = mrt( {
  21573. * output: output,
  21574. * normal: normalView
  21575. * } ) );
  21576. * ```
  21577. * The MRT output is defined as a dictionary.
  21578. *
  21579. * @augments OutputStructNode
  21580. */
  21581. class MRTNode extends OutputStructNode {
  21582. static get type() {
  21583. return 'MRTNode';
  21584. }
  21585. /**
  21586. * Constructs a new output struct node.
  21587. *
  21588. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  21589. */
  21590. constructor( outputNodes ) {
  21591. super();
  21592. /**
  21593. * A dictionary representing the MRT outputs. The key
  21594. * is the name of the output, the value the node which produces
  21595. * the output result.
  21596. *
  21597. * @type {Object<string, Node>}
  21598. */
  21599. this.outputNodes = outputNodes;
  21600. /**
  21601. * This flag can be used for type testing.
  21602. *
  21603. * @type {boolean}
  21604. * @readonly
  21605. * @default true
  21606. */
  21607. this.isMRTNode = true;
  21608. }
  21609. /**
  21610. * Returns `true` if the MRT node has an output with the given name.
  21611. *
  21612. * @param {string} name - The name of the output.
  21613. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  21614. */
  21615. has( name ) {
  21616. return this.outputNodes[ name ] !== undefined;
  21617. }
  21618. /**
  21619. * Returns the output node for the given name.
  21620. *
  21621. * @param {string} name - The name of the output.
  21622. * @return {Node} The output node.
  21623. */
  21624. get( name ) {
  21625. return this.outputNodes[ name ];
  21626. }
  21627. /**
  21628. * Merges the outputs of the given MRT node with the outputs of this node.
  21629. *
  21630. * @param {MRTNode} mrtNode - The MRT to merge.
  21631. * @return {MRTNode} A new MRT node with merged outputs..
  21632. */
  21633. merge( mrtNode ) {
  21634. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  21635. return mrt( outputs );
  21636. }
  21637. setup( builder ) {
  21638. const outputNodes = this.outputNodes;
  21639. const mrt = builder.renderer.getRenderTarget();
  21640. const members = [];
  21641. const textures = mrt.textures;
  21642. for ( const name in outputNodes ) {
  21643. const index = getTextureIndex( textures, name );
  21644. members[ index ] = vec4( outputNodes[ name ] );
  21645. }
  21646. this.members = members;
  21647. return super.setup( builder );
  21648. }
  21649. }
  21650. /**
  21651. * TSL function for creating a MRT node.
  21652. *
  21653. * @tsl
  21654. * @function
  21655. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  21656. * @returns {MRTNode}
  21657. */
  21658. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  21659. /**
  21660. * Generates a hash value in the range `[0, 1]` from the given seed.
  21661. *
  21662. * @tsl
  21663. * @function
  21664. * @param {Node<float>} seed - The seed.
  21665. * @return {Node<float>} The hash value.
  21666. */
  21667. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  21668. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  21669. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  21670. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  21671. const result = word.shiftRight( 22 ).bitXor( word );
  21672. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  21673. } );
  21674. /**
  21675. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21676. * The corners are mapped to `0` and the center to `1`.
  21677. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21678. *
  21679. * @tsl
  21680. * @function
  21681. * @param {Node<float>} x - The value to remap.
  21682. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  21683. * @return {Node<float>} The remapped value.
  21684. */
  21685. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  21686. /**
  21687. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21688. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  21689. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21690. *
  21691. * @tsl
  21692. * @function
  21693. * @param {Node<float>} x - The value to remap.
  21694. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  21695. * @return {Node<float>} The remapped value.
  21696. */
  21697. 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 ) );
  21698. /**
  21699. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21700. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  21701. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21702. *
  21703. * @tsl
  21704. * @function
  21705. * @param {Node<float>} x - The value to remap.
  21706. * @param {Node<float>} a - First control parameter.
  21707. * @param {Node<float>} b - Second control parameter.
  21708. * @return {Node<float>} The remapped value.
  21709. */
  21710. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  21711. /**
  21712. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  21713. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21714. *
  21715. * @tsl
  21716. * @function
  21717. * @param {Node<float>} x - The value to compute the sin for.
  21718. * @param {Node<float>} k - Controls the amount of bounces.
  21719. * @return {Node<float>} The result value.
  21720. */
  21721. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  21722. // https://github.com/cabbibo/glsl-tri-noise-3d
  21723. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  21724. return x.fract().sub( .5 ).abs();
  21725. } ).setLayout( {
  21726. name: 'tri',
  21727. type: 'float',
  21728. inputs: [
  21729. { name: 'x', type: 'float' }
  21730. ]
  21731. } );
  21732. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  21733. 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. ) ) ) ) );
  21734. } ).setLayout( {
  21735. name: 'tri3',
  21736. type: 'vec3',
  21737. inputs: [
  21738. { name: 'p', type: 'vec3' }
  21739. ]
  21740. } );
  21741. /**
  21742. * Generates a noise value from the given position, speed and time parameters.
  21743. *
  21744. * @tsl
  21745. * @function
  21746. * @param {Node<vec3>} position - The position.
  21747. * @param {Node<float>} speed - The speed.
  21748. * @param {Node<float>} time - The time.
  21749. * @return {Node<float>} The generated noise.
  21750. */
  21751. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  21752. const p = vec3( position ).toVar();
  21753. const z = float( 1.4 ).toVar();
  21754. const rz = float( 0.0 ).toVar();
  21755. const bp = vec3( p ).toVar();
  21756. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  21757. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  21758. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  21759. bp.mulAssign( 1.8 );
  21760. z.mulAssign( 1.5 );
  21761. p.mulAssign( 1.2 );
  21762. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  21763. rz.addAssign( t.div( z ) );
  21764. bp.addAssign( 0.14 );
  21765. } );
  21766. return rz;
  21767. } ).setLayout( {
  21768. name: 'triNoise3D',
  21769. type: 'float',
  21770. inputs: [
  21771. { name: 'position', type: 'vec3' },
  21772. { name: 'speed', type: 'float' },
  21773. { name: 'time', type: 'float' }
  21774. ]
  21775. } );
  21776. /**
  21777. * This class allows to define multiple overloaded versions
  21778. * of the same function. Depending on the parameters of the function
  21779. * call, the node picks the best-fit overloaded version.
  21780. *
  21781. * @augments Node
  21782. */
  21783. class FunctionOverloadingNode extends Node {
  21784. static get type() {
  21785. return 'FunctionOverloadingNode';
  21786. }
  21787. /**
  21788. * Constructs a new function overloading node.
  21789. *
  21790. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  21791. * @param {...Node} parametersNodes - A list of parameter nodes.
  21792. */
  21793. constructor( functionNodes = [], ...parametersNodes ) {
  21794. super();
  21795. /**
  21796. * Array of `Fn` function definitions.
  21797. *
  21798. * @type {Array<Function>}
  21799. */
  21800. this.functionNodes = functionNodes;
  21801. /**
  21802. * A list of parameter nodes.
  21803. *
  21804. * @type {Array<Node>}
  21805. */
  21806. this.parametersNodes = parametersNodes;
  21807. /**
  21808. * The selected overloaded function call.
  21809. *
  21810. * @private
  21811. * @type {ShaderCallNodeInternal}
  21812. */
  21813. this._candidateFnCall = null;
  21814. /**
  21815. * This node is marked as global.
  21816. *
  21817. * @type {boolean}
  21818. * @default true
  21819. */
  21820. this.global = true;
  21821. }
  21822. /**
  21823. * This method is overwritten since the node type is inferred from
  21824. * the function's return type.
  21825. *
  21826. * @param {NodeBuilder} builder - The current node builder.
  21827. * @return {string} The node type.
  21828. */
  21829. getNodeType() {
  21830. return this.functionNodes[ 0 ].shaderNode.layout.type;
  21831. }
  21832. setup( builder ) {
  21833. const params = this.parametersNodes;
  21834. let candidateFnCall = this._candidateFnCall;
  21835. if ( candidateFnCall === null ) {
  21836. let candidateFn = null;
  21837. let candidateScore = -1;
  21838. for ( const functionNode of this.functionNodes ) {
  21839. const shaderNode = functionNode.shaderNode;
  21840. const layout = shaderNode.layout;
  21841. if ( layout === null ) {
  21842. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  21843. }
  21844. const inputs = layout.inputs;
  21845. if ( params.length === inputs.length ) {
  21846. let score = 0;
  21847. for ( let i = 0; i < params.length; i ++ ) {
  21848. const param = params[ i ];
  21849. const input = inputs[ i ];
  21850. if ( param.getNodeType( builder ) === input.type ) {
  21851. score ++;
  21852. } else {
  21853. score = 0;
  21854. }
  21855. }
  21856. if ( score > candidateScore ) {
  21857. candidateFn = functionNode;
  21858. candidateScore = score;
  21859. }
  21860. }
  21861. }
  21862. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  21863. }
  21864. return candidateFnCall;
  21865. }
  21866. }
  21867. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  21868. /**
  21869. * TSL function for creating a function overloading node.
  21870. *
  21871. * @tsl
  21872. * @function
  21873. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  21874. * @returns {FunctionOverloadingNode}
  21875. */
  21876. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  21877. /**
  21878. * Represents the elapsed time in seconds.
  21879. *
  21880. * @tsl
  21881. * @type {UniformNode<float>}
  21882. */
  21883. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  21884. /**
  21885. * Represents the delta time in seconds.
  21886. *
  21887. * @tsl
  21888. * @type {UniformNode<float>}
  21889. */
  21890. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  21891. /**
  21892. * Represents the current frame ID.
  21893. *
  21894. * @tsl
  21895. * @type {UniformNode<uint>}
  21896. */
  21897. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  21898. // Deprecated
  21899. /**
  21900. * @tsl
  21901. * @function
  21902. * @deprecated since r170. Use {@link time} instead.
  21903. *
  21904. * @param {number} [timeScale=1] - The time scale.
  21905. * @returns {UniformNode<float>}
  21906. */
  21907. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  21908. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  21909. return time.mul( timeScale );
  21910. };
  21911. /**
  21912. * @tsl
  21913. * @function
  21914. * @deprecated since r170. Use {@link time} instead.
  21915. *
  21916. * @param {number} [timeScale=1] - The time scale.
  21917. * @returns {UniformNode<float>}
  21918. */
  21919. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  21920. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  21921. return time.mul( timeScale );
  21922. };
  21923. /**
  21924. * @tsl
  21925. * @function
  21926. * @deprecated since r170. Use {@link deltaTime} instead.
  21927. *
  21928. * @param {number} [timeScale=1] - The time scale.
  21929. * @returns {UniformNode<float>}
  21930. */
  21931. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  21932. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  21933. return deltaTime.mul( timeScale );
  21934. };
  21935. /**
  21936. * Generates a sine wave oscillation based on a timer.
  21937. *
  21938. * @tsl
  21939. * @function
  21940. * @param {Node<float>} t - The timer to generate the oscillation with.
  21941. * @return {Node<float>} The oscillation node.
  21942. */
  21943. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  21944. /**
  21945. * Generates a square wave oscillation based on a timer.
  21946. *
  21947. * @tsl
  21948. * @function
  21949. * @param {Node<float>} t - The timer to generate the oscillation with.
  21950. * @return {Node<float>} The oscillation node.
  21951. */
  21952. const oscSquare = ( t = time ) => t.fract().round();
  21953. /**
  21954. * Generates a triangle wave oscillation based on a timer.
  21955. *
  21956. * @tsl
  21957. * @function
  21958. * @param {Node<float>} t - The timer to generate the oscillation with.
  21959. * @return {Node<float>} The oscillation node.
  21960. */
  21961. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  21962. /**
  21963. * Generates a sawtooth wave oscillation based on a timer.
  21964. *
  21965. * @tsl
  21966. * @function
  21967. * @param {Node<float>} t - The timer to generate the oscillation with.
  21968. * @return {Node<float>} The oscillation node.
  21969. */
  21970. const oscSawtooth = ( t = time ) => t.fract();
  21971. /**
  21972. * Rotates the given uv coordinates around a center point
  21973. *
  21974. * @tsl
  21975. * @function
  21976. * @param {Node<vec2>} uv - The uv coordinates.
  21977. * @param {Node<float>} rotation - The rotation defined in radians.
  21978. * @param {Node<vec2>} center - The center of rotation
  21979. * @return {Node<vec2>} The rotated uv coordinates.
  21980. */
  21981. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  21982. return rotate( uv.sub( center ), rotation ).add( center );
  21983. } );
  21984. /**
  21985. * Applies a spherical warping effect to the given uv coordinates.
  21986. *
  21987. * @tsl
  21988. * @function
  21989. * @param {Node<vec2>} uv - The uv coordinates.
  21990. * @param {Node<float>} strength - The strength of the effect.
  21991. * @param {Node<vec2>} center - The center point
  21992. * @return {Node<vec2>} The updated uv coordinates.
  21993. */
  21994. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  21995. const delta = uv.sub( center );
  21996. const delta2 = delta.dot( delta );
  21997. const delta4 = delta2.mul( delta2 );
  21998. const deltaOffset = delta4.mul( strength );
  21999. return uv.add( delta.mul( deltaOffset ) );
  22000. } );
  22001. /**
  22002. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  22003. * oriented always towards the camera.
  22004. *
  22005. * ```js
  22006. * material.vertexNode = billboarding();
  22007. * ```
  22008. *
  22009. * @tsl
  22010. * @function
  22011. * @param {Object} config - The configuration object.
  22012. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  22013. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  22014. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  22015. * @return {Node<vec3>} The updated vertex position in clip space.
  22016. */
  22017. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  22018. let worldMatrix;
  22019. if ( position !== null ) {
  22020. worldMatrix = modelWorldMatrix.toVar();
  22021. worldMatrix[ 3 ][ 0 ] = position.x;
  22022. worldMatrix[ 3 ][ 1 ] = position.y;
  22023. worldMatrix[ 3 ][ 2 ] = position.z;
  22024. } else {
  22025. worldMatrix = modelWorldMatrix;
  22026. }
  22027. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  22028. if ( defined( horizontal ) ) {
  22029. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  22030. modelViewMatrix[ 0 ][ 1 ] = 0;
  22031. modelViewMatrix[ 0 ][ 2 ] = 0;
  22032. }
  22033. if ( defined( vertical ) ) {
  22034. modelViewMatrix[ 1 ][ 0 ] = 0;
  22035. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  22036. modelViewMatrix[ 1 ][ 2 ] = 0;
  22037. }
  22038. modelViewMatrix[ 2 ][ 0 ] = 0;
  22039. modelViewMatrix[ 2 ][ 1 ] = 0;
  22040. modelViewMatrix[ 2 ][ 2 ] = 1;
  22041. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22042. } );
  22043. /**
  22044. * A special version of a screen uv function that involves a depth comparison
  22045. * when computing the final uvs. The function mitigates visual errors when
  22046. * using viewport texture nodes for refraction purposes. Without this function
  22047. * objects in front of a refractive surface might appear on the refractive surface
  22048. * which is incorrect.
  22049. *
  22050. * @tsl
  22051. * @function
  22052. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  22053. * @return {Node<vec2>} The update uv coordinates.
  22054. */
  22055. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  22056. const depth = linearDepth();
  22057. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  22058. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  22059. return finalUV;
  22060. } );
  22061. /**
  22062. * Can be used to compute texture coordinates for animated sprite sheets.
  22063. *
  22064. * ```js
  22065. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  22066. *
  22067. * material.colorNode = texture( spriteSheet, uvNode );
  22068. * ```
  22069. *
  22070. * @augments Node
  22071. */
  22072. class SpriteSheetUVNode extends Node {
  22073. static get type() {
  22074. return 'SpriteSheetUVNode';
  22075. }
  22076. /**
  22077. * Constructs a new sprite sheet uv node.
  22078. *
  22079. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22080. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  22081. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22082. */
  22083. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  22084. super( 'vec2' );
  22085. /**
  22086. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22087. *
  22088. * @type {Node<vec2>}
  22089. */
  22090. this.countNode = countNode;
  22091. /**
  22092. * The uv node.
  22093. *
  22094. * @type {Node<vec2>}
  22095. */
  22096. this.uvNode = uvNode;
  22097. /**
  22098. * The node that defines the current frame/sprite.
  22099. *
  22100. * @type {Node<float>}
  22101. */
  22102. this.frameNode = frameNode;
  22103. }
  22104. setup() {
  22105. const { frameNode, uvNode, countNode } = this;
  22106. const { width, height } = countNode;
  22107. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  22108. const column = frameNum.mod( width );
  22109. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  22110. const scale = countNode.reciprocal();
  22111. const uvFrameOffset = vec2( column, row );
  22112. return uvNode.add( uvFrameOffset ).mul( scale );
  22113. }
  22114. }
  22115. /**
  22116. * TSL function for creating a sprite sheet uv node.
  22117. *
  22118. * @tsl
  22119. * @function
  22120. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22121. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  22122. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22123. * @returns {SpriteSheetUVNode}
  22124. */
  22125. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  22126. /**
  22127. * Can be used for triplanar texture mapping.
  22128. *
  22129. * ```js
  22130. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  22131. * ```
  22132. *
  22133. * @augments Node
  22134. */
  22135. class TriplanarTexturesNode extends Node {
  22136. static get type() {
  22137. return 'TriplanarTexturesNode';
  22138. }
  22139. /**
  22140. * Constructs a new triplanar textures node.
  22141. *
  22142. * @param {Node} textureXNode - First texture node.
  22143. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22144. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22145. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22146. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22147. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22148. */
  22149. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  22150. super( 'vec4' );
  22151. /**
  22152. * First texture node.
  22153. *
  22154. * @type {Node}
  22155. */
  22156. this.textureXNode = textureXNode;
  22157. /**
  22158. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22159. *
  22160. * @type {?Node}
  22161. * @default null
  22162. */
  22163. this.textureYNode = textureYNode;
  22164. /**
  22165. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22166. *
  22167. * @type {?Node}
  22168. * @default null
  22169. */
  22170. this.textureZNode = textureZNode;
  22171. /**
  22172. * The scale node.
  22173. *
  22174. * @type {Node<float>}
  22175. * @default float(1)
  22176. */
  22177. this.scaleNode = scaleNode;
  22178. /**
  22179. * Vertex positions in local space.
  22180. *
  22181. * @type {Node<vec3>}
  22182. * @default positionLocal
  22183. */
  22184. this.positionNode = positionNode;
  22185. /**
  22186. * Normals in local space.
  22187. *
  22188. * @type {Node<vec3>}
  22189. * @default normalLocal
  22190. */
  22191. this.normalNode = normalNode;
  22192. }
  22193. setup() {
  22194. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  22195. // Ref: https://github.com/keijiro/StandardTriplanar
  22196. // Blending factor of triplanar mapping
  22197. let bf = normalNode.abs().normalize();
  22198. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  22199. // Triplanar mapping
  22200. const tx = positionNode.yz.mul( scaleNode );
  22201. const ty = positionNode.zx.mul( scaleNode );
  22202. const tz = positionNode.xy.mul( scaleNode );
  22203. // Base color
  22204. const textureX = textureXNode.value;
  22205. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  22206. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  22207. const cx = texture( textureX, tx ).mul( bf.x );
  22208. const cy = texture( textureY, ty ).mul( bf.y );
  22209. const cz = texture( textureZ, tz ).mul( bf.z );
  22210. return add( cx, cy, cz );
  22211. }
  22212. }
  22213. /**
  22214. * TSL function for creating a triplanar textures node.
  22215. *
  22216. * @tsl
  22217. * @function
  22218. * @param {Node} textureXNode - First texture node.
  22219. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22220. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22221. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22222. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22223. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22224. * @returns {TriplanarTexturesNode}
  22225. */
  22226. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ).setParameterLength( 1, 6 );
  22227. /**
  22228. * TSL function for creating a triplanar textures node.
  22229. *
  22230. * @tsl
  22231. * @function
  22232. * @param {Node} textureXNode - First texture node.
  22233. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22234. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22235. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22236. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22237. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22238. * @returns {TriplanarTexturesNode}
  22239. */
  22240. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  22241. const _reflectorPlane = new Plane();
  22242. const _normal = new Vector3();
  22243. const _reflectorWorldPosition = new Vector3();
  22244. const _cameraWorldPosition = new Vector3();
  22245. const _rotationMatrix = new Matrix4();
  22246. const _lookAtPosition = new Vector3( 0, 0, -1 );
  22247. const clipPlane = new Vector4();
  22248. const _view = new Vector3();
  22249. const _target = new Vector3();
  22250. const _q = new Vector4();
  22251. const _size$2 = new Vector2();
  22252. const _defaultRT = new RenderTarget();
  22253. const _defaultUV = screenUV.flipX();
  22254. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  22255. let _inReflector = false;
  22256. /**
  22257. * This node can be used to implement mirror-like flat reflective surfaces.
  22258. *
  22259. * ```js
  22260. * const groundReflector = reflector();
  22261. * material.colorNode = groundReflector;
  22262. *
  22263. * const plane = new Mesh( geometry, material );
  22264. * plane.add( groundReflector.target );
  22265. * ```
  22266. *
  22267. * @augments TextureNode
  22268. */
  22269. class ReflectorNode extends TextureNode {
  22270. static get type() {
  22271. return 'ReflectorNode';
  22272. }
  22273. /**
  22274. * Constructs a new reflector node.
  22275. *
  22276. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22277. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22278. * @param {number} [parameters.resolution=1] - The resolution scale.
  22279. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22280. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22281. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22282. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22283. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22284. */
  22285. constructor( parameters = {} ) {
  22286. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  22287. /**
  22288. * A reference to the internal reflector base node which holds the actual implementation.
  22289. *
  22290. * @private
  22291. * @type {ReflectorBaseNode}
  22292. * @default ReflectorBaseNode
  22293. */
  22294. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  22295. /**
  22296. * A reference to the internal depth node.
  22297. *
  22298. * @private
  22299. * @type {?Node}
  22300. * @default null
  22301. */
  22302. this._depthNode = null;
  22303. this.setUpdateMatrix( false );
  22304. }
  22305. /**
  22306. * A reference to the internal reflector node.
  22307. *
  22308. * @type {ReflectorBaseNode}
  22309. */
  22310. get reflector() {
  22311. return this._reflectorBaseNode;
  22312. }
  22313. /**
  22314. * A reference to 3D object the reflector is linked to.
  22315. *
  22316. * @type {Object3D}
  22317. */
  22318. get target() {
  22319. return this._reflectorBaseNode.target;
  22320. }
  22321. /**
  22322. * Returns a node representing the mirror's depth. That can be used
  22323. * to implement more advanced reflection effects like distance attenuation.
  22324. *
  22325. * @return {Node} The depth node.
  22326. */
  22327. getDepthNode() {
  22328. if ( this._depthNode === null ) {
  22329. if ( this._reflectorBaseNode.depth !== true ) {
  22330. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  22331. }
  22332. this._depthNode = nodeObject( new ReflectorNode( {
  22333. defaultTexture: _defaultRT.depthTexture,
  22334. reflector: this._reflectorBaseNode
  22335. } ) );
  22336. }
  22337. return this._depthNode;
  22338. }
  22339. setup( builder ) {
  22340. // ignore if used in post-processing
  22341. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  22342. return super.setup( builder );
  22343. }
  22344. clone() {
  22345. const texture = new this.constructor( this.reflectorNode );
  22346. texture._reflectorBaseNode = this._reflectorBaseNode;
  22347. return texture;
  22348. }
  22349. /**
  22350. * Frees internal resources. Should be called when the node is no longer in use.
  22351. */
  22352. dispose() {
  22353. super.dispose();
  22354. this._reflectorBaseNode.dispose();
  22355. }
  22356. }
  22357. /**
  22358. * Holds the actual implementation of the reflector.
  22359. *
  22360. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  22361. * in `ReflectorNode`, see #29619.
  22362. *
  22363. * @private
  22364. * @augments Node
  22365. */
  22366. class ReflectorBaseNode extends Node {
  22367. static get type() {
  22368. return 'ReflectorBaseNode';
  22369. }
  22370. /**
  22371. * Constructs a new reflector base node.
  22372. *
  22373. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  22374. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22375. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22376. * @param {number} [parameters.resolution=1] - The resolution scale.
  22377. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22378. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22379. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22380. */
  22381. constructor( textureNode, parameters = {} ) {
  22382. super();
  22383. const {
  22384. target = new Object3D(),
  22385. resolution = 1,
  22386. generateMipmaps = false,
  22387. bounces = true,
  22388. depth = false
  22389. } = parameters;
  22390. /**
  22391. * Represents the rendered reflections as a texture node.
  22392. *
  22393. * @type {TextureNode}
  22394. */
  22395. this.textureNode = textureNode;
  22396. /**
  22397. * The 3D object the reflector is linked to.
  22398. *
  22399. * @type {Object3D}
  22400. * @default {new Object3D()}
  22401. */
  22402. this.target = target;
  22403. /**
  22404. * The resolution scale.
  22405. *
  22406. * @type {number}
  22407. * @default {1}
  22408. */
  22409. this.resolution = resolution;
  22410. /**
  22411. * Whether mipmaps should be generated or not.
  22412. *
  22413. * @type {boolean}
  22414. * @default {false}
  22415. */
  22416. this.generateMipmaps = generateMipmaps;
  22417. /**
  22418. * Whether reflectors can render other reflector nodes or not.
  22419. *
  22420. * @type {boolean}
  22421. * @default {true}
  22422. */
  22423. this.bounces = bounces;
  22424. /**
  22425. * Whether depth data should be generated or not.
  22426. *
  22427. * @type {boolean}
  22428. * @default {false}
  22429. */
  22430. this.depth = depth;
  22431. /**
  22432. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  22433. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  22434. *
  22435. * @type {string}
  22436. * @default 'render'
  22437. */
  22438. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  22439. /**
  22440. * Weak map for managing virtual cameras.
  22441. *
  22442. * @type {WeakMap<Camera, Camera>}
  22443. */
  22444. this.virtualCameras = new WeakMap();
  22445. /**
  22446. * Weak map for managing render targets.
  22447. *
  22448. * @type {Map<Camera, RenderTarget>}
  22449. */
  22450. this.renderTargets = new Map();
  22451. /**
  22452. * Force render even if reflector is facing away from camera.
  22453. *
  22454. * @type {boolean}
  22455. * @default {false}
  22456. */
  22457. this.forceUpdate = false;
  22458. }
  22459. /**
  22460. * Updates the resolution of the internal render target.
  22461. *
  22462. * @private
  22463. * @param {RenderTarget} renderTarget - The render target to resize.
  22464. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  22465. */
  22466. _updateResolution( renderTarget, renderer ) {
  22467. const resolution = this.resolution;
  22468. renderer.getDrawingBufferSize( _size$2 );
  22469. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  22470. }
  22471. setup( builder ) {
  22472. this._updateResolution( _defaultRT, builder.renderer );
  22473. return super.setup( builder );
  22474. }
  22475. /**
  22476. * Frees internal resources. Should be called when the node is no longer in use.
  22477. */
  22478. dispose() {
  22479. super.dispose();
  22480. for ( const renderTarget of this.renderTargets.values() ) {
  22481. renderTarget.dispose();
  22482. }
  22483. }
  22484. /**
  22485. * Returns a virtual camera for the given camera. The virtual camera is used to
  22486. * render the scene from the reflector's view so correct reflections can be produced.
  22487. *
  22488. * @param {Camera} camera - The scene's camera.
  22489. * @return {Camera} The corresponding virtual camera.
  22490. */
  22491. getVirtualCamera( camera ) {
  22492. let virtualCamera = this.virtualCameras.get( camera );
  22493. if ( virtualCamera === undefined ) {
  22494. virtualCamera = camera.clone();
  22495. this.virtualCameras.set( camera, virtualCamera );
  22496. }
  22497. return virtualCamera;
  22498. }
  22499. /**
  22500. * Returns a render target for the given camera. The reflections are rendered
  22501. * into this render target.
  22502. *
  22503. * @param {Camera} camera - The scene's camera.
  22504. * @return {RenderTarget} The render target.
  22505. */
  22506. getRenderTarget( camera ) {
  22507. let renderTarget = this.renderTargets.get( camera );
  22508. if ( renderTarget === undefined ) {
  22509. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  22510. if ( this.generateMipmaps === true ) {
  22511. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  22512. renderTarget.texture.generateMipmaps = true;
  22513. }
  22514. if ( this.depth === true ) {
  22515. renderTarget.depthTexture = new DepthTexture();
  22516. }
  22517. this.renderTargets.set( camera, renderTarget );
  22518. }
  22519. return renderTarget;
  22520. }
  22521. updateBefore( frame ) {
  22522. if ( this.bounces === false && _inReflector ) return false;
  22523. _inReflector = true;
  22524. const { scene, camera, renderer, material } = frame;
  22525. const { target } = this;
  22526. const virtualCamera = this.getVirtualCamera( camera );
  22527. const renderTarget = this.getRenderTarget( virtualCamera );
  22528. renderer.getDrawingBufferSize( _size$2 );
  22529. this._updateResolution( renderTarget, renderer );
  22530. //
  22531. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  22532. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  22533. _rotationMatrix.extractRotation( target.matrixWorld );
  22534. _normal.set( 0, 0, 1 );
  22535. _normal.applyMatrix4( _rotationMatrix );
  22536. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  22537. // Avoid rendering when reflector is facing away unless forcing an update
  22538. const isFacingAway = _view.dot( _normal ) > 0;
  22539. if ( isFacingAway === true && this.forceUpdate === false ) return;
  22540. _view.reflect( _normal ).negate();
  22541. _view.add( _reflectorWorldPosition );
  22542. _rotationMatrix.extractRotation( camera.matrixWorld );
  22543. _lookAtPosition.set( 0, 0, -1 );
  22544. _lookAtPosition.applyMatrix4( _rotationMatrix );
  22545. _lookAtPosition.add( _cameraWorldPosition );
  22546. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  22547. _target.reflect( _normal ).negate();
  22548. _target.add( _reflectorWorldPosition );
  22549. //
  22550. virtualCamera.coordinateSystem = camera.coordinateSystem;
  22551. virtualCamera.position.copy( _view );
  22552. virtualCamera.up.set( 0, 1, 0 );
  22553. virtualCamera.up.applyMatrix4( _rotationMatrix );
  22554. virtualCamera.up.reflect( _normal );
  22555. virtualCamera.lookAt( _target );
  22556. virtualCamera.near = camera.near;
  22557. virtualCamera.far = camera.far;
  22558. virtualCamera.updateMatrixWorld();
  22559. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  22560. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  22561. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  22562. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  22563. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  22564. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  22565. const projectionMatrix = virtualCamera.projectionMatrix;
  22566. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  22567. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  22568. _q.z = -1;
  22569. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  22570. // Calculate the scaled plane vector
  22571. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  22572. const clipBias = 0;
  22573. // Replacing the third row of the projection matrix
  22574. projectionMatrix.elements[ 2 ] = clipPlane.x;
  22575. projectionMatrix.elements[ 6 ] = clipPlane.y;
  22576. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  22577. projectionMatrix.elements[ 14 ] = clipPlane.w;
  22578. //
  22579. this.textureNode.value = renderTarget.texture;
  22580. if ( this.depth === true ) {
  22581. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  22582. }
  22583. material.visible = false;
  22584. const currentRenderTarget = renderer.getRenderTarget();
  22585. const currentMRT = renderer.getMRT();
  22586. const currentAutoClear = renderer.autoClear;
  22587. renderer.setMRT( null );
  22588. renderer.setRenderTarget( renderTarget );
  22589. renderer.autoClear = true;
  22590. renderer.render( scene, virtualCamera );
  22591. renderer.setMRT( currentMRT );
  22592. renderer.setRenderTarget( currentRenderTarget );
  22593. renderer.autoClear = currentAutoClear;
  22594. material.visible = true;
  22595. _inReflector = false;
  22596. this.forceUpdate = false;
  22597. }
  22598. }
  22599. /**
  22600. * TSL function for creating a reflector node.
  22601. *
  22602. * @tsl
  22603. * @function
  22604. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22605. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22606. * @param {number} [parameters.resolution=1] - The resolution scale.
  22607. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22608. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22609. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22610. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22611. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22612. * @returns {ReflectorNode}
  22613. */
  22614. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  22615. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  22616. /**
  22617. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  22618. *
  22619. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  22620. *
  22621. * @private
  22622. * @augments BufferGeometry
  22623. */
  22624. class QuadGeometry extends BufferGeometry {
  22625. /**
  22626. * Constructs a new quad geometry.
  22627. *
  22628. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  22629. */
  22630. constructor( flipY = false ) {
  22631. super();
  22632. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  22633. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  22634. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  22635. }
  22636. }
  22637. const _geometry = /*@__PURE__*/ new QuadGeometry();
  22638. /**
  22639. * This module is a helper for passes which need to render a full
  22640. * screen effect which is quite common in context of post processing.
  22641. *
  22642. * The intended usage is to reuse a single quad mesh for rendering
  22643. * subsequent passes by just reassigning the `material` reference.
  22644. *
  22645. * Note: This module can only be used with `WebGPURenderer`.
  22646. *
  22647. * @augments Mesh
  22648. */
  22649. class QuadMesh extends Mesh {
  22650. /**
  22651. * Constructs a new quad mesh.
  22652. *
  22653. * @param {?Material} [material=null] - The material to render the quad mesh with.
  22654. */
  22655. constructor( material = null ) {
  22656. super( _geometry, material );
  22657. /**
  22658. * The camera to render the quad mesh with.
  22659. *
  22660. * @type {OrthographicCamera}
  22661. * @readonly
  22662. */
  22663. this.camera = _camera;
  22664. /**
  22665. * This flag can be used for type testing.
  22666. *
  22667. * @type {boolean}
  22668. * @readonly
  22669. * @default true
  22670. */
  22671. this.isQuadMesh = true;
  22672. }
  22673. /**
  22674. * Async version of `render()`.
  22675. *
  22676. * @async
  22677. * @param {Renderer} renderer - The renderer.
  22678. * @return {Promise} A Promise that resolves when the render has been finished.
  22679. */
  22680. async renderAsync( renderer ) {
  22681. return renderer.renderAsync( this, _camera );
  22682. }
  22683. /**
  22684. * Renders the quad mesh
  22685. *
  22686. * @param {Renderer} renderer - The renderer.
  22687. */
  22688. render( renderer ) {
  22689. renderer.render( this, _camera );
  22690. }
  22691. }
  22692. const _size$1 = /*@__PURE__*/ new Vector2();
  22693. /**
  22694. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  22695. * This module is especially relevant in context of post processing where certain nodes require
  22696. * texture input for their effects. With the helper function `convertToTexture()` which is based
  22697. * on this module, the node system can automatically ensure texture input if required.
  22698. *
  22699. * @augments TextureNode
  22700. */
  22701. class RTTNode extends TextureNode {
  22702. static get type() {
  22703. return 'RTTNode';
  22704. }
  22705. /**
  22706. * Constructs a new RTT node.
  22707. *
  22708. * @param {Node} node - The node to render a texture with.
  22709. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  22710. * @param {?number} [height=null] - The height of the internal render target.
  22711. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  22712. */
  22713. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  22714. const renderTarget = new RenderTarget( width, height, options );
  22715. super( renderTarget.texture, uv() );
  22716. /**
  22717. * The node to render a texture with.
  22718. *
  22719. * @type {Node}
  22720. */
  22721. this.node = node;
  22722. /**
  22723. * The width of the internal render target.
  22724. * If not width is applied, the render target is automatically resized.
  22725. *
  22726. * @type {?number}
  22727. * @default null
  22728. */
  22729. this.width = width;
  22730. /**
  22731. * The height of the internal render target.
  22732. *
  22733. * @type {?number}
  22734. * @default null
  22735. */
  22736. this.height = height;
  22737. /**
  22738. * The pixel ratio
  22739. *
  22740. * @type {number}
  22741. * @default 1
  22742. */
  22743. this.pixelRatio = 1;
  22744. /**
  22745. * The render target
  22746. *
  22747. * @type {RenderTarget}
  22748. */
  22749. this.renderTarget = renderTarget;
  22750. /**
  22751. * Whether the texture requires an update or not.
  22752. *
  22753. * @type {boolean}
  22754. * @default true
  22755. */
  22756. this.textureNeedsUpdate = true;
  22757. /**
  22758. * Whether the texture should automatically be updated or not.
  22759. *
  22760. * @type {boolean}
  22761. * @default true
  22762. */
  22763. this.autoUpdate = true;
  22764. /**
  22765. * The node which is used with the quad mesh for RTT.
  22766. *
  22767. * @private
  22768. * @type {Node}
  22769. * @default null
  22770. */
  22771. this._rttNode = null;
  22772. /**
  22773. * The internal quad mesh for RTT.
  22774. *
  22775. * @private
  22776. * @type {QuadMesh}
  22777. */
  22778. this._quadMesh = new QuadMesh( new NodeMaterial() );
  22779. /**
  22780. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  22781. * the texture once per render in its {@link RTTNode#updateBefore} method.
  22782. *
  22783. * @type {string}
  22784. * @default 'render'
  22785. */
  22786. this.updateBeforeType = NodeUpdateType.RENDER;
  22787. }
  22788. /**
  22789. * Whether the internal render target should automatically be resized or not.
  22790. *
  22791. * @type {boolean}
  22792. * @readonly
  22793. * @default true
  22794. */
  22795. get autoSize() {
  22796. return this.width === null;
  22797. }
  22798. setup( builder ) {
  22799. this._rttNode = this.node.context( builder.getSharedContext() );
  22800. this._quadMesh.material.name = 'RTT';
  22801. this._quadMesh.material.needsUpdate = true;
  22802. return super.setup( builder );
  22803. }
  22804. /**
  22805. * Sets the size of the internal render target
  22806. *
  22807. * @param {number} width - The width to set.
  22808. * @param {number} height - The width to set.
  22809. */
  22810. setSize( width, height ) {
  22811. this.width = width;
  22812. this.height = height;
  22813. const effectiveWidth = width * this.pixelRatio;
  22814. const effectiveHeight = height * this.pixelRatio;
  22815. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22816. this.textureNeedsUpdate = true;
  22817. }
  22818. /**
  22819. * Sets the pixel ratio. This will also resize the render target.
  22820. *
  22821. * @param {number} pixelRatio - The pixel ratio to set.
  22822. */
  22823. setPixelRatio( pixelRatio ) {
  22824. this.pixelRatio = pixelRatio;
  22825. this.setSize( this.width, this.height );
  22826. }
  22827. updateBefore( { renderer } ) {
  22828. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  22829. this.textureNeedsUpdate = false;
  22830. //
  22831. if ( this.autoSize === true ) {
  22832. this.pixelRatio = renderer.getPixelRatio();
  22833. const size = renderer.getSize( _size$1 );
  22834. this.setSize( size.width, size.height );
  22835. }
  22836. //
  22837. this._quadMesh.material.fragmentNode = this._rttNode;
  22838. //
  22839. const currentRenderTarget = renderer.getRenderTarget();
  22840. renderer.setRenderTarget( this.renderTarget );
  22841. this._quadMesh.render( renderer );
  22842. renderer.setRenderTarget( currentRenderTarget );
  22843. }
  22844. clone() {
  22845. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  22846. newNode.sampler = this.sampler;
  22847. newNode.referenceNode = this;
  22848. return newNode;
  22849. }
  22850. }
  22851. /**
  22852. * TSL function for creating a RTT node.
  22853. *
  22854. * @tsl
  22855. * @function
  22856. * @param {Node} node - The node to render a texture with.
  22857. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  22858. * @param {?number} [height=null] - The height of the internal render target.
  22859. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  22860. * @returns {RTTNode}
  22861. */
  22862. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  22863. /**
  22864. * TSL function for converting nodes to textures nodes.
  22865. *
  22866. * @tsl
  22867. * @function
  22868. * @param {Node} node - The node to render a texture with.
  22869. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  22870. * @param {?number} [height=null] - The height of the internal render target.
  22871. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  22872. * @returns {RTTNode}
  22873. */
  22874. const convertToTexture = ( node, ...params ) => {
  22875. if ( node.isTextureNode ) return node;
  22876. if ( node.isPassNode ) return node.getTextureNode();
  22877. return rtt( node, ...params );
  22878. };
  22879. /**
  22880. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  22881. * depth value and the camera's inverse projection matrix.
  22882. *
  22883. * @tsl
  22884. * @function
  22885. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  22886. * @param {Node<float>} depth - The fragment's depth value.
  22887. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  22888. * @return {Node<vec3>} The fragments position in view space.
  22889. */
  22890. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  22891. let clipSpacePosition;
  22892. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  22893. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  22894. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  22895. } else {
  22896. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  22897. }
  22898. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  22899. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  22900. } );
  22901. /**
  22902. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  22903. * and the camera's projection matrix
  22904. *
  22905. * @tsl
  22906. * @function
  22907. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  22908. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  22909. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  22910. */
  22911. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  22912. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  22913. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  22914. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  22915. } );
  22916. /**
  22917. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  22918. * target is available or if flat surface normals are required.
  22919. *
  22920. * @tsl
  22921. * @function
  22922. * @param {Node<vec2>} uv - The texture coordinate.
  22923. * @param {DepthTexture} depthTexture - The depth texture.
  22924. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  22925. * @return {Node<vec3>} The computed normal vector.
  22926. */
  22927. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  22928. const size = textureSize( textureLoad( depthTexture ) );
  22929. const p = ivec2( uv.mul( size ) ).toVar();
  22930. const c0 = textureLoad( depthTexture, p ).toVar();
  22931. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  22932. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  22933. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  22934. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  22935. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  22936. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  22937. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  22938. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  22939. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  22940. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  22941. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  22942. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  22943. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  22944. 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 ) ) );
  22945. 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 ) ) );
  22946. return normalize( cross( dpdx, dpdy ) );
  22947. } );
  22948. /**
  22949. * This special type of instanced buffer attribute is intended for compute shaders.
  22950. * In earlier three.js versions it was only possible to update attribute data
  22951. * on the CPU via JavaScript and then upload the data to the GPU. With the
  22952. * new material system and renderer it is now possible to use compute shaders
  22953. * to compute the data for an attribute more efficiently on the GPU.
  22954. *
  22955. * The idea is to create an instance of this class and provide it as an input
  22956. * to {@link StorageBufferNode}.
  22957. *
  22958. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  22959. *
  22960. * @augments InstancedBufferAttribute
  22961. */
  22962. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  22963. /**
  22964. * Constructs a new storage instanced buffer attribute.
  22965. *
  22966. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  22967. * The subsequent parameters are then obsolete.
  22968. * @param {number} itemSize - The item size.
  22969. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  22970. */
  22971. constructor( count, itemSize, typeClass = Float32Array ) {
  22972. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  22973. super( array, itemSize );
  22974. /**
  22975. * This flag can be used for type testing.
  22976. *
  22977. * @type {boolean}
  22978. * @readonly
  22979. * @default true
  22980. */
  22981. this.isStorageInstancedBufferAttribute = true;
  22982. }
  22983. }
  22984. /**
  22985. * This special type of buffer attribute is intended for compute shaders.
  22986. * In earlier three.js versions it was only possible to update attribute data
  22987. * on the CPU via JavaScript and then upload the data to the GPU. With the
  22988. * new material system and renderer it is now possible to use compute shaders
  22989. * to compute the data for an attribute more efficiently on the GPU.
  22990. *
  22991. * The idea is to create an instance of this class and provide it as an input
  22992. * to {@link StorageBufferNode}.
  22993. *
  22994. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  22995. *
  22996. * @augments BufferAttribute
  22997. */
  22998. class StorageBufferAttribute extends BufferAttribute {
  22999. /**
  23000. * Constructs a new storage buffer attribute.
  23001. *
  23002. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23003. * The subsequent parameters are then obsolete.
  23004. * @param {number} itemSize - The item size.
  23005. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23006. */
  23007. constructor( count, itemSize, typeClass = Float32Array ) {
  23008. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23009. super( array, itemSize );
  23010. /**
  23011. * This flag can be used for type testing.
  23012. *
  23013. * @type {boolean}
  23014. * @readonly
  23015. * @default true
  23016. */
  23017. this.isStorageBufferAttribute = true;
  23018. }
  23019. }
  23020. /**
  23021. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  23022. *
  23023. * @tsl
  23024. * @function
  23025. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23026. * @param {string|Struct} [type='float'] - The data type.
  23027. * @returns {StorageBufferNode}
  23028. */
  23029. const attributeArray = ( count, type = 'float' ) => {
  23030. let itemSize, typedArray;
  23031. if ( type.isStruct === true ) {
  23032. itemSize = type.layout.getLength();
  23033. typedArray = getTypedArrayFromType( 'float' );
  23034. } else {
  23035. itemSize = getLengthFromType( type );
  23036. typedArray = getTypedArrayFromType( type );
  23037. }
  23038. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  23039. const node = storage( buffer, type, count );
  23040. return node;
  23041. };
  23042. /**
  23043. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  23044. *
  23045. * @tsl
  23046. * @function
  23047. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23048. * @param {string|Struct} [type='float'] - The data type.
  23049. * @returns {StorageBufferNode}
  23050. */
  23051. const instancedArray = ( count, type = 'float' ) => {
  23052. let itemSize, typedArray;
  23053. if ( type.isStruct === true ) {
  23054. itemSize = type.layout.getLength();
  23055. typedArray = getTypedArrayFromType( 'float' );
  23056. } else {
  23057. itemSize = getLengthFromType( type );
  23058. typedArray = getTypedArrayFromType( type );
  23059. }
  23060. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  23061. const node = storage( buffer, type, count );
  23062. return node;
  23063. };
  23064. /**
  23065. * A node for representing the uv coordinates of points.
  23066. *
  23067. * Can only be used with a WebGL backend. In WebGPU, point
  23068. * primitives always have the size of one pixel and can thus
  23069. * can't be used as sprite-like objects that display textures.
  23070. *
  23071. * @augments Node
  23072. */
  23073. class PointUVNode extends Node {
  23074. static get type() {
  23075. return 'PointUVNode';
  23076. }
  23077. /**
  23078. * Constructs a new point uv node.
  23079. */
  23080. constructor() {
  23081. super( 'vec2' );
  23082. /**
  23083. * This flag can be used for type testing.
  23084. *
  23085. * @type {boolean}
  23086. * @readonly
  23087. * @default true
  23088. */
  23089. this.isPointUVNode = true;
  23090. }
  23091. generate( /*builder*/ ) {
  23092. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  23093. }
  23094. }
  23095. /**
  23096. * TSL object that represents the uv coordinates of points.
  23097. *
  23098. * @tsl
  23099. * @type {PointUVNode}
  23100. */
  23101. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  23102. const _e1 = /*@__PURE__*/ new Euler();
  23103. const _m1 = /*@__PURE__*/ new Matrix4();
  23104. /**
  23105. * This module allows access to a collection of scene properties. The following predefined TSL objects
  23106. * are available for easier use:
  23107. *
  23108. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  23109. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  23110. * - `backgroundRotation`: A node that represents the scene's background rotation.
  23111. *
  23112. * @augments Node
  23113. */
  23114. class SceneNode extends Node {
  23115. static get type() {
  23116. return 'SceneNode';
  23117. }
  23118. /**
  23119. * Constructs a new scene node.
  23120. *
  23121. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  23122. * @param {?Scene} [scene=null] - A reference to the scene.
  23123. */
  23124. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  23125. super();
  23126. /**
  23127. * The scope defines the type of scene property that is accessed.
  23128. *
  23129. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  23130. */
  23131. this.scope = scope;
  23132. /**
  23133. * A reference to the scene that is going to be accessed.
  23134. *
  23135. * @type {?Scene}
  23136. * @default null
  23137. */
  23138. this.scene = scene;
  23139. }
  23140. /**
  23141. * Depending on the scope, the method returns a different type of node that represents
  23142. * the respective scene property.
  23143. *
  23144. * @param {NodeBuilder} builder - The current node builder.
  23145. * @return {Node} The output node.
  23146. */
  23147. setup( builder ) {
  23148. const scope = this.scope;
  23149. const scene = this.scene !== null ? this.scene : builder.scene;
  23150. let output;
  23151. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  23152. output = reference( 'backgroundBlurriness', 'float', scene );
  23153. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  23154. output = reference( 'backgroundIntensity', 'float', scene );
  23155. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  23156. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  23157. const background = scene.background;
  23158. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  23159. _e1.copy( scene.backgroundRotation );
  23160. // accommodate left-handed frame
  23161. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  23162. _m1.makeRotationFromEuler( _e1 );
  23163. } else {
  23164. _m1.identity();
  23165. }
  23166. return _m1;
  23167. } );
  23168. } else {
  23169. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  23170. }
  23171. return output;
  23172. }
  23173. }
  23174. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  23175. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  23176. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  23177. /**
  23178. * TSL object that represents the scene's background blurriness.
  23179. *
  23180. * @tsl
  23181. * @type {SceneNode}
  23182. */
  23183. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  23184. /**
  23185. * TSL object that represents the scene's background intensity.
  23186. *
  23187. * @tsl
  23188. * @type {SceneNode}
  23189. */
  23190. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  23191. /**
  23192. * TSL object that represents the scene's background rotation.
  23193. *
  23194. * @tsl
  23195. * @type {SceneNode}
  23196. */
  23197. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  23198. /**
  23199. * This special version of a texture node can be used to
  23200. * write data into a storage texture with a compute shader.
  23201. *
  23202. * ```js
  23203. * const storageTexture = new THREE.StorageTexture( width, height );
  23204. *
  23205. * const computeTexture = Fn( ( { storageTexture } ) => {
  23206. *
  23207. * const posX = instanceIndex.mod( width );
  23208. * const posY = instanceIndex.div( width );
  23209. * const indexUV = uvec2( posX, posY );
  23210. *
  23211. * // generate RGB values
  23212. *
  23213. * const r = 1;
  23214. * const g = 1;
  23215. * const b = 1;
  23216. *
  23217. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  23218. *
  23219. * } );
  23220. *
  23221. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  23222. * renderer.computeAsync( computeNode );
  23223. * ```
  23224. *
  23225. * This node can only be used with a WebGPU backend.
  23226. *
  23227. * @augments TextureNode
  23228. */
  23229. class StorageTextureNode extends TextureNode {
  23230. static get type() {
  23231. return 'StorageTextureNode';
  23232. }
  23233. /**
  23234. * Constructs a new storage texture node.
  23235. *
  23236. * @param {StorageTexture} value - The storage texture.
  23237. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23238. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23239. */
  23240. constructor( value, uvNode, storeNode = null ) {
  23241. super( value, uvNode );
  23242. /**
  23243. * The value node that should be stored in the texture.
  23244. *
  23245. * @type {?Node}
  23246. * @default null
  23247. */
  23248. this.storeNode = storeNode;
  23249. /**
  23250. * This flag can be used for type testing.
  23251. *
  23252. * @type {boolean}
  23253. * @readonly
  23254. * @default true
  23255. */
  23256. this.isStorageTextureNode = true;
  23257. /**
  23258. * The access type of the texture node.
  23259. *
  23260. * @type {string}
  23261. * @default 'writeOnly'
  23262. */
  23263. this.access = NodeAccess.WRITE_ONLY;
  23264. }
  23265. /**
  23266. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  23267. *
  23268. * @param {NodeBuilder} builder - The current node builder.
  23269. * @return {string} The input type.
  23270. */
  23271. getInputType( /*builder*/ ) {
  23272. return 'storageTexture';
  23273. }
  23274. setup( builder ) {
  23275. super.setup( builder );
  23276. const properties = builder.getNodeProperties( this );
  23277. properties.storeNode = this.storeNode;
  23278. return properties;
  23279. }
  23280. /**
  23281. * Defines the node access.
  23282. *
  23283. * @param {string} value - The node access.
  23284. * @return {StorageTextureNode} A reference to this node.
  23285. */
  23286. setAccess( value ) {
  23287. this.access = value;
  23288. return this;
  23289. }
  23290. /**
  23291. * Generates the code snippet of the storage node. If no `storeNode`
  23292. * is defined, the texture node is generated as normal texture.
  23293. *
  23294. * @param {NodeBuilder} builder - The current node builder.
  23295. * @param {string} output - The current output.
  23296. * @return {string} The generated code snippet.
  23297. */
  23298. generate( builder, output ) {
  23299. let snippet;
  23300. if ( this.storeNode !== null ) {
  23301. snippet = this.generateStore( builder );
  23302. } else {
  23303. snippet = super.generate( builder, output );
  23304. }
  23305. return snippet;
  23306. }
  23307. /**
  23308. * Convenience method for configuring a read/write node access.
  23309. *
  23310. * @return {StorageTextureNode} A reference to this node.
  23311. */
  23312. toReadWrite() {
  23313. return this.setAccess( NodeAccess.READ_WRITE );
  23314. }
  23315. /**
  23316. * Convenience method for configuring a read-only node access.
  23317. *
  23318. * @return {StorageTextureNode} A reference to this node.
  23319. */
  23320. toReadOnly() {
  23321. return this.setAccess( NodeAccess.READ_ONLY );
  23322. }
  23323. /**
  23324. * Convenience method for configuring a write-only node access.
  23325. *
  23326. * @return {StorageTextureNode} A reference to this node.
  23327. */
  23328. toWriteOnly() {
  23329. return this.setAccess( NodeAccess.WRITE_ONLY );
  23330. }
  23331. /**
  23332. * Generates the code snippet of the storage texture node.
  23333. *
  23334. * @param {NodeBuilder} builder - The current node builder.
  23335. */
  23336. generateStore( builder ) {
  23337. const properties = builder.getNodeProperties( this );
  23338. const { uvNode, storeNode, depthNode } = properties;
  23339. const textureProperty = super.generate( builder, 'property' );
  23340. const uvSnippet = uvNode.build( builder, 'uvec2' );
  23341. const storeSnippet = storeNode.build( builder, 'vec4' );
  23342. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  23343. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  23344. builder.addLineFlowCode( snippet, this );
  23345. }
  23346. clone() {
  23347. const newNode = super.clone();
  23348. newNode.storeNode = this.storeNode;
  23349. return newNode;
  23350. }
  23351. }
  23352. /**
  23353. * TSL function for creating a storage texture node.
  23354. *
  23355. * @tsl
  23356. * @function
  23357. * @param {StorageTexture} value - The storage texture.
  23358. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  23359. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23360. * @returns {StorageTextureNode}
  23361. */
  23362. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  23363. /**
  23364. * TODO: Explain difference to `storageTexture()`.
  23365. *
  23366. * @tsl
  23367. * @function
  23368. * @param {StorageTexture} value - The storage texture.
  23369. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23370. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23371. * @returns {StorageTextureNode}
  23372. */
  23373. const textureStore = ( value, uvNode, storeNode ) => {
  23374. const node = storageTexture( value, uvNode, storeNode );
  23375. if ( storeNode !== null ) node.toStack();
  23376. return node;
  23377. };
  23378. const normal = Fn( ( { texture, uv } ) => {
  23379. const epsilon = 0.0001;
  23380. const ret = vec3().toVar();
  23381. If( uv.x.lessThan( epsilon ), () => {
  23382. ret.assign( vec3( 1, 0, 0 ) );
  23383. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  23384. ret.assign( vec3( 0, 1, 0 ) );
  23385. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  23386. ret.assign( vec3( 0, 0, 1 ) );
  23387. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  23388. ret.assign( vec3( -1, 0, 0 ) );
  23389. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  23390. ret.assign( vec3( 0, -1, 0 ) );
  23391. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  23392. ret.assign( vec3( 0, 0, -1 ) );
  23393. } ).Else( () => {
  23394. const step = 0.01;
  23395. const x = texture.sample( uv.add( vec3( -0.01, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  23396. const y = texture.sample( uv.add( vec3( 0.0, -0.01, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  23397. const z = texture.sample( uv.add( vec3( 0.0, 0.0, -0.01 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  23398. ret.assign( vec3( x, y, z ) );
  23399. } );
  23400. return ret.normalize();
  23401. } );
  23402. /**
  23403. * This type of uniform node represents a 3D texture.
  23404. *
  23405. * @augments TextureNode
  23406. */
  23407. class Texture3DNode extends TextureNode {
  23408. static get type() {
  23409. return 'Texture3DNode';
  23410. }
  23411. /**
  23412. * Constructs a new 3D texture node.
  23413. *
  23414. * @param {Data3DTexture} value - The 3D texture.
  23415. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  23416. * @param {?Node<int>} [levelNode=null] - The level node.
  23417. */
  23418. constructor( value, uvNode = null, levelNode = null ) {
  23419. super( value, uvNode, levelNode );
  23420. /**
  23421. * This flag can be used for type testing.
  23422. *
  23423. * @type {boolean}
  23424. * @readonly
  23425. * @default true
  23426. */
  23427. this.isTexture3DNode = true;
  23428. }
  23429. /**
  23430. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  23431. *
  23432. * @param {NodeBuilder} builder - The current node builder.
  23433. * @return {string} The input type.
  23434. */
  23435. getInputType( /*builder*/ ) {
  23436. return 'texture3D';
  23437. }
  23438. /**
  23439. * Returns a default uv node which is in context of 3D textures a three-dimensional
  23440. * uv node.
  23441. *
  23442. * @return {Node<vec3>} The default uv node.
  23443. */
  23444. getDefaultUV() {
  23445. return vec3( 0.5, 0.5, 0.5 );
  23446. }
  23447. /**
  23448. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  23449. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  23450. *
  23451. * @param {boolean} value - The update toggle.
  23452. */
  23453. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  23454. /**
  23455. * Overwrites the default implementation to return the unmodified uv node.
  23456. *
  23457. * @param {NodeBuilder} builder - The current node builder.
  23458. * @param {Node} uvNode - The uv node to setup.
  23459. * @return {Node} The unmodified uv node.
  23460. */
  23461. setupUV( builder, uvNode ) {
  23462. const texture = this.value;
  23463. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  23464. if ( this.sampler ) {
  23465. uvNode = uvNode.flipY();
  23466. } else {
  23467. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  23468. }
  23469. }
  23470. return uvNode;
  23471. }
  23472. /**
  23473. * Generates the uv code snippet.
  23474. *
  23475. * @param {NodeBuilder} builder - The current node builder.
  23476. * @param {Node} uvNode - The uv node to generate code for.
  23477. * @return {string} The generated code snippet.
  23478. */
  23479. generateUV( builder, uvNode ) {
  23480. return uvNode.build( builder, 'vec3' );
  23481. }
  23482. /**
  23483. * TODO.
  23484. *
  23485. * @param {Node<vec3>} uvNode - The uv node .
  23486. * @return {Node<vec3>} TODO.
  23487. */
  23488. normal( uvNode ) {
  23489. return normal( { texture: this, uv: uvNode } );
  23490. }
  23491. }
  23492. /**
  23493. * TSL function for creating a 3D texture node.
  23494. *
  23495. * @tsl
  23496. * @function
  23497. * @param {Data3DTexture} value - The 3D texture.
  23498. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  23499. * @param {?Node<int>} [levelNode=null] - The level node.
  23500. * @returns {Texture3DNode}
  23501. */
  23502. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  23503. /**
  23504. * A special type of reference node that allows to link values in
  23505. * `userData` fields to node objects.
  23506. * ```js
  23507. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  23508. *
  23509. * const material = new THREE.SpriteNodeMaterial();
  23510. * material.rotationNode = userData( 'rotation', 'float' );
  23511. * ```
  23512. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  23513. * will automatically be updated when the `rotation` user data field changes.
  23514. *
  23515. * @augments ReferenceNode
  23516. */
  23517. class UserDataNode extends ReferenceNode {
  23518. static get type() {
  23519. return 'UserDataNode';
  23520. }
  23521. /**
  23522. * Constructs a new user data node.
  23523. *
  23524. * @param {string} property - The property name that should be referenced by the node.
  23525. * @param {string} inputType - The node data type of the reference.
  23526. * @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.
  23527. */
  23528. constructor( property, inputType, userData = null ) {
  23529. super( property, inputType, userData );
  23530. /**
  23531. * A reference to the `userData` object. If not provided, the `userData`
  23532. * property of the 3D object that uses the node material is evaluated.
  23533. *
  23534. * @type {?Object}
  23535. * @default null
  23536. */
  23537. this.userData = userData;
  23538. }
  23539. /**
  23540. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  23541. * `userData` field.
  23542. *
  23543. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  23544. * @return {Object} A reference to the `userData` field.
  23545. */
  23546. updateReference( state ) {
  23547. this.reference = this.userData !== null ? this.userData : state.object.userData;
  23548. return this.reference;
  23549. }
  23550. }
  23551. /**
  23552. * TSL function for creating a user data node.
  23553. *
  23554. * @tsl
  23555. * @function
  23556. * @param {string} name - The property name that should be referenced by the node.
  23557. * @param {string} inputType - The node data type of the reference.
  23558. * @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.
  23559. * @returns {UserDataNode}
  23560. */
  23561. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  23562. const _objectData = new WeakMap();
  23563. /**
  23564. * A node for representing motion or velocity vectors. Foundation
  23565. * for advanced post processing effects like motion blur or TRAA.
  23566. *
  23567. * The node keeps track of the model, view and projection matrices
  23568. * of the previous frame and uses them to compute offsets in NDC space.
  23569. * These offsets represent the final velocity.
  23570. *
  23571. * @augments TempNode
  23572. */
  23573. class VelocityNode extends TempNode {
  23574. static get type() {
  23575. return 'VelocityNode';
  23576. }
  23577. /**
  23578. * Constructs a new vertex color node.
  23579. */
  23580. constructor() {
  23581. super( 'vec2' );
  23582. /**
  23583. * The current projection matrix.
  23584. *
  23585. * @type {?Matrix4}
  23586. * @default null
  23587. */
  23588. this.projectionMatrix = null;
  23589. /**
  23590. * Overwritten since velocity nodes are updated per object.
  23591. *
  23592. * @type {string}
  23593. * @default 'object'
  23594. */
  23595. this.updateType = NodeUpdateType.OBJECT;
  23596. /**
  23597. * Overwritten since velocity nodes save data after the update.
  23598. *
  23599. * @type {string}
  23600. * @default 'object'
  23601. */
  23602. this.updateAfterType = NodeUpdateType.OBJECT;
  23603. /**
  23604. * Uniform node representing the previous model matrix in world space.
  23605. *
  23606. * @type {UniformNode<mat4>}
  23607. * @default null
  23608. */
  23609. this.previousModelWorldMatrix = uniform( new Matrix4() );
  23610. /**
  23611. * Uniform node representing the previous projection matrix.
  23612. *
  23613. * @type {UniformNode<mat4>}
  23614. * @default null
  23615. */
  23616. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  23617. /**
  23618. * Uniform node representing the previous view matrix.
  23619. *
  23620. * @type {UniformNode<mat4>}
  23621. * @default null
  23622. */
  23623. this.previousCameraViewMatrix = uniform( new Matrix4() );
  23624. }
  23625. /**
  23626. * Sets the given projection matrix.
  23627. *
  23628. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  23629. */
  23630. setProjectionMatrix( projectionMatrix ) {
  23631. this.projectionMatrix = projectionMatrix;
  23632. }
  23633. /**
  23634. * Updates velocity specific uniforms.
  23635. *
  23636. * @param {NodeFrame} frame - A reference to the current node frame.
  23637. */
  23638. update( { frameId, camera, object } ) {
  23639. const previousModelMatrix = getPreviousMatrix( object );
  23640. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  23641. //
  23642. const cameraData = getData( camera );
  23643. if ( cameraData.frameId !== frameId ) {
  23644. cameraData.frameId = frameId;
  23645. if ( cameraData.previousProjectionMatrix === undefined ) {
  23646. cameraData.previousProjectionMatrix = new Matrix4();
  23647. cameraData.previousCameraViewMatrix = new Matrix4();
  23648. cameraData.currentProjectionMatrix = new Matrix4();
  23649. cameraData.currentCameraViewMatrix = new Matrix4();
  23650. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23651. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  23652. } else {
  23653. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  23654. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  23655. }
  23656. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23657. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  23658. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  23659. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  23660. }
  23661. }
  23662. /**
  23663. * Overwritten to updated velocity specific uniforms.
  23664. *
  23665. * @param {NodeFrame} frame - A reference to the current node frame.
  23666. */
  23667. updateAfter( { object } ) {
  23668. getPreviousMatrix( object ).copy( object.matrixWorld );
  23669. }
  23670. /**
  23671. * Implements the velocity computation based on the previous and current vertex data.
  23672. *
  23673. * @param {NodeBuilder} builder - A reference to the current node builder.
  23674. * @return {Node<vec2>} The motion vector.
  23675. */
  23676. setup( /*builder*/ ) {
  23677. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  23678. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  23679. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23680. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  23681. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  23682. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  23683. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  23684. return velocity;
  23685. }
  23686. }
  23687. function getData( object ) {
  23688. let objectData = _objectData.get( object );
  23689. if ( objectData === undefined ) {
  23690. objectData = {};
  23691. _objectData.set( object, objectData );
  23692. }
  23693. return objectData;
  23694. }
  23695. function getPreviousMatrix( object, index = 0 ) {
  23696. const objectData = getData( object );
  23697. let matrix = objectData[ index ];
  23698. if ( matrix === undefined ) {
  23699. objectData[ index ] = matrix = new Matrix4();
  23700. objectData[ index ].copy( object.matrixWorld );
  23701. }
  23702. return matrix;
  23703. }
  23704. /**
  23705. * TSL object that represents the velocity of a render pass.
  23706. *
  23707. * @tsl
  23708. * @type {VelocityNode}
  23709. */
  23710. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  23711. /**
  23712. * Represents a "Color Burn" blend mode.
  23713. *
  23714. * It's designed to darken the base layer's colors based on the color of the blend layer.
  23715. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  23716. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  23717. *
  23718. * @tsl
  23719. * @function
  23720. * @param {Node<vec3>} base - The base color.
  23721. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  23722. * @return {Node<vec3>} The result.
  23723. */
  23724. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23725. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  23726. } ).setLayout( {
  23727. name: 'blendBurn',
  23728. type: 'vec3',
  23729. inputs: [
  23730. { name: 'base', type: 'vec3' },
  23731. { name: 'blend', type: 'vec3' }
  23732. ]
  23733. } );
  23734. /**
  23735. * Represents a "Color Dodge" blend mode.
  23736. *
  23737. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  23738. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  23739. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  23740. *
  23741. * @tsl
  23742. * @function
  23743. * @param {Node<vec3>} base - The base color.
  23744. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23745. * @return {Node<vec3>} The result.
  23746. */
  23747. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23748. return min$1( base.div( blend.oneMinus() ), 1.0 );
  23749. } ).setLayout( {
  23750. name: 'blendDodge',
  23751. type: 'vec3',
  23752. inputs: [
  23753. { name: 'base', type: 'vec3' },
  23754. { name: 'blend', type: 'vec3' }
  23755. ]
  23756. } );
  23757. /**
  23758. * Represents a "Screen" blend mode.
  23759. *
  23760. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  23761. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  23762. * effects.
  23763. *
  23764. * @tsl
  23765. * @function
  23766. * @param {Node<vec3>} base - The base color.
  23767. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23768. * @return {Node<vec3>} The result.
  23769. */
  23770. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23771. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  23772. } ).setLayout( {
  23773. name: 'blendScreen',
  23774. type: 'vec3',
  23775. inputs: [
  23776. { name: 'base', type: 'vec3' },
  23777. { name: 'blend', type: 'vec3' }
  23778. ]
  23779. } );
  23780. /**
  23781. * Represents a "Overlay" blend mode.
  23782. *
  23783. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  23784. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  23785. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  23786. *
  23787. * @tsl
  23788. * @function
  23789. * @param {Node<vec3>} base - The base color.
  23790. * @param {Node<vec3>} blend - The blend color
  23791. * @return {Node<vec3>} The result.
  23792. */
  23793. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23794. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  23795. } ).setLayout( {
  23796. name: 'blendOverlay',
  23797. type: 'vec3',
  23798. inputs: [
  23799. { name: 'base', type: 'vec3' },
  23800. { name: 'blend', type: 'vec3' }
  23801. ]
  23802. } );
  23803. /**
  23804. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  23805. * It assumes both input colors have non-premultiplied alpha.
  23806. *
  23807. * @tsl
  23808. * @function
  23809. * @param {Node<vec4>} base - The base color.
  23810. * @param {Node<vec4>} blend - The blend color
  23811. * @return {Node<vec4>} The result.
  23812. */
  23813. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23814. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  23815. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  23816. } ).setLayout( {
  23817. name: 'blendColor',
  23818. type: 'vec4',
  23819. inputs: [
  23820. { name: 'base', type: 'vec4' },
  23821. { name: 'blend', type: 'vec4' }
  23822. ]
  23823. } );
  23824. // Deprecated
  23825. /**
  23826. * @tsl
  23827. * @function
  23828. * @deprecated since r171. Use {@link blendBurn} instead.
  23829. *
  23830. * @param {...any} params
  23831. * @returns {Function}
  23832. */
  23833. const burn = ( ...params ) => { // @deprecated, r171
  23834. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  23835. return blendBurn( params );
  23836. };
  23837. /**
  23838. * @tsl
  23839. * @function
  23840. * @deprecated since r171. Use {@link blendDodge} instead.
  23841. *
  23842. * @param {...any} params
  23843. * @returns {Function}
  23844. */
  23845. const dodge = ( ...params ) => { // @deprecated, r171
  23846. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  23847. return blendDodge( params );
  23848. };
  23849. /**
  23850. * @tsl
  23851. * @function
  23852. * @deprecated since r171. Use {@link blendScreen} instead.
  23853. *
  23854. * @param {...any} params
  23855. * @returns {Function}
  23856. */
  23857. const screen = ( ...params ) => { // @deprecated, r171
  23858. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  23859. return blendScreen( params );
  23860. };
  23861. /**
  23862. * @tsl
  23863. * @function
  23864. * @deprecated since r171. Use {@link blendOverlay} instead.
  23865. *
  23866. * @param {...any} params
  23867. * @returns {Function}
  23868. */
  23869. const overlay = ( ...params ) => { // @deprecated, r171
  23870. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  23871. return blendOverlay( params );
  23872. };
  23873. /**
  23874. * Computes a grayscale value for the given RGB color value.
  23875. *
  23876. * @tsl
  23877. * @function
  23878. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  23879. * @return {Node<vec3>} The grayscale color.
  23880. */
  23881. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23882. return luminance( color.rgb );
  23883. } );
  23884. /**
  23885. * Super-saturates or desaturates the given RGB color.
  23886. *
  23887. * @tsl
  23888. * @function
  23889. * @param {Node<vec3>} color - The input color.
  23890. * @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.
  23891. * @return {Node<vec3>} The saturated color.
  23892. */
  23893. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23894. return adjustment.mix( luminance( color.rgb ), color.rgb );
  23895. } );
  23896. /**
  23897. * Selectively enhance the intensity of less saturated RGB colors. Can result
  23898. * in a more natural and visually appealing image with enhanced color depth
  23899. * compared to {@link ColorAdjustment#saturation}.
  23900. *
  23901. * @tsl
  23902. * @function
  23903. * @param {Node<vec3>} color - The input color.
  23904. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  23905. * @return {Node<vec3>} The updated color.
  23906. */
  23907. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23908. const average = add( color.r, color.g, color.b ).div( 3.0 );
  23909. const mx = color.r.max( color.g.max( color.b ) );
  23910. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  23911. return mix( color.rgb, mx, amt );
  23912. } );
  23913. /**
  23914. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  23915. *
  23916. * @tsl
  23917. * @function
  23918. * @param {Node<vec3>} color - The input color.
  23919. * @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.
  23920. * @return {Node<vec3>} The updated color.
  23921. */
  23922. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23923. const k = vec3( 0.57735, 0.57735, 0.57735 );
  23924. const cosAngle = adjustment.cos();
  23925. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  23926. } );
  23927. /**
  23928. * Computes the luminance for the given RGB color value.
  23929. *
  23930. * @tsl
  23931. * @function
  23932. * @param {Node<vec3>} color - The color value to compute the luminance for.
  23933. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  23934. * @return {Node<vec3>} The luminance.
  23935. */
  23936. const luminance = (
  23937. color,
  23938. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  23939. ) => dot( color, luminanceCoefficients );
  23940. /**
  23941. * Color Decision List (CDL) v1.2
  23942. *
  23943. * Compact representation of color grading information, defined by slope, offset, power, and
  23944. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  23945. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  23946. *
  23947. * @tsl
  23948. * @function
  23949. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  23950. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  23951. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  23952. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  23953. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  23954. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  23955. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  23956. *
  23957. * References:
  23958. * - ASC CDL v1.2
  23959. * - {@link https://blender.stackexchange.com/a/55239/43930}
  23960. * - {@link https://docs.acescentral.com/specifications/acescc/}
  23961. */
  23962. const cdl = /*@__PURE__*/ Fn( ( [
  23963. color,
  23964. slope = vec3( 1 ),
  23965. offset = vec3( 0 ),
  23966. power = vec3( 1 ),
  23967. saturation = float( 1 ),
  23968. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  23969. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  23970. ] ) => {
  23971. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  23972. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  23973. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  23974. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  23975. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  23976. const pv = v.pow( power ).toVar();
  23977. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  23978. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  23979. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  23980. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  23981. return vec4( v.rgb, color.a );
  23982. } );
  23983. /**
  23984. * Represents a posterize effect which reduces the number of colors
  23985. * in an image, resulting in a more blocky and stylized appearance.
  23986. *
  23987. * @augments TempNode
  23988. */
  23989. class PosterizeNode extends TempNode {
  23990. static get type() {
  23991. return 'PosterizeNode';
  23992. }
  23993. /**
  23994. * Constructs a new posterize node.
  23995. *
  23996. * @param {Node} sourceNode - The input color.
  23997. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  23998. */
  23999. constructor( sourceNode, stepsNode ) {
  24000. super();
  24001. /**
  24002. * The input color.
  24003. *
  24004. * @type {Node}
  24005. */
  24006. this.sourceNode = sourceNode;
  24007. /**
  24008. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24009. *
  24010. * @type {Node}
  24011. */
  24012. this.stepsNode = stepsNode;
  24013. }
  24014. setup() {
  24015. const { sourceNode, stepsNode } = this;
  24016. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  24017. }
  24018. }
  24019. /**
  24020. * TSL function for creating a posterize node.
  24021. *
  24022. * @tsl
  24023. * @function
  24024. * @param {Node} sourceNode - The input color.
  24025. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24026. * @returns {PosterizeNode}
  24027. */
  24028. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  24029. const _size = /*@__PURE__*/ new Vector2();
  24030. /**
  24031. * Represents the texture of a pass node.
  24032. *
  24033. * @augments TextureNode
  24034. */
  24035. class PassTextureNode extends TextureNode {
  24036. static get type() {
  24037. return 'PassTextureNode';
  24038. }
  24039. /**
  24040. * Constructs a new pass texture node.
  24041. *
  24042. * @param {PassNode} passNode - The pass node.
  24043. * @param {Texture} texture - The output texture.
  24044. */
  24045. constructor( passNode, texture ) {
  24046. super( texture );
  24047. /**
  24048. * A reference to the pass node.
  24049. *
  24050. * @type {PassNode}
  24051. */
  24052. this.passNode = passNode;
  24053. this.setUpdateMatrix( false );
  24054. }
  24055. setup( builder ) {
  24056. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  24057. return super.setup( builder );
  24058. }
  24059. clone() {
  24060. return new this.constructor( this.passNode, this.value );
  24061. }
  24062. }
  24063. /**
  24064. * An extension of `PassTextureNode` which allows to manage more than one
  24065. * internal texture. Relevant for the `getPreviousTexture()` related API.
  24066. *
  24067. * @augments PassTextureNode
  24068. */
  24069. class PassMultipleTextureNode extends PassTextureNode {
  24070. static get type() {
  24071. return 'PassMultipleTextureNode';
  24072. }
  24073. /**
  24074. * Constructs a new pass texture node.
  24075. *
  24076. * @param {PassNode} passNode - The pass node.
  24077. * @param {string} textureName - The output texture name.
  24078. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  24079. */
  24080. constructor( passNode, textureName, previousTexture = false ) {
  24081. // null is passed to the super call since this class does not
  24082. // use an external texture for rendering pass data into. Instead
  24083. // the texture is managed by the pass node itself
  24084. super( passNode, null );
  24085. /**
  24086. * The output texture name.
  24087. *
  24088. * @type {string}
  24089. */
  24090. this.textureName = textureName;
  24091. /**
  24092. * Whether previous frame data should be used or not.
  24093. *
  24094. * @type {boolean}
  24095. */
  24096. this.previousTexture = previousTexture;
  24097. }
  24098. /**
  24099. * Updates the texture reference of this node.
  24100. */
  24101. updateTexture() {
  24102. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  24103. }
  24104. setup( builder ) {
  24105. this.updateTexture();
  24106. return super.setup( builder );
  24107. }
  24108. clone() {
  24109. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  24110. }
  24111. }
  24112. /**
  24113. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  24114. * This pass produces a render for the given scene and camera and can provide multiple outputs
  24115. * via MRT for further processing.
  24116. *
  24117. * ```js
  24118. * const postProcessing = new PostProcessing( renderer );
  24119. *
  24120. * const scenePass = pass( scene, camera );
  24121. *
  24122. * postProcessing.outputNode = scenePass;
  24123. * ```
  24124. *
  24125. * @augments TempNode
  24126. */
  24127. class PassNode extends TempNode {
  24128. static get type() {
  24129. return 'PassNode';
  24130. }
  24131. /**
  24132. * Constructs a new pass node.
  24133. *
  24134. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  24135. * @param {Scene} scene - A reference to the scene.
  24136. * @param {Camera} camera - A reference to the camera.
  24137. * @param {Object} options - Options for the internal render target.
  24138. */
  24139. constructor( scope, scene, camera, options = {} ) {
  24140. super( 'vec4' );
  24141. /**
  24142. * The scope of the pass. The scope determines whether the node outputs color or depth.
  24143. *
  24144. * @type {('color'|'depth')}
  24145. */
  24146. this.scope = scope;
  24147. /**
  24148. * A reference to the scene.
  24149. *
  24150. * @type {Scene}
  24151. */
  24152. this.scene = scene;
  24153. /**
  24154. * A reference to the camera.
  24155. *
  24156. * @type {Camera}
  24157. */
  24158. this.camera = camera;
  24159. /**
  24160. * Options for the internal render target.
  24161. *
  24162. * @type {Object}
  24163. */
  24164. this.options = options;
  24165. /**
  24166. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  24167. *
  24168. * @private
  24169. * @type {number}
  24170. * @default 1
  24171. */
  24172. this._pixelRatio = 1;
  24173. /**
  24174. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  24175. * @private
  24176. * @type {number}
  24177. * @default 1
  24178. */
  24179. this._width = 1;
  24180. /**
  24181. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  24182. * @private
  24183. * @type {number}
  24184. * @default 1
  24185. */
  24186. this._height = 1;
  24187. const depthTexture = new DepthTexture();
  24188. depthTexture.isRenderTargetTexture = true;
  24189. //depthTexture.type = FloatType;
  24190. depthTexture.name = 'depth';
  24191. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  24192. renderTarget.texture.name = 'output';
  24193. renderTarget.depthTexture = depthTexture;
  24194. /**
  24195. * The pass's render target.
  24196. *
  24197. * @type {RenderTarget}
  24198. */
  24199. this.renderTarget = renderTarget;
  24200. /**
  24201. * A dictionary holding the internal result textures.
  24202. *
  24203. * @private
  24204. * @type {Object<string, Texture>}
  24205. */
  24206. this._textures = {
  24207. output: renderTarget.texture,
  24208. depth: depthTexture
  24209. };
  24210. /**
  24211. * A dictionary holding the internal texture nodes.
  24212. *
  24213. * @private
  24214. * @type {Object<string, TextureNode>}
  24215. */
  24216. this._textureNodes = {};
  24217. /**
  24218. * A dictionary holding the internal depth nodes.
  24219. *
  24220. * @private
  24221. * @type {Object}
  24222. */
  24223. this._linearDepthNodes = {};
  24224. /**
  24225. * A dictionary holding the internal viewZ nodes.
  24226. *
  24227. * @private
  24228. * @type {Object}
  24229. */
  24230. this._viewZNodes = {};
  24231. /**
  24232. * A dictionary holding the texture data of the previous frame.
  24233. * Used for computing velocity/motion vectors.
  24234. *
  24235. * @private
  24236. * @type {Object<string, Texture>}
  24237. */
  24238. this._previousTextures = {};
  24239. /**
  24240. * A dictionary holding the texture nodes of the previous frame.
  24241. * Used for computing velocity/motion vectors.
  24242. *
  24243. * @private
  24244. * @type {Object<string, TextureNode>}
  24245. */
  24246. this._previousTextureNodes = {};
  24247. /**
  24248. * The `near` property of the camera as a uniform.
  24249. *
  24250. * @private
  24251. * @type {UniformNode}
  24252. */
  24253. this._cameraNear = uniform( 0 );
  24254. /**
  24255. * The `far` property of the camera as a uniform.
  24256. *
  24257. * @private
  24258. * @type {UniformNode}
  24259. */
  24260. this._cameraFar = uniform( 0 );
  24261. /**
  24262. * A MRT node configuring the MRT settings.
  24263. *
  24264. * @private
  24265. * @type {?MRTNode}
  24266. * @default null
  24267. */
  24268. this._mrt = null;
  24269. this._layers = null;
  24270. this._resolution = 1;
  24271. /**
  24272. * This flag can be used for type testing.
  24273. *
  24274. * @type {boolean}
  24275. * @readonly
  24276. * @default true
  24277. */
  24278. this.isPassNode = true;
  24279. /**
  24280. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  24281. * scene once per frame in its {@link PassNode#updateBefore} method.
  24282. *
  24283. * @type {string}
  24284. * @default 'frame'
  24285. */
  24286. this.updateBeforeType = NodeUpdateType.FRAME;
  24287. }
  24288. /**
  24289. * Sets the resolution for the pass.
  24290. * The resolution is a factor that is multiplied with the renderer's width and height.
  24291. *
  24292. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  24293. * @return {PassNode} A reference to this pass.
  24294. */
  24295. setResolution( resolution ) {
  24296. this._resolution = resolution;
  24297. return this;
  24298. }
  24299. /**
  24300. * Gets the current resolution of the pass.
  24301. *
  24302. * @return {number} The current resolution. A value of `1` means full resolution.
  24303. * @default 1
  24304. */
  24305. getResolution() {
  24306. return this._resolution;
  24307. }
  24308. setLayers( layers ) {
  24309. this._layers = layers;
  24310. return this;
  24311. }
  24312. getLayers() {
  24313. return this._layers;
  24314. }
  24315. /**
  24316. * Sets the given MRT node to setup MRT for this pass.
  24317. *
  24318. * @param {MRTNode} mrt - The MRT object.
  24319. * @return {PassNode} A reference to this pass.
  24320. */
  24321. setMRT( mrt ) {
  24322. this._mrt = mrt;
  24323. return this;
  24324. }
  24325. /**
  24326. * Returns the current MRT node.
  24327. *
  24328. * @return {MRTNode} The current MRT node.
  24329. */
  24330. getMRT() {
  24331. return this._mrt;
  24332. }
  24333. /**
  24334. * The method is overwritten so it always returns `true`.
  24335. *
  24336. * @return {boolean} Whether this node is global or not.
  24337. */
  24338. isGlobal() {
  24339. return true;
  24340. }
  24341. /**
  24342. * Returns the texture for the given output name.
  24343. *
  24344. * @param {string} name - The output name to get the texture for.
  24345. * @return {Texture} The texture.
  24346. */
  24347. getTexture( name ) {
  24348. let texture = this._textures[ name ];
  24349. if ( texture === undefined ) {
  24350. const refTexture = this.renderTarget.texture;
  24351. texture = refTexture.clone();
  24352. texture.name = name;
  24353. this._textures[ name ] = texture;
  24354. this.renderTarget.textures.push( texture );
  24355. }
  24356. return texture;
  24357. }
  24358. /**
  24359. * Returns the texture holding the data of the previous frame for the given output name.
  24360. *
  24361. * @param {string} name - The output name to get the texture for.
  24362. * @return {Texture} The texture holding the data of the previous frame.
  24363. */
  24364. getPreviousTexture( name ) {
  24365. let texture = this._previousTextures[ name ];
  24366. if ( texture === undefined ) {
  24367. texture = this.getTexture( name ).clone();
  24368. this._previousTextures[ name ] = texture;
  24369. }
  24370. return texture;
  24371. }
  24372. /**
  24373. * Switches current and previous textures for the given output name.
  24374. *
  24375. * @param {string} name - The output name.
  24376. */
  24377. toggleTexture( name ) {
  24378. const prevTexture = this._previousTextures[ name ];
  24379. if ( prevTexture !== undefined ) {
  24380. const texture = this._textures[ name ];
  24381. const index = this.renderTarget.textures.indexOf( texture );
  24382. this.renderTarget.textures[ index ] = prevTexture;
  24383. this._textures[ name ] = prevTexture;
  24384. this._previousTextures[ name ] = texture;
  24385. this._textureNodes[ name ].updateTexture();
  24386. this._previousTextureNodes[ name ].updateTexture();
  24387. }
  24388. }
  24389. /**
  24390. * Returns the texture node for the given output name.
  24391. *
  24392. * @param {string} [name='output'] - The output name to get the texture node for.
  24393. * @return {TextureNode} The texture node.
  24394. */
  24395. getTextureNode( name = 'output' ) {
  24396. let textureNode = this._textureNodes[ name ];
  24397. if ( textureNode === undefined ) {
  24398. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  24399. textureNode.updateTexture();
  24400. this._textureNodes[ name ] = textureNode;
  24401. }
  24402. return textureNode;
  24403. }
  24404. /**
  24405. * Returns the previous texture node for the given output name.
  24406. *
  24407. * @param {string} [name='output'] - The output name to get the previous texture node for.
  24408. * @return {TextureNode} The previous texture node.
  24409. */
  24410. getPreviousTextureNode( name = 'output' ) {
  24411. let textureNode = this._previousTextureNodes[ name ];
  24412. if ( textureNode === undefined ) {
  24413. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  24414. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  24415. textureNode.updateTexture();
  24416. this._previousTextureNodes[ name ] = textureNode;
  24417. }
  24418. return textureNode;
  24419. }
  24420. /**
  24421. * Returns a viewZ node of this pass.
  24422. *
  24423. * @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.
  24424. * @return {Node} The viewZ node.
  24425. */
  24426. getViewZNode( name = 'depth' ) {
  24427. let viewZNode = this._viewZNodes[ name ];
  24428. if ( viewZNode === undefined ) {
  24429. const cameraNear = this._cameraNear;
  24430. const cameraFar = this._cameraFar;
  24431. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  24432. }
  24433. return viewZNode;
  24434. }
  24435. /**
  24436. * Returns a linear depth node of this pass.
  24437. *
  24438. * @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.
  24439. * @return {Node} The linear depth node.
  24440. */
  24441. getLinearDepthNode( name = 'depth' ) {
  24442. let linearDepthNode = this._linearDepthNodes[ name ];
  24443. if ( linearDepthNode === undefined ) {
  24444. const cameraNear = this._cameraNear;
  24445. const cameraFar = this._cameraFar;
  24446. const viewZNode = this.getViewZNode( name );
  24447. // TODO: just if ( builder.camera.isPerspectiveCamera )
  24448. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  24449. }
  24450. return linearDepthNode;
  24451. }
  24452. setup( { renderer } ) {
  24453. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  24454. // TODO: Disable MSAA for WebGL backend for now
  24455. if ( renderer.backend.isWebGLBackend === true ) {
  24456. this.renderTarget.samples = 0;
  24457. }
  24458. this.renderTarget.texture.type = renderer.getColorBufferType();
  24459. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  24460. }
  24461. updateBefore( frame ) {
  24462. const { renderer } = frame;
  24463. const { scene } = this;
  24464. let camera;
  24465. let pixelRatio;
  24466. const outputRenderTarget = renderer.getOutputRenderTarget();
  24467. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  24468. pixelRatio = 1;
  24469. camera = renderer.xr.getCamera();
  24470. renderer.xr.updateCamera( camera );
  24471. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  24472. } else {
  24473. camera = this.camera;
  24474. pixelRatio = renderer.getPixelRatio();
  24475. renderer.getSize( _size );
  24476. }
  24477. this._pixelRatio = pixelRatio;
  24478. this.setSize( _size.width, _size.height );
  24479. const currentRenderTarget = renderer.getRenderTarget();
  24480. const currentMRT = renderer.getMRT();
  24481. const currentMask = camera.layers.mask;
  24482. this._cameraNear.value = camera.near;
  24483. this._cameraFar.value = camera.far;
  24484. if ( this._layers !== null ) {
  24485. camera.layers.mask = this._layers.mask;
  24486. }
  24487. for ( const name in this._previousTextures ) {
  24488. this.toggleTexture( name );
  24489. }
  24490. renderer.setRenderTarget( this.renderTarget );
  24491. renderer.setMRT( this._mrt );
  24492. renderer.render( scene, camera );
  24493. renderer.setRenderTarget( currentRenderTarget );
  24494. renderer.setMRT( currentMRT );
  24495. camera.layers.mask = currentMask;
  24496. }
  24497. /**
  24498. * Sets the size of the pass's render target. Honors the pixel ratio.
  24499. *
  24500. * @param {number} width - The width to set.
  24501. * @param {number} height - The height to set.
  24502. */
  24503. setSize( width, height ) {
  24504. this._width = width;
  24505. this._height = height;
  24506. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  24507. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  24508. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24509. }
  24510. /**
  24511. * Sets the pixel ratio the pass's render target and updates the size.
  24512. *
  24513. * @param {number} pixelRatio - The pixel ratio to set.
  24514. */
  24515. setPixelRatio( pixelRatio ) {
  24516. this._pixelRatio = pixelRatio;
  24517. this.setSize( this._width, this._height );
  24518. }
  24519. /**
  24520. * Frees internal resources. Should be called when the node is no longer in use.
  24521. */
  24522. dispose() {
  24523. this.renderTarget.dispose();
  24524. }
  24525. }
  24526. /**
  24527. * @static
  24528. * @type {'color'}
  24529. * @default 'color'
  24530. */
  24531. PassNode.COLOR = 'color';
  24532. /**
  24533. * @static
  24534. * @type {'depth'}
  24535. * @default 'depth'
  24536. */
  24537. PassNode.DEPTH = 'depth';
  24538. /**
  24539. * TSL function for creating a pass node.
  24540. *
  24541. * @tsl
  24542. * @function
  24543. * @param {Scene} scene - A reference to the scene.
  24544. * @param {Camera} camera - A reference to the camera.
  24545. * @param {Object} options - Options for the internal render target.
  24546. * @returns {PassNode}
  24547. */
  24548. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  24549. /**
  24550. * TSL function for creating a pass texture node.
  24551. *
  24552. * @tsl
  24553. * @function
  24554. * @param {PassNode} pass - The pass node.
  24555. * @param {Texture} texture - The output texture.
  24556. * @returns {PassTextureNode}
  24557. */
  24558. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  24559. /**
  24560. * TSL function for creating a depth pass node.
  24561. *
  24562. * @tsl
  24563. * @function
  24564. * @param {Scene} scene - A reference to the scene.
  24565. * @param {Camera} camera - A reference to the camera.
  24566. * @param {Object} options - Options for the internal render target.
  24567. * @returns {PassNode}
  24568. */
  24569. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  24570. /**
  24571. * Represents a render pass for producing a toon outline effect on compatible objects.
  24572. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  24573. * will receive the outline.
  24574. *
  24575. * ```js
  24576. * const postProcessing = new PostProcessing( renderer );
  24577. *
  24578. * const scenePass = toonOutlinePass( scene, camera );
  24579. *
  24580. * postProcessing.outputNode = scenePass;
  24581. * ```
  24582. * @augments PassNode
  24583. */
  24584. class ToonOutlinePassNode extends PassNode {
  24585. static get type() {
  24586. return 'ToonOutlinePassNode';
  24587. }
  24588. /**
  24589. * Constructs a new outline pass node.
  24590. *
  24591. * @param {Scene} scene - A reference to the scene.
  24592. * @param {Camera} camera - A reference to the camera.
  24593. * @param {Node} colorNode - Defines the outline's color.
  24594. * @param {Node} thicknessNode - Defines the outline's thickness.
  24595. * @param {Node} alphaNode - Defines the outline's alpha.
  24596. */
  24597. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  24598. super( PassNode.COLOR, scene, camera );
  24599. /**
  24600. * Defines the outline's color.
  24601. *
  24602. * @type {Node}
  24603. */
  24604. this.colorNode = colorNode;
  24605. /**
  24606. * Defines the outline's thickness.
  24607. *
  24608. * @type {Node}
  24609. */
  24610. this.thicknessNode = thicknessNode;
  24611. /**
  24612. * Defines the outline's alpha.
  24613. *
  24614. * @type {Node}
  24615. */
  24616. this.alphaNode = alphaNode;
  24617. /**
  24618. * An internal material cache.
  24619. *
  24620. * @private
  24621. * @type {WeakMap<Material, NodeMaterial>}
  24622. */
  24623. this._materialCache = new WeakMap();
  24624. }
  24625. updateBefore( frame ) {
  24626. const { renderer } = frame;
  24627. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  24628. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  24629. // only render outline for supported materials
  24630. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  24631. if ( material.wireframe === false ) {
  24632. const outlineMaterial = this._getOutlineMaterial( material );
  24633. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  24634. }
  24635. }
  24636. // default
  24637. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  24638. } );
  24639. super.updateBefore( frame );
  24640. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  24641. }
  24642. /**
  24643. * Creates the material used for outline rendering.
  24644. *
  24645. * @private
  24646. * @return {NodeMaterial} The outline material.
  24647. */
  24648. _createMaterial() {
  24649. const material = new NodeMaterial();
  24650. material.isMeshToonOutlineMaterial = true;
  24651. material.name = 'Toon_Outline';
  24652. material.side = BackSide;
  24653. // vertex node
  24654. const outlineNormal = normalLocal.negate();
  24655. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  24656. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  24657. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  24658. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  24659. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  24660. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  24661. // color node
  24662. material.colorNode = vec4( this.colorNode, this.alphaNode );
  24663. return material;
  24664. }
  24665. /**
  24666. * For the given toon material, this method returns a corresponding
  24667. * outline material.
  24668. *
  24669. * @private
  24670. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  24671. * @return {NodeMaterial} The outline material.
  24672. */
  24673. _getOutlineMaterial( originalMaterial ) {
  24674. let outlineMaterial = this._materialCache.get( originalMaterial );
  24675. if ( outlineMaterial === undefined ) {
  24676. outlineMaterial = this._createMaterial();
  24677. this._materialCache.set( originalMaterial, outlineMaterial );
  24678. }
  24679. return outlineMaterial;
  24680. }
  24681. }
  24682. /**
  24683. * TSL function for creating a toon outline pass node.
  24684. *
  24685. * @tsl
  24686. * @function
  24687. * @param {Scene} scene - A reference to the scene.
  24688. * @param {Camera} camera - A reference to the camera.
  24689. * @param {Color} color - Defines the outline's color.
  24690. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  24691. * @param {number} [alpha=1] - Defines the outline's alpha.
  24692. * @returns {ToonOutlinePassNode}
  24693. */
  24694. 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 ) ) );
  24695. /**
  24696. * Linear tone mapping, exposure only.
  24697. *
  24698. * @tsl
  24699. * @function
  24700. * @param {Node<vec3>} color - The color that should be tone mapped.
  24701. * @param {Node<float>} exposure - The exposure.
  24702. * @return {Node<vec3>} The tone mapped color.
  24703. */
  24704. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24705. return color.mul( exposure ).clamp();
  24706. } ).setLayout( {
  24707. name: 'linearToneMapping',
  24708. type: 'vec3',
  24709. inputs: [
  24710. { name: 'color', type: 'vec3' },
  24711. { name: 'exposure', type: 'float' }
  24712. ]
  24713. } );
  24714. /**
  24715. * Reinhard tone mapping.
  24716. *
  24717. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  24718. *
  24719. * @tsl
  24720. * @function
  24721. * @param {Node<vec3>} color - The color that should be tone mapped.
  24722. * @param {Node<float>} exposure - The exposure.
  24723. * @return {Node<vec3>} The tone mapped color.
  24724. */
  24725. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24726. color = color.mul( exposure );
  24727. return color.div( color.add( 1.0 ) ).clamp();
  24728. } ).setLayout( {
  24729. name: 'reinhardToneMapping',
  24730. type: 'vec3',
  24731. inputs: [
  24732. { name: 'color', type: 'vec3' },
  24733. { name: 'exposure', type: 'float' }
  24734. ]
  24735. } );
  24736. /**
  24737. * Cineon tone mapping.
  24738. *
  24739. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  24740. *
  24741. * @tsl
  24742. * @function
  24743. * @param {Node<vec3>} color - The color that should be tone mapped.
  24744. * @param {Node<float>} exposure - The exposure.
  24745. * @return {Node<vec3>} The tone mapped color.
  24746. */
  24747. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24748. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  24749. color = color.mul( exposure );
  24750. color = color.sub( 0.004 ).max( 0.0 );
  24751. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  24752. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  24753. return a.div( b ).pow( 2.2 );
  24754. } ).setLayout( {
  24755. name: 'cineonToneMapping',
  24756. type: 'vec3',
  24757. inputs: [
  24758. { name: 'color', type: 'vec3' },
  24759. { name: 'exposure', type: 'float' }
  24760. ]
  24761. } );
  24762. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  24763. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24764. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  24765. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  24766. return a.div( b );
  24767. } );
  24768. /**
  24769. * ACESFilmic tone mapping.
  24770. *
  24771. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  24772. *
  24773. * @tsl
  24774. * @function
  24775. * @param {Node<vec3>} color - The color that should be tone mapped.
  24776. * @param {Node<float>} exposure - The exposure.
  24777. * @return {Node<vec3>} The tone mapped color.
  24778. */
  24779. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24780. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  24781. const ACESInputMat = mat3(
  24782. 0.59719, 0.35458, 0.04823,
  24783. 0.07600, 0.90834, 0.01566,
  24784. 0.02840, 0.13383, 0.83777
  24785. );
  24786. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  24787. const ACESOutputMat = mat3(
  24788. 1.60475, -0.53108, -0.07367,
  24789. -0.10208, 1.10813, -605e-5,
  24790. -327e-5, -0.07276, 1.07602
  24791. );
  24792. color = color.mul( exposure ).div( 0.6 );
  24793. color = ACESInputMat.mul( color );
  24794. // Apply RRT and ODT
  24795. color = RRTAndODTFit( color );
  24796. color = ACESOutputMat.mul( color );
  24797. // Clamp to [0, 1]
  24798. return color.clamp();
  24799. } ).setLayout( {
  24800. name: 'acesFilmicToneMapping',
  24801. type: 'vec3',
  24802. inputs: [
  24803. { name: 'color', type: 'vec3' },
  24804. { name: 'exposure', type: 'float' }
  24805. ]
  24806. } );
  24807. 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 ) );
  24808. 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 ) );
  24809. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  24810. const x = vec3( x_immutable ).toVar();
  24811. const x2 = vec3( x.mul( x ) ).toVar();
  24812. const x4 = vec3( x2.mul( x2 ) ).toVar();
  24813. 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 ) ) ) );
  24814. } );
  24815. /**
  24816. * AgX tone mapping.
  24817. *
  24818. * @tsl
  24819. * @function
  24820. * @param {Node<vec3>} color - The color that should be tone mapped.
  24821. * @param {Node<float>} exposure - The exposure.
  24822. * @return {Node<vec3>} The tone mapped color.
  24823. */
  24824. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24825. const colortone = vec3( color ).toVar();
  24826. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  24827. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  24828. const AgxMinEv = float( -12.47393 );
  24829. const AgxMaxEv = float( 4.026069 );
  24830. colortone.mulAssign( exposure );
  24831. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  24832. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  24833. colortone.assign( max$1( colortone, 1e-10 ) );
  24834. colortone.assign( log2( colortone ) );
  24835. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  24836. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  24837. colortone.assign( agxDefaultContrastApprox( colortone ) );
  24838. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  24839. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  24840. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  24841. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  24842. return colortone;
  24843. } ).setLayout( {
  24844. name: 'agxToneMapping',
  24845. type: 'vec3',
  24846. inputs: [
  24847. { name: 'color', type: 'vec3' },
  24848. { name: 'exposure', type: 'float' }
  24849. ]
  24850. } );
  24851. /**
  24852. * Neutral tone mapping.
  24853. *
  24854. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  24855. *
  24856. * @tsl
  24857. * @function
  24858. * @param {Node<vec3>} color - The color that should be tone mapped.
  24859. * @param {Node<float>} exposure - The exposure.
  24860. * @return {Node<vec3>} The tone mapped color.
  24861. */
  24862. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24863. const StartCompression = float( 0.8 - 0.04 );
  24864. const Desaturation = float( 0.15 );
  24865. color = color.mul( exposure );
  24866. const x = min$1( color.r, min$1( color.g, color.b ) );
  24867. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  24868. color.subAssign( offset );
  24869. const peak = max$1( color.r, max$1( color.g, color.b ) );
  24870. If( peak.lessThan( StartCompression ), () => {
  24871. return color;
  24872. } );
  24873. const d = sub( 1, StartCompression );
  24874. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  24875. color.mulAssign( newPeak.div( peak ) );
  24876. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  24877. return mix( color, vec3( newPeak ), g );
  24878. } ).setLayout( {
  24879. name: 'neutralToneMapping',
  24880. type: 'vec3',
  24881. inputs: [
  24882. { name: 'color', type: 'vec3' },
  24883. { name: 'exposure', type: 'float' }
  24884. ]
  24885. } );
  24886. /**
  24887. * This class represents native code sections. It is the base
  24888. * class for modules like {@link FunctionNode} which allows to implement
  24889. * functions with native shader languages.
  24890. *
  24891. * @augments Node
  24892. */
  24893. class CodeNode extends Node {
  24894. static get type() {
  24895. return 'CodeNode';
  24896. }
  24897. /**
  24898. * Constructs a new code node.
  24899. *
  24900. * @param {string} [code=''] - The native code.
  24901. * @param {Array<Node>} [includes=[]] - An array of includes.
  24902. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24903. */
  24904. constructor( code = '', includes = [], language = '' ) {
  24905. super( 'code' );
  24906. /**
  24907. * This flag can be used for type testing.
  24908. *
  24909. * @type {boolean}
  24910. * @readonly
  24911. * @default true
  24912. */
  24913. this.isCodeNode = true;
  24914. /**
  24915. * The native code.
  24916. *
  24917. * @type {string}
  24918. * @default ''
  24919. */
  24920. this.code = code;
  24921. /**
  24922. * An array of includes
  24923. *
  24924. * @type {Array<Node>}
  24925. * @default []
  24926. */
  24927. this.includes = includes;
  24928. /**
  24929. * The used language.
  24930. *
  24931. * @type {('js'|'wgsl'|'glsl')}
  24932. * @default ''
  24933. */
  24934. this.language = language;
  24935. }
  24936. /**
  24937. * The method is overwritten so it always returns `true`.
  24938. *
  24939. * @return {boolean} Whether this node is global or not.
  24940. */
  24941. isGlobal() {
  24942. return true;
  24943. }
  24944. /**
  24945. * Sets the includes of this code node.
  24946. *
  24947. * @param {Array<Node>} includes - The includes to set.
  24948. * @return {CodeNode} A reference to this node.
  24949. */
  24950. setIncludes( includes ) {
  24951. this.includes = includes;
  24952. return this;
  24953. }
  24954. /**
  24955. * Returns the includes of this code node.
  24956. *
  24957. * @param {NodeBuilder} builder - The current node builder.
  24958. * @return {Array<Node>} The includes.
  24959. */
  24960. getIncludes( /*builder*/ ) {
  24961. return this.includes;
  24962. }
  24963. generate( builder ) {
  24964. const includes = this.getIncludes( builder );
  24965. for ( const include of includes ) {
  24966. include.build( builder );
  24967. }
  24968. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  24969. nodeCode.code = this.code;
  24970. return nodeCode.code;
  24971. }
  24972. serialize( data ) {
  24973. super.serialize( data );
  24974. data.code = this.code;
  24975. data.language = this.language;
  24976. }
  24977. deserialize( data ) {
  24978. super.deserialize( data );
  24979. this.code = data.code;
  24980. this.language = data.language;
  24981. }
  24982. }
  24983. /**
  24984. * TSL function for creating a code node.
  24985. *
  24986. * @tsl
  24987. * @function
  24988. * @param {string} [code] - The native code.
  24989. * @param {?Array<Node>} [includes=[]] - An array of includes.
  24990. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24991. * @returns {CodeNode}
  24992. */
  24993. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  24994. /**
  24995. * TSL function for creating a JS code node.
  24996. *
  24997. * @tsl
  24998. * @function
  24999. * @param {string} src - The native code.
  25000. * @param {Array<Node>} includes - An array of includes.
  25001. * @returns {CodeNode}
  25002. */
  25003. const js = ( src, includes ) => code( src, includes, 'js' );
  25004. /**
  25005. * TSL function for creating a WGSL code node.
  25006. *
  25007. * @tsl
  25008. * @function
  25009. * @param {string} src - The native code.
  25010. * @param {Array<Node>} includes - An array of includes.
  25011. * @returns {CodeNode}
  25012. */
  25013. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  25014. /**
  25015. * TSL function for creating a GLSL code node.
  25016. *
  25017. * @tsl
  25018. * @function
  25019. * @param {string} src - The native code.
  25020. * @param {Array<Node>} includes - An array of includes.
  25021. * @returns {CodeNode}
  25022. */
  25023. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  25024. /**
  25025. * This class represents a native shader function. It can be used to implement
  25026. * certain aspects of a node material with native shader code. There are two predefined
  25027. * TSL functions for easier usage.
  25028. *
  25029. * - `wgslFn`: Creates a WGSL function node.
  25030. * - `glslFn`: Creates a GLSL function node.
  25031. *
  25032. * A basic example with one include looks like so:
  25033. *
  25034. * ```js
  25035. * const desaturateWGSLFn = wgslFn( `
  25036. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  25037. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  25038. * return vec3<f32>( dot( lum, color ) );
  25039. * }`
  25040. *);
  25041. * const someWGSLFn = wgslFn( `
  25042. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  25043. * return desaturate( color );
  25044. * }
  25045. * `, [ desaturateWGSLFn ] );
  25046. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  25047. *```
  25048. * @augments CodeNode
  25049. */
  25050. class FunctionNode extends CodeNode {
  25051. static get type() {
  25052. return 'FunctionNode';
  25053. }
  25054. /**
  25055. * Constructs a new function node.
  25056. *
  25057. * @param {string} [code=''] - The native code.
  25058. * @param {Array<Node>} [includes=[]] - An array of includes.
  25059. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25060. */
  25061. constructor( code = '', includes = [], language = '' ) {
  25062. super( code, includes, language );
  25063. }
  25064. getNodeType( builder ) {
  25065. return this.getNodeFunction( builder ).type;
  25066. }
  25067. /**
  25068. * Returns the inputs of this function node.
  25069. *
  25070. * @param {NodeBuilder} builder - The current node builder.
  25071. * @return {Array<NodeFunctionInput>} The inputs.
  25072. */
  25073. getInputs( builder ) {
  25074. return this.getNodeFunction( builder ).inputs;
  25075. }
  25076. /**
  25077. * Returns the node function for this function node.
  25078. *
  25079. * @param {NodeBuilder} builder - The current node builder.
  25080. * @return {NodeFunction} The node function.
  25081. */
  25082. getNodeFunction( builder ) {
  25083. const nodeData = builder.getDataFromNode( this );
  25084. let nodeFunction = nodeData.nodeFunction;
  25085. if ( nodeFunction === undefined ) {
  25086. nodeFunction = builder.parser.parseFunction( this.code );
  25087. nodeData.nodeFunction = nodeFunction;
  25088. }
  25089. return nodeFunction;
  25090. }
  25091. generate( builder, output ) {
  25092. super.generate( builder );
  25093. const nodeFunction = this.getNodeFunction( builder );
  25094. const name = nodeFunction.name;
  25095. const type = nodeFunction.type;
  25096. const nodeCode = builder.getCodeFromNode( this, type );
  25097. if ( name !== '' ) {
  25098. // use a custom property name
  25099. nodeCode.name = name;
  25100. }
  25101. const propertyName = builder.getPropertyName( nodeCode );
  25102. const code = this.getNodeFunction( builder ).getCode( propertyName );
  25103. nodeCode.code = code + '\n';
  25104. if ( output === 'property' ) {
  25105. return propertyName;
  25106. } else {
  25107. return builder.format( `${ propertyName }()`, type, output );
  25108. }
  25109. }
  25110. }
  25111. const nativeFn = ( code, includes = [], language = '' ) => {
  25112. for ( let i = 0; i < includes.length; i ++ ) {
  25113. const include = includes[ i ];
  25114. // TSL Function: glslFn, wgslFn
  25115. if ( typeof include === 'function' ) {
  25116. includes[ i ] = include.functionNode;
  25117. }
  25118. }
  25119. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  25120. const fn = ( ...params ) => functionNode.call( ...params );
  25121. fn.functionNode = functionNode;
  25122. return fn;
  25123. };
  25124. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  25125. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  25126. /**
  25127. * `ScriptableNode` uses this class to manage script inputs and outputs.
  25128. *
  25129. * @augments Node
  25130. */
  25131. class ScriptableValueNode extends Node {
  25132. static get type() {
  25133. return 'ScriptableValueNode';
  25134. }
  25135. /**
  25136. * Constructs a new scriptable node.
  25137. *
  25138. * @param {any} [value=null] - The value.
  25139. */
  25140. constructor( value = null ) {
  25141. super();
  25142. /**
  25143. * A reference to the value.
  25144. *
  25145. * @private
  25146. * @default null
  25147. */
  25148. this._value = value;
  25149. /**
  25150. * Depending on the type of `_value`, this property might cache parsed data.
  25151. *
  25152. * @private
  25153. * @default null
  25154. */
  25155. this._cache = null;
  25156. /**
  25157. * If this node represents an input, this property represents the input type.
  25158. *
  25159. * @type {?string}
  25160. * @default null
  25161. */
  25162. this.inputType = null;
  25163. /**
  25164. * If this node represents an output, this property represents the output type.
  25165. *
  25166. * @type {?string}
  25167. * @default null
  25168. */
  25169. this.outputType = null;
  25170. /**
  25171. * An event dispatcher for managing events.
  25172. *
  25173. * @type {EventDispatcher}
  25174. */
  25175. this.events = new EventDispatcher();
  25176. /**
  25177. * This flag can be used for type testing.
  25178. *
  25179. * @type {boolean}
  25180. * @readonly
  25181. * @default true
  25182. */
  25183. this.isScriptableValueNode = true;
  25184. }
  25185. /**
  25186. * Whether this node represents an output or not.
  25187. *
  25188. * @type {boolean}
  25189. * @readonly
  25190. * @default true
  25191. */
  25192. get isScriptableOutputNode() {
  25193. return this.outputType !== null;
  25194. }
  25195. set value( val ) {
  25196. if ( this._value === val ) return;
  25197. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  25198. URL.revokeObjectURL( this._cache );
  25199. this._cache = null;
  25200. }
  25201. this._value = val;
  25202. this.events.dispatchEvent( { type: 'change' } );
  25203. this.refresh();
  25204. }
  25205. /**
  25206. * The node's value.
  25207. *
  25208. * @type {any}
  25209. */
  25210. get value() {
  25211. return this._value;
  25212. }
  25213. /**
  25214. * Dispatches the `refresh` event.
  25215. */
  25216. refresh() {
  25217. this.events.dispatchEvent( { type: 'refresh' } );
  25218. }
  25219. /**
  25220. * The `value` property usually represents a node or even binary data in form of array buffers.
  25221. * In this case, this method tries to return the actual value behind the complex type.
  25222. *
  25223. * @return {any} The value.
  25224. */
  25225. getValue() {
  25226. const value = this.value;
  25227. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  25228. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  25229. } else if ( value && value.value !== null && value.value !== undefined && (
  25230. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  25231. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  25232. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  25233. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  25234. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  25235. ( this.inputType === 'Color' && value.value.isColor ) ||
  25236. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  25237. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  25238. ) ) {
  25239. return value.value;
  25240. }
  25241. return this._cache || value;
  25242. }
  25243. /**
  25244. * Overwritten since the node type is inferred from the value.
  25245. *
  25246. * @param {NodeBuilder} builder - The current node builder.
  25247. * @return {string} The node type.
  25248. */
  25249. getNodeType( builder ) {
  25250. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  25251. }
  25252. setup() {
  25253. return this.value && this.value.isNode ? this.value : float();
  25254. }
  25255. serialize( data ) {
  25256. super.serialize( data );
  25257. if ( this.value !== null ) {
  25258. if ( this.inputType === 'ArrayBuffer' ) {
  25259. data.value = arrayBufferToBase64( this.value );
  25260. } else {
  25261. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  25262. }
  25263. } else {
  25264. data.value = null;
  25265. }
  25266. data.inputType = this.inputType;
  25267. data.outputType = this.outputType;
  25268. }
  25269. deserialize( data ) {
  25270. super.deserialize( data );
  25271. let value = null;
  25272. if ( data.value !== null ) {
  25273. if ( data.inputType === 'ArrayBuffer' ) {
  25274. value = base64ToArrayBuffer( data.value );
  25275. } else if ( data.inputType === 'Texture' ) {
  25276. value = data.meta.textures[ data.value ];
  25277. } else {
  25278. value = data.meta.nodes[ data.value ] || null;
  25279. }
  25280. }
  25281. this.value = value;
  25282. this.inputType = data.inputType;
  25283. this.outputType = data.outputType;
  25284. }
  25285. }
  25286. /**
  25287. * TSL function for creating a scriptable value node.
  25288. *
  25289. * @tsl
  25290. * @function
  25291. * @param {any} [value] - The value.
  25292. * @returns {ScriptableValueNode}
  25293. */
  25294. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  25295. /**
  25296. * A Map-like data structure for managing resources of scriptable nodes.
  25297. *
  25298. * @augments Map
  25299. */
  25300. class Resources extends Map {
  25301. get( key, callback = null, ...params ) {
  25302. if ( this.has( key ) ) return super.get( key );
  25303. if ( callback !== null ) {
  25304. const value = callback( ...params );
  25305. this.set( key, value );
  25306. return value;
  25307. }
  25308. }
  25309. }
  25310. class Parameters {
  25311. constructor( scriptableNode ) {
  25312. this.scriptableNode = scriptableNode;
  25313. }
  25314. get parameters() {
  25315. return this.scriptableNode.parameters;
  25316. }
  25317. get layout() {
  25318. return this.scriptableNode.getLayout();
  25319. }
  25320. getInputLayout( id ) {
  25321. return this.scriptableNode.getInputLayout( id );
  25322. }
  25323. get( name ) {
  25324. const param = this.parameters[ name ];
  25325. const value = param ? param.getValue() : null;
  25326. return value;
  25327. }
  25328. }
  25329. /**
  25330. * Defines the resources (e.g. namespaces) of scriptable nodes.
  25331. *
  25332. * @type {Resources}
  25333. */
  25334. const ScriptableNodeResources = new Resources();
  25335. /**
  25336. * This type of node allows to implement nodes with custom scripts. The script
  25337. * section is represented as an instance of `CodeNode` written with JavaScript.
  25338. * The script itself must adhere to a specific structure.
  25339. *
  25340. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  25341. * - layout: The layout object defines the script's interface (inputs and outputs).
  25342. *
  25343. * ```js
  25344. * ScriptableNodeResources.set( 'TSL', TSL );
  25345. *
  25346. * const scriptableNode = scriptable( js( `
  25347. * layout = {
  25348. * outputType: 'node',
  25349. * elements: [
  25350. * { name: 'source', inputType: 'node' },
  25351. * ]
  25352. * };
  25353. *
  25354. * const { mul, oscSine } = TSL;
  25355. *
  25356. * function main() {
  25357. * const source = parameters.get( 'source' ) || float();
  25358. * return mul( source, oscSine() ) );
  25359. * }
  25360. *
  25361. * ` ) );
  25362. *
  25363. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  25364. *
  25365. * const material = new THREE.MeshBasicNodeMaterial();
  25366. * material.colorNode = scriptableNode;
  25367. * ```
  25368. *
  25369. * @augments Node
  25370. */
  25371. class ScriptableNode extends Node {
  25372. static get type() {
  25373. return 'ScriptableNode';
  25374. }
  25375. /**
  25376. * Constructs a new scriptable node.
  25377. *
  25378. * @param {?CodeNode} [codeNode=null] - The code node.
  25379. * @param {Object} [parameters={}] - The parameters definition.
  25380. */
  25381. constructor( codeNode = null, parameters = {} ) {
  25382. super();
  25383. /**
  25384. * The code node.
  25385. *
  25386. * @type {?CodeNode}
  25387. * @default null
  25388. */
  25389. this.codeNode = codeNode;
  25390. /**
  25391. * The parameters definition.
  25392. *
  25393. * @type {Object}
  25394. * @default {}
  25395. */
  25396. this.parameters = parameters;
  25397. this._local = new Resources();
  25398. this._output = scriptableValue( null );
  25399. this._outputs = {};
  25400. this._source = this.source;
  25401. this._method = null;
  25402. this._object = null;
  25403. this._value = null;
  25404. this._needsOutputUpdate = true;
  25405. this.onRefresh = this.onRefresh.bind( this );
  25406. /**
  25407. * This flag can be used for type testing.
  25408. *
  25409. * @type {boolean}
  25410. * @readonly
  25411. * @default true
  25412. */
  25413. this.isScriptableNode = true;
  25414. }
  25415. /**
  25416. * The source code of the scriptable node.
  25417. *
  25418. * @type {string}
  25419. */
  25420. get source() {
  25421. return this.codeNode ? this.codeNode.code : '';
  25422. }
  25423. /**
  25424. * Sets the reference of a local script variable.
  25425. *
  25426. * @param {string} name - The variable name.
  25427. * @param {Object} value - The reference to set.
  25428. * @return {Resources} The resource map
  25429. */
  25430. setLocal( name, value ) {
  25431. return this._local.set( name, value );
  25432. }
  25433. /**
  25434. * Gets the value of a local script variable.
  25435. *
  25436. * @param {string} name - The variable name.
  25437. * @return {Object} The value.
  25438. */
  25439. getLocal( name ) {
  25440. return this._local.get( name );
  25441. }
  25442. /**
  25443. * Event listener for the `refresh` event.
  25444. */
  25445. onRefresh() {
  25446. this._refresh();
  25447. }
  25448. /**
  25449. * Returns an input from the layout with the given id/name.
  25450. *
  25451. * @param {string} id - The id/name of the input.
  25452. * @return {Object} The element entry.
  25453. */
  25454. getInputLayout( id ) {
  25455. for ( const element of this.getLayout() ) {
  25456. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  25457. return element;
  25458. }
  25459. }
  25460. }
  25461. /**
  25462. * Returns an output from the layout with the given id/name.
  25463. *
  25464. * @param {string} id - The id/name of the output.
  25465. * @return {Object} The element entry.
  25466. */
  25467. getOutputLayout( id ) {
  25468. for ( const element of this.getLayout() ) {
  25469. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  25470. return element;
  25471. }
  25472. }
  25473. }
  25474. /**
  25475. * Defines a script output for the given name and value.
  25476. *
  25477. * @param {string} name - The name of the output.
  25478. * @param {Node} value - The node value.
  25479. * @return {ScriptableNode} A reference to this node.
  25480. */
  25481. setOutput( name, value ) {
  25482. const outputs = this._outputs;
  25483. if ( outputs[ name ] === undefined ) {
  25484. outputs[ name ] = scriptableValue( value );
  25485. } else {
  25486. outputs[ name ].value = value;
  25487. }
  25488. return this;
  25489. }
  25490. /**
  25491. * Returns a script output for the given name.
  25492. *
  25493. * @param {string} name - The name of the output.
  25494. * @return {ScriptableValueNode} The node value.
  25495. */
  25496. getOutput( name ) {
  25497. return this._outputs[ name ];
  25498. }
  25499. /**
  25500. * Returns a parameter for the given name
  25501. *
  25502. * @param {string} name - The name of the parameter.
  25503. * @return {ScriptableValueNode} The node value.
  25504. */
  25505. getParameter( name ) {
  25506. return this.parameters[ name ];
  25507. }
  25508. /**
  25509. * Sets a value for the given parameter name.
  25510. *
  25511. * @param {string} name - The parameter name.
  25512. * @param {any} value - The parameter value.
  25513. * @return {ScriptableNode} A reference to this node.
  25514. */
  25515. setParameter( name, value ) {
  25516. const parameters = this.parameters;
  25517. if ( value && value.isScriptableNode ) {
  25518. this.deleteParameter( name );
  25519. parameters[ name ] = value;
  25520. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  25521. } else if ( value && value.isScriptableValueNode ) {
  25522. this.deleteParameter( name );
  25523. parameters[ name ] = value;
  25524. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25525. } else if ( parameters[ name ] === undefined ) {
  25526. parameters[ name ] = scriptableValue( value );
  25527. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25528. } else {
  25529. parameters[ name ].value = value;
  25530. }
  25531. return this;
  25532. }
  25533. /**
  25534. * Returns the value of this node which is the value of
  25535. * the default output.
  25536. *
  25537. * @return {Node} The value.
  25538. */
  25539. getValue() {
  25540. return this.getDefaultOutput().getValue();
  25541. }
  25542. /**
  25543. * Deletes a parameter from the script.
  25544. *
  25545. * @param {string} name - The parameter to remove.
  25546. * @return {ScriptableNode} A reference to this node.
  25547. */
  25548. deleteParameter( name ) {
  25549. let valueNode = this.parameters[ name ];
  25550. if ( valueNode ) {
  25551. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25552. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  25553. }
  25554. return this;
  25555. }
  25556. /**
  25557. * Deletes all parameters from the script.
  25558. *
  25559. * @return {ScriptableNode} A reference to this node.
  25560. */
  25561. clearParameters() {
  25562. for ( const name of Object.keys( this.parameters ) ) {
  25563. this.deleteParameter( name );
  25564. }
  25565. this.needsUpdate = true;
  25566. return this;
  25567. }
  25568. /**
  25569. * Calls a function from the script.
  25570. *
  25571. * @param {string} name - The function name.
  25572. * @param {...any} params - A list of parameters.
  25573. * @return {any} The result of the function call.
  25574. */
  25575. call( name, ...params ) {
  25576. const object = this.getObject();
  25577. const method = object[ name ];
  25578. if ( typeof method === 'function' ) {
  25579. return method( ...params );
  25580. }
  25581. }
  25582. /**
  25583. * Asynchronously calls a function from the script.
  25584. *
  25585. * @param {string} name - The function name.
  25586. * @param {...any} params - A list of parameters.
  25587. * @return {Promise<any>} The result of the function call.
  25588. */
  25589. async callAsync( name, ...params ) {
  25590. const object = this.getObject();
  25591. const method = object[ name ];
  25592. if ( typeof method === 'function' ) {
  25593. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  25594. }
  25595. }
  25596. /**
  25597. * Overwritten since the node types is inferred from the script's output.
  25598. *
  25599. * @param {NodeBuilder} builder - The current node builder
  25600. * @return {string} The node type.
  25601. */
  25602. getNodeType( builder ) {
  25603. return this.getDefaultOutputNode().getNodeType( builder );
  25604. }
  25605. /**
  25606. * Refreshes the script node.
  25607. *
  25608. * @param {?string} [output=null] - An optional output.
  25609. */
  25610. refresh( output = null ) {
  25611. if ( output !== null ) {
  25612. this.getOutput( output ).refresh();
  25613. } else {
  25614. this._refresh();
  25615. }
  25616. }
  25617. /**
  25618. * Returns an object representation of the script.
  25619. *
  25620. * @return {Object} The result object.
  25621. */
  25622. getObject() {
  25623. if ( this.needsUpdate ) this.dispose();
  25624. if ( this._object !== null ) return this._object;
  25625. //
  25626. const refresh = () => this.refresh();
  25627. const setOutput = ( id, value ) => this.setOutput( id, value );
  25628. const parameters = new Parameters( this );
  25629. const THREE = ScriptableNodeResources.get( 'THREE' );
  25630. const TSL = ScriptableNodeResources.get( 'TSL' );
  25631. const method = this.getMethod();
  25632. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  25633. this._object = method( ...params );
  25634. const layout = this._object.layout;
  25635. if ( layout ) {
  25636. if ( layout.cache === false ) {
  25637. this._local.clear();
  25638. }
  25639. // default output
  25640. this._output.outputType = layout.outputType || null;
  25641. if ( Array.isArray( layout.elements ) ) {
  25642. for ( const element of layout.elements ) {
  25643. const id = element.id || element.name;
  25644. if ( element.inputType ) {
  25645. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  25646. this.getParameter( id ).inputType = element.inputType;
  25647. }
  25648. if ( element.outputType ) {
  25649. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  25650. this.getOutput( id ).outputType = element.outputType;
  25651. }
  25652. }
  25653. }
  25654. }
  25655. return this._object;
  25656. }
  25657. deserialize( data ) {
  25658. super.deserialize( data );
  25659. for ( const name in this.parameters ) {
  25660. let valueNode = this.parameters[ name ];
  25661. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25662. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  25663. }
  25664. }
  25665. /**
  25666. * Returns the layout of the script.
  25667. *
  25668. * @return {Object} The script's layout.
  25669. */
  25670. getLayout() {
  25671. return this.getObject().layout;
  25672. }
  25673. /**
  25674. * Returns default node output of the script.
  25675. *
  25676. * @return {Node} The default node output.
  25677. */
  25678. getDefaultOutputNode() {
  25679. const output = this.getDefaultOutput().value;
  25680. if ( output && output.isNode ) {
  25681. return output;
  25682. }
  25683. return float();
  25684. }
  25685. /**
  25686. * Returns default output of the script.
  25687. *
  25688. * @return {ScriptableValueNode} The default output.
  25689. */
  25690. getDefaultOutput() {
  25691. return this._exec()._output;
  25692. }
  25693. /**
  25694. * Returns a function created from the node's script.
  25695. *
  25696. * @return {Function} The function representing the node's code.
  25697. */
  25698. getMethod() {
  25699. if ( this.needsUpdate ) this.dispose();
  25700. if ( this._method !== null ) return this._method;
  25701. //
  25702. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  25703. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  25704. const properties = interfaceProps.join( ', ' );
  25705. const declarations = 'var ' + properties + '; var output = {};\n';
  25706. const returns = '\nreturn { ...output, ' + properties + ' };';
  25707. const code = declarations + this.codeNode.code + returns;
  25708. //
  25709. this._method = new Function( ...parametersProps, code );
  25710. return this._method;
  25711. }
  25712. /**
  25713. * Frees all internal resources.
  25714. */
  25715. dispose() {
  25716. if ( this._method === null ) return;
  25717. if ( this._object && typeof this._object.dispose === 'function' ) {
  25718. this._object.dispose();
  25719. }
  25720. this._method = null;
  25721. this._object = null;
  25722. this._source = null;
  25723. this._value = null;
  25724. this._needsOutputUpdate = true;
  25725. this._output.value = null;
  25726. this._outputs = {};
  25727. }
  25728. setup() {
  25729. return this.getDefaultOutputNode();
  25730. }
  25731. getCacheKey( force ) {
  25732. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  25733. for ( const param in this.parameters ) {
  25734. values.push( this.parameters[ param ].getCacheKey( force ) );
  25735. }
  25736. return hashArray( values );
  25737. }
  25738. set needsUpdate( value ) {
  25739. if ( value === true ) this.dispose();
  25740. }
  25741. get needsUpdate() {
  25742. return this.source !== this._source;
  25743. }
  25744. /**
  25745. * Executes the `main` function of the script.
  25746. *
  25747. * @private
  25748. * @return {ScriptableNode} A reference to this node.
  25749. */
  25750. _exec() {
  25751. if ( this.codeNode === null ) return this;
  25752. if ( this._needsOutputUpdate === true ) {
  25753. this._value = this.call( 'main' );
  25754. this._needsOutputUpdate = false;
  25755. }
  25756. this._output.value = this._value;
  25757. return this;
  25758. }
  25759. /**
  25760. * Executes the refresh.
  25761. *
  25762. * @private
  25763. */
  25764. _refresh() {
  25765. this.needsUpdate = true;
  25766. this._exec();
  25767. this._output.refresh();
  25768. }
  25769. }
  25770. /**
  25771. * TSL function for creating a scriptable node.
  25772. *
  25773. * @tsl
  25774. * @function
  25775. * @param {CodeNode} [codeNode] - The code node.
  25776. * @param {?Object} [parameters={}] - The parameters definition.
  25777. * @returns {ScriptableNode}
  25778. */
  25779. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  25780. /**
  25781. * Returns a node that represents the `z` coordinate in view space
  25782. * for the current fragment. It's a different representation of the
  25783. * default depth value.
  25784. *
  25785. * This value can be part of a computation that defines how the fog
  25786. * density increases when moving away from the camera.
  25787. *
  25788. * @param {NodeBuilder} builder - The current node builder.
  25789. * @return {Node} The viewZ node.
  25790. */
  25791. function getViewZNode( builder ) {
  25792. let viewZ;
  25793. const getViewZ = builder.context.getViewZ;
  25794. if ( getViewZ !== undefined ) {
  25795. viewZ = getViewZ( this );
  25796. }
  25797. return ( viewZ || positionView.z ).negate();
  25798. }
  25799. /**
  25800. * Constructs a new range factor node.
  25801. *
  25802. * @tsl
  25803. * @function
  25804. * @param {Node} near - Defines the near value.
  25805. * @param {Node} far - Defines the far value.
  25806. */
  25807. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  25808. const viewZ = getViewZNode( builder );
  25809. return smoothstep( near, far, viewZ );
  25810. } );
  25811. /**
  25812. * Represents an exponential squared fog. This type of fog gives
  25813. * a clear view near the camera and a faster than exponentially
  25814. * densening fog farther from the camera.
  25815. *
  25816. * @tsl
  25817. * @function
  25818. * @param {Node} density - Defines the fog density.
  25819. */
  25820. const densityFogFactor = Fn( ( [ density ], builder ) => {
  25821. const viewZ = getViewZNode( builder );
  25822. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  25823. } );
  25824. /**
  25825. * This class can be used to configure a fog for the scene.
  25826. * Nodes of this type are assigned to `Scene.fogNode`.
  25827. *
  25828. * @tsl
  25829. * @function
  25830. * @param {Node} color - Defines the color of the fog.
  25831. * @param {Node} factor - Defines how the fog is factored in the scene.
  25832. */
  25833. const fog = Fn( ( [ color, factor ] ) => {
  25834. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  25835. } );
  25836. // Deprecated
  25837. /**
  25838. * @tsl
  25839. * @function
  25840. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  25841. *
  25842. * @param {Node} color
  25843. * @param {Node} near
  25844. * @param {Node} far
  25845. * @returns {Function}
  25846. */
  25847. function rangeFog( color, near, far ) { // @deprecated, r171
  25848. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  25849. return fog( color, rangeFogFactor( near, far ) );
  25850. }
  25851. /**
  25852. * @tsl
  25853. * @function
  25854. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  25855. *
  25856. * @param {Node} color
  25857. * @param {Node} density
  25858. * @returns {Function}
  25859. */
  25860. function densityFog( color, density ) { // @deprecated, r171
  25861. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  25862. return fog( color, densityFogFactor( density ) );
  25863. }
  25864. let min = null;
  25865. let max = null;
  25866. /**
  25867. * `RangeNode` generates random instanced attribute data in a defined range.
  25868. * An exemplary use case for this utility node is to generate random per-instance
  25869. * colors:
  25870. * ```js
  25871. * const material = new MeshBasicNodeMaterial();
  25872. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  25873. * const mesh = new InstancedMesh( geometry, material, count );
  25874. * ```
  25875. * @augments Node
  25876. */
  25877. class RangeNode extends Node {
  25878. static get type() {
  25879. return 'RangeNode';
  25880. }
  25881. /**
  25882. * Constructs a new range node.
  25883. *
  25884. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  25885. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  25886. */
  25887. constructor( minNode = float(), maxNode = float() ) {
  25888. super();
  25889. /**
  25890. * A node defining the lower bound of the range.
  25891. *
  25892. * @type {Node<any>}
  25893. * @default float()
  25894. */
  25895. this.minNode = minNode;
  25896. /**
  25897. * A node defining the upper bound of the range.
  25898. *
  25899. * @type {Node<any>}
  25900. * @default float()
  25901. */
  25902. this.maxNode = maxNode;
  25903. }
  25904. /**
  25905. * Returns the vector length which is computed based on the range definition.
  25906. *
  25907. * @param {NodeBuilder} builder - The current node builder.
  25908. * @return {number} The vector length.
  25909. */
  25910. getVectorLength( builder ) {
  25911. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  25912. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  25913. return minLength > maxLength ? minLength : maxLength;
  25914. }
  25915. /**
  25916. * This method is overwritten since the node type is inferred from range definition.
  25917. *
  25918. * @param {NodeBuilder} builder - The current node builder.
  25919. * @return {string} The node type.
  25920. */
  25921. getNodeType( builder ) {
  25922. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  25923. }
  25924. setup( builder ) {
  25925. const object = builder.object;
  25926. let output = null;
  25927. if ( object.count > 1 ) {
  25928. const minValue = this.minNode.value;
  25929. const maxValue = this.maxNode.value;
  25930. const minLength = builder.getTypeLength( getValueType( minValue ) );
  25931. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  25932. min = min || new Vector4();
  25933. max = max || new Vector4();
  25934. min.setScalar( 0 );
  25935. max.setScalar( 0 );
  25936. if ( minLength === 1 ) min.setScalar( minValue );
  25937. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  25938. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  25939. if ( maxLength === 1 ) max.setScalar( maxValue );
  25940. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  25941. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  25942. const stride = 4;
  25943. const length = stride * object.count;
  25944. const array = new Float32Array( length );
  25945. for ( let i = 0; i < length; i ++ ) {
  25946. const index = i % stride;
  25947. const minElementValue = min.getComponent( index );
  25948. const maxElementValue = max.getComponent( index );
  25949. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  25950. }
  25951. const nodeType = this.getNodeType( builder );
  25952. if ( object.count <= 4096 ) {
  25953. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  25954. } else {
  25955. // TODO: Improve anonymous buffer attribute creation removing this part
  25956. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  25957. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  25958. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  25959. }
  25960. } else {
  25961. output = float( 0 );
  25962. }
  25963. return output;
  25964. }
  25965. }
  25966. /**
  25967. * TSL function for creating a range node.
  25968. *
  25969. * @tsl
  25970. * @function
  25971. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  25972. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  25973. * @returns {RangeNode}
  25974. */
  25975. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  25976. /**
  25977. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  25978. * about the currently running dispatch and/or the device it is running on.
  25979. *
  25980. * This node can only be used with a WebGPU backend.
  25981. *
  25982. * @augments Node
  25983. */
  25984. class ComputeBuiltinNode extends Node {
  25985. static get type() {
  25986. return 'ComputeBuiltinNode';
  25987. }
  25988. /**
  25989. * Constructs a new compute builtin node.
  25990. *
  25991. * @param {string} builtinName - The built-in name.
  25992. * @param {string} nodeType - The node type.
  25993. */
  25994. constructor( builtinName, nodeType ) {
  25995. super( nodeType );
  25996. /**
  25997. * The built-in name.
  25998. *
  25999. * @private
  26000. * @type {string}
  26001. */
  26002. this._builtinName = builtinName;
  26003. }
  26004. /**
  26005. * This method is overwritten since hash is derived from the built-in name.
  26006. *
  26007. * @param {NodeBuilder} builder - The current node builder.
  26008. * @return {string} The hash.
  26009. */
  26010. getHash( builder ) {
  26011. return this.getBuiltinName( builder );
  26012. }
  26013. /**
  26014. * This method is overwritten since the node type is simply derived from `nodeType`..
  26015. *
  26016. * @param {NodeBuilder} builder - The current node builder.
  26017. * @return {string} The node type.
  26018. */
  26019. getNodeType( /*builder*/ ) {
  26020. return this.nodeType;
  26021. }
  26022. /**
  26023. * Sets the builtin name.
  26024. *
  26025. * @param {string} builtinName - The built-in name.
  26026. * @return {ComputeBuiltinNode} A reference to this node.
  26027. */
  26028. setBuiltinName( builtinName ) {
  26029. this._builtinName = builtinName;
  26030. return this;
  26031. }
  26032. /**
  26033. * Returns the builtin name.
  26034. *
  26035. * @param {NodeBuilder} builder - The current node builder.
  26036. * @return {string} The builtin name.
  26037. */
  26038. getBuiltinName( /*builder*/ ) {
  26039. return this._builtinName;
  26040. }
  26041. /**
  26042. * Whether the current node builder has the builtin or not.
  26043. *
  26044. * @param {NodeBuilder} builder - The current node builder.
  26045. * @return {boolean} Whether the builder has the builtin or not.
  26046. */
  26047. hasBuiltin( builder ) {
  26048. return builder.hasBuiltin( this._builtinName );
  26049. }
  26050. generate( builder, output ) {
  26051. const builtinName = this.getBuiltinName( builder );
  26052. const nodeType = this.getNodeType( builder );
  26053. if ( builder.shaderStage === 'compute' ) {
  26054. return builder.format( builtinName, nodeType, output );
  26055. } else {
  26056. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  26057. return builder.generateConst( nodeType );
  26058. }
  26059. }
  26060. serialize( data ) {
  26061. super.serialize( data );
  26062. data.global = this.global;
  26063. data._builtinName = this._builtinName;
  26064. }
  26065. deserialize( data ) {
  26066. super.deserialize( data );
  26067. this.global = data.global;
  26068. this._builtinName = data._builtinName;
  26069. }
  26070. }
  26071. /**
  26072. * TSL function for creating a compute builtin node.
  26073. *
  26074. * @tsl
  26075. * @function
  26076. * @param {string} name - The built-in name.
  26077. * @param {string} nodeType - The node type.
  26078. * @returns {ComputeBuiltinNode}
  26079. */
  26080. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  26081. /**
  26082. * Represents the number of workgroups dispatched by the compute shader.
  26083. * ```js
  26084. * // Run 512 invocations/threads with a workgroup size of 128.
  26085. * const computeFn = Fn(() => {
  26086. *
  26087. * // numWorkgroups.x = 4
  26088. * storageBuffer.element(0).assign(numWorkgroups.x)
  26089. *
  26090. * })().compute(512, [128]);
  26091. *
  26092. * // Run 512 invocations/threads with the default workgroup size of 64.
  26093. * const computeFn = Fn(() => {
  26094. *
  26095. * // numWorkgroups.x = 8
  26096. * storageBuffer.element(0).assign(numWorkgroups.x)
  26097. *
  26098. * })().compute(512);
  26099. * ```
  26100. *
  26101. * @tsl
  26102. * @type {ComputeBuiltinNode<uvec3>}
  26103. */
  26104. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  26105. /**
  26106. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  26107. * ```js
  26108. * // Execute 12 compute threads with a workgroup size of 3.
  26109. * const computeFn = Fn( () => {
  26110. *
  26111. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  26112. *
  26113. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  26114. *
  26115. * } ).Else( () => {
  26116. *
  26117. * storageBuffer.element( instanceIndex ).assign( 0 );
  26118. *
  26119. * } );
  26120. *
  26121. * } )().compute( 12, [ 3 ] );
  26122. *
  26123. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  26124. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  26125. * ```
  26126. *
  26127. * @tsl
  26128. * @type {ComputeBuiltinNode<uvec3>}
  26129. */
  26130. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  26131. /**
  26132. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  26133. *
  26134. * @tsl
  26135. * @type {ComputeBuiltinNode<uvec3>}
  26136. */
  26137. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  26138. /**
  26139. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  26140. *
  26141. * @tsl
  26142. * @type {ComputeBuiltinNode<uvec3>}
  26143. */
  26144. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  26145. /**
  26146. * A device dependent variable that exposes the size of the current invocation's subgroup.
  26147. *
  26148. * @tsl
  26149. * @type {ComputeBuiltinNode<uint>}
  26150. */
  26151. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  26152. /**
  26153. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  26154. *
  26155. * This node can only be used with a WebGPU backend.
  26156. *
  26157. * @augments Node
  26158. */
  26159. class BarrierNode extends Node {
  26160. /**
  26161. * Constructs a new barrier node.
  26162. *
  26163. * @param {string} scope - The scope defines the behavior of the node.
  26164. */
  26165. constructor( scope ) {
  26166. super();
  26167. this.scope = scope;
  26168. }
  26169. generate( builder ) {
  26170. const { scope } = this;
  26171. const { renderer } = builder;
  26172. if ( renderer.backend.isWebGLBackend === true ) {
  26173. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  26174. } else {
  26175. builder.addLineFlowCode( `${scope}Barrier()`, this );
  26176. }
  26177. }
  26178. }
  26179. /**
  26180. * TSL function for creating a barrier node.
  26181. *
  26182. * @tsl
  26183. * @function
  26184. * @param {string} scope - The scope defines the behavior of the node..
  26185. * @returns {BarrierNode}
  26186. */
  26187. const barrier = nodeProxy( BarrierNode );
  26188. /**
  26189. * TSL function for creating a workgroup barrier. All compute shader
  26190. * invocations must wait for each invocation within a workgroup to
  26191. * complete before the barrier can be surpassed.
  26192. *
  26193. * @tsl
  26194. * @function
  26195. * @returns {BarrierNode}
  26196. */
  26197. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  26198. /**
  26199. * TSL function for creating a storage barrier. All invocations must
  26200. * wait for each access to variables within the 'storage' address space
  26201. * to complete before the barrier can be passed.
  26202. *
  26203. * @tsl
  26204. * @function
  26205. * @returns {BarrierNode}
  26206. */
  26207. const storageBarrier = () => barrier( 'storage' ).toStack();
  26208. /**
  26209. * TSL function for creating a texture barrier. All invocations must
  26210. * wait for each access to variables within the 'texture' address space
  26211. * to complete before the barrier can be passed.
  26212. *
  26213. * @tsl
  26214. * @function
  26215. * @returns {BarrierNode}
  26216. */
  26217. const textureBarrier = () => barrier( 'texture' ).toStack();
  26218. /**
  26219. * Represents an element of a 'workgroup' scoped buffer.
  26220. *
  26221. * @augments ArrayElementNode
  26222. */
  26223. class WorkgroupInfoElementNode extends ArrayElementNode {
  26224. /**
  26225. * Constructs a new workgroup info element node.
  26226. *
  26227. * @param {Node} workgroupInfoNode - The workgroup info node.
  26228. * @param {Node} indexNode - The index node that defines the element access.
  26229. */
  26230. constructor( workgroupInfoNode, indexNode ) {
  26231. super( workgroupInfoNode, indexNode );
  26232. /**
  26233. * This flag can be used for type testing.
  26234. *
  26235. * @type {boolean}
  26236. * @readonly
  26237. * @default true
  26238. */
  26239. this.isWorkgroupInfoElementNode = true;
  26240. }
  26241. generate( builder, output ) {
  26242. let snippet;
  26243. const isAssignContext = builder.context.assign;
  26244. snippet = super.generate( builder );
  26245. if ( isAssignContext !== true ) {
  26246. const type = this.getNodeType( builder );
  26247. snippet = builder.format( snippet, type, output );
  26248. }
  26249. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  26250. return snippet;
  26251. }
  26252. }
  26253. /**
  26254. * A node allowing the user to create a 'workgroup' scoped buffer within the
  26255. * context of a compute shader. Typically, workgroup scoped buffers are
  26256. * created to hold data that is transferred from a global storage scope into
  26257. * a local workgroup scope. For invocations within a workgroup, data
  26258. * access speeds on 'workgroup' scoped buffers can be significantly faster
  26259. * than similar access operations on globally accessible storage buffers.
  26260. *
  26261. * This node can only be used with a WebGPU backend.
  26262. *
  26263. * @augments Node
  26264. */
  26265. class WorkgroupInfoNode extends Node {
  26266. /**
  26267. * Constructs a new buffer scoped to type scope.
  26268. *
  26269. * @param {string} scope - TODO.
  26270. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  26271. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  26272. */
  26273. constructor( scope, bufferType, bufferCount = 0 ) {
  26274. super( bufferType );
  26275. /**
  26276. * The buffer type.
  26277. *
  26278. * @type {string}
  26279. */
  26280. this.bufferType = bufferType;
  26281. /**
  26282. * The buffer count.
  26283. *
  26284. * @type {number}
  26285. * @default 0
  26286. */
  26287. this.bufferCount = bufferCount;
  26288. /**
  26289. * This flag can be used for type testing.
  26290. *
  26291. * @type {boolean}
  26292. * @readonly
  26293. * @default true
  26294. */
  26295. this.isWorkgroupInfoNode = true;
  26296. /**
  26297. * The data type of the array buffer.
  26298. *
  26299. * @type {string}
  26300. */
  26301. this.elementType = bufferType;
  26302. /**
  26303. * TODO.
  26304. *
  26305. * @type {string}
  26306. */
  26307. this.scope = scope;
  26308. }
  26309. /**
  26310. * Sets the name/label of this node.
  26311. *
  26312. * @param {string} name - The name to set.
  26313. * @return {WorkgroupInfoNode} A reference to this node.
  26314. */
  26315. label( name ) {
  26316. this.name = name;
  26317. return this;
  26318. }
  26319. /**
  26320. * Sets the scope of this node.
  26321. *
  26322. * @param {string} scope - The scope to set.
  26323. * @return {WorkgroupInfoNode} A reference to this node.
  26324. */
  26325. setScope( scope ) {
  26326. this.scope = scope;
  26327. return this;
  26328. }
  26329. /**
  26330. * The data type of the array buffer.
  26331. *
  26332. * @return {string} The element type.
  26333. */
  26334. getElementType() {
  26335. return this.elementType;
  26336. }
  26337. /**
  26338. * Overwrites the default implementation since the input type
  26339. * is inferred from the scope.
  26340. *
  26341. * @param {NodeBuilder} builder - The current node builder.
  26342. * @return {string} The input type.
  26343. */
  26344. getInputType( /*builder*/ ) {
  26345. return `${this.scope}Array`;
  26346. }
  26347. /**
  26348. * This method can be used to access elements via an index node.
  26349. *
  26350. * @param {IndexNode} indexNode - indexNode.
  26351. * @return {WorkgroupInfoElementNode} A reference to an element.
  26352. */
  26353. element( indexNode ) {
  26354. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  26355. }
  26356. generate( builder ) {
  26357. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  26358. }
  26359. }
  26360. /**
  26361. * TSL function for creating a workgroup info node.
  26362. * Creates a new 'workgroup' scoped array buffer.
  26363. *
  26364. * @tsl
  26365. * @function
  26366. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  26367. * @param {number} [count=0] - The number of elements in the buffer.
  26368. * @returns {WorkgroupInfoNode}
  26369. */
  26370. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  26371. /**
  26372. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  26373. * within a shader. In an atomic function, any modification to an atomic variable will
  26374. * occur as an indivisible step with a defined order relative to other modifications.
  26375. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  26376. * atomic operations will not interfere with each other.
  26377. *
  26378. * This node can only be used with a WebGPU backend.
  26379. *
  26380. * @augments Node
  26381. */
  26382. class AtomicFunctionNode extends Node {
  26383. static get type() {
  26384. return 'AtomicFunctionNode';
  26385. }
  26386. /**
  26387. * Constructs a new atomic function node.
  26388. *
  26389. * @param {string} method - The signature of the atomic function to construct.
  26390. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26391. * @param {Node} valueNode - The value that mutates the atomic variable.
  26392. */
  26393. constructor( method, pointerNode, valueNode ) {
  26394. super( 'uint' );
  26395. /**
  26396. * The signature of the atomic function to construct.
  26397. *
  26398. * @type {string}
  26399. */
  26400. this.method = method;
  26401. /**
  26402. * An atomic variable or element of an atomic buffer.
  26403. *
  26404. * @type {Node}
  26405. */
  26406. this.pointerNode = pointerNode;
  26407. /**
  26408. * A value that modifies the atomic variable.
  26409. *
  26410. * @type {Node}
  26411. */
  26412. this.valueNode = valueNode;
  26413. /**
  26414. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  26415. *
  26416. * @type {boolean}
  26417. * @default true
  26418. */
  26419. this.parents = true;
  26420. }
  26421. /**
  26422. * Overwrites the default implementation to return the type of
  26423. * the pointer node.
  26424. *
  26425. * @param {NodeBuilder} builder - The current node builder.
  26426. * @return {string} The input type.
  26427. */
  26428. getInputType( builder ) {
  26429. return this.pointerNode.getNodeType( builder );
  26430. }
  26431. /**
  26432. * Overwritten since the node type is inferred from the input type.
  26433. *
  26434. * @param {NodeBuilder} builder - The current node builder.
  26435. * @return {string} The node type.
  26436. */
  26437. getNodeType( builder ) {
  26438. return this.getInputType( builder );
  26439. }
  26440. generate( builder ) {
  26441. const properties = builder.getNodeProperties( this );
  26442. const parents = properties.parents;
  26443. const method = this.method;
  26444. const type = this.getNodeType( builder );
  26445. const inputType = this.getInputType( builder );
  26446. const a = this.pointerNode;
  26447. const b = this.valueNode;
  26448. const params = [];
  26449. params.push( `&${ a.build( builder, inputType ) }` );
  26450. if ( b !== null ) {
  26451. params.push( b.build( builder, inputType ) );
  26452. }
  26453. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  26454. const isVoid = parents.length === 1 && parents[ 0 ].isStackNode === true;
  26455. if ( isVoid ) {
  26456. builder.addLineFlowCode( methodSnippet, this );
  26457. } else {
  26458. if ( properties.constNode === undefined ) {
  26459. properties.constNode = expression( methodSnippet, type ).toConst();
  26460. }
  26461. return properties.constNode.build( builder );
  26462. }
  26463. }
  26464. }
  26465. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  26466. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  26467. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  26468. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  26469. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  26470. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  26471. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  26472. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  26473. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  26474. /**
  26475. * TSL function for creating an atomic function node.
  26476. *
  26477. * @tsl
  26478. * @function
  26479. * @param {string} method - The signature of the atomic function to construct.
  26480. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26481. * @param {Node} valueNode - The value that mutates the atomic variable.
  26482. * @returns {AtomicFunctionNode}
  26483. */
  26484. const atomicNode = nodeProxy( AtomicFunctionNode );
  26485. /**
  26486. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  26487. *
  26488. * @tsl
  26489. * @function
  26490. * @param {string} method - The signature of the atomic function to construct.
  26491. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26492. * @param {Node} valueNode - The value that mutates the atomic variable.
  26493. * @returns {AtomicFunctionNode}
  26494. */
  26495. const atomicFunc = ( method, pointerNode, valueNode ) => {
  26496. return atomicNode( method, pointerNode, valueNode ).toStack();
  26497. };
  26498. /**
  26499. * Loads the value stored in the atomic variable.
  26500. *
  26501. * @tsl
  26502. * @function
  26503. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26504. * @returns {AtomicFunctionNode}
  26505. */
  26506. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  26507. /**
  26508. * Stores a value in the atomic variable.
  26509. *
  26510. * @tsl
  26511. * @function
  26512. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26513. * @param {Node} valueNode - The value that mutates the atomic variable.
  26514. * @returns {AtomicFunctionNode}
  26515. */
  26516. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  26517. /**
  26518. * Increments the value stored in the atomic variable.
  26519. *
  26520. * @tsl
  26521. * @function
  26522. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26523. * @param {Node} valueNode - The value that mutates the atomic variable.
  26524. * @returns {AtomicFunctionNode}
  26525. */
  26526. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  26527. /**
  26528. * Decrements the value stored in the atomic variable.
  26529. *
  26530. * @tsl
  26531. * @function
  26532. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26533. * @param {Node} valueNode - The value that mutates the atomic variable.
  26534. * @returns {AtomicFunctionNode}
  26535. */
  26536. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  26537. /**
  26538. * Stores in an atomic variable the maximum between its current value and a parameter.
  26539. *
  26540. * @tsl
  26541. * @function
  26542. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26543. * @param {Node} valueNode - The value that mutates the atomic variable.
  26544. * @returns {AtomicFunctionNode}
  26545. */
  26546. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  26547. /**
  26548. * Stores in an atomic variable the minimum between its current value and a parameter.
  26549. *
  26550. * @tsl
  26551. * @function
  26552. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26553. * @param {Node} valueNode - The value that mutates the atomic variable.
  26554. * @returns {AtomicFunctionNode}
  26555. */
  26556. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  26557. /**
  26558. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  26559. *
  26560. * @tsl
  26561. * @function
  26562. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26563. * @param {Node} valueNode - The value that mutates the atomic variable.
  26564. * @returns {AtomicFunctionNode}
  26565. */
  26566. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  26567. /**
  26568. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  26569. *
  26570. * @tsl
  26571. * @function
  26572. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26573. * @param {Node} valueNode - The value that mutates the atomic variable.
  26574. * @returns {AtomicFunctionNode}
  26575. */
  26576. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  26577. /**
  26578. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  26579. *
  26580. * @tsl
  26581. * @function
  26582. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26583. * @param {Node} valueNode - The value that mutates the atomic variable.
  26584. * @returns {AtomicFunctionNode}
  26585. */
  26586. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  26587. let uniformsLib;
  26588. function getLightData( light ) {
  26589. uniformsLib = uniformsLib || new WeakMap();
  26590. let uniforms = uniformsLib.get( light );
  26591. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  26592. return uniforms;
  26593. }
  26594. /**
  26595. * TSL function for getting a shadow matrix uniform node for the given light.
  26596. *
  26597. * @tsl
  26598. * @function
  26599. * @param {Light} light -The light source.
  26600. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  26601. */
  26602. function lightShadowMatrix( light ) {
  26603. const data = getLightData( light );
  26604. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  26605. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  26606. light.shadow.updateMatrices( light );
  26607. }
  26608. return light.shadow.matrix;
  26609. } ) );
  26610. }
  26611. /**
  26612. * TSL function for getting projected uv coordinates for the given light.
  26613. * Relevant when using maps with spot lights.
  26614. *
  26615. * @tsl
  26616. * @function
  26617. * @param {Light} light -The light source.
  26618. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  26619. * @returns {Node<vec3>} The projected uvs.
  26620. */
  26621. function lightProjectionUV( light, position = positionWorld ) {
  26622. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  26623. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  26624. return projectionUV;
  26625. }
  26626. /**
  26627. * TSL function for getting the position in world space for the given light.
  26628. *
  26629. * @tsl
  26630. * @function
  26631. * @param {Light} light -The light source.
  26632. * @returns {UniformNode<vec3>} The light's position in world space.
  26633. */
  26634. function lightPosition( light ) {
  26635. const data = getLightData( light );
  26636. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  26637. }
  26638. /**
  26639. * TSL function for getting the light target position in world space for the given light.
  26640. *
  26641. * @tsl
  26642. * @function
  26643. * @param {Light} light -The light source.
  26644. * @returns {UniformNode<vec3>} The light target position in world space.
  26645. */
  26646. function lightTargetPosition( light ) {
  26647. const data = getLightData( light );
  26648. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  26649. }
  26650. /**
  26651. * TSL function for getting the position in view space for the given light.
  26652. *
  26653. * @tsl
  26654. * @function
  26655. * @param {Light} light - The light source.
  26656. * @returns {UniformNode<vec3>} The light's position in view space.
  26657. */
  26658. function lightViewPosition( light ) {
  26659. const data = getLightData( light );
  26660. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  26661. self.value = self.value || new Vector3();
  26662. self.value.setFromMatrixPosition( light.matrixWorld );
  26663. self.value.applyMatrix4( camera.matrixWorldInverse );
  26664. } ) );
  26665. }
  26666. /**
  26667. * TSL function for getting the light target direction for the given light.
  26668. *
  26669. * @tsl
  26670. * @function
  26671. * @param {Light} light -The light source.
  26672. * @returns {Node<vec3>} The light's target direction.
  26673. */
  26674. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  26675. const sortLights = ( lights ) => {
  26676. return lights.sort( ( a, b ) => a.id - b.id );
  26677. };
  26678. const getLightNodeById = ( id, lightNodes ) => {
  26679. for ( const lightNode of lightNodes ) {
  26680. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26681. return lightNode;
  26682. }
  26683. }
  26684. return null;
  26685. };
  26686. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  26687. /**
  26688. * This node represents the scene's lighting and manages the lighting model's life cycle
  26689. * for the current build 3D object. It is responsible for computing the total outgoing
  26690. * light in a given lighting context.
  26691. *
  26692. * @augments Node
  26693. */
  26694. class LightsNode extends Node {
  26695. static get type() {
  26696. return 'LightsNode';
  26697. }
  26698. /**
  26699. * Constructs a new lights node.
  26700. */
  26701. constructor() {
  26702. super( 'vec3' );
  26703. /**
  26704. * A node representing the total diffuse light.
  26705. *
  26706. * @type {Node<vec3>}
  26707. */
  26708. this.totalDiffuseNode = vec3().toVar();
  26709. /**
  26710. * A node representing the total specular light.
  26711. *
  26712. * @type {Node<vec3>}
  26713. */
  26714. this.totalSpecularNode = vec3().toVar();
  26715. /**
  26716. * A node representing the outgoing light.
  26717. *
  26718. * @type {Node<vec3>}
  26719. */
  26720. this.outgoingLightNode = vec3().toVar();
  26721. /**
  26722. * An array representing the lights in the scene.
  26723. *
  26724. * @private
  26725. * @type {Array<Light>}
  26726. */
  26727. this._lights = [];
  26728. /**
  26729. * For each light in the scene, this node will create a
  26730. * corresponding light node.
  26731. *
  26732. * @private
  26733. * @type {?Array<LightingNode>}
  26734. * @default null
  26735. */
  26736. this._lightNodes = null;
  26737. /**
  26738. * A hash for identifying the current light nodes setup.
  26739. *
  26740. * @private
  26741. * @type {?string}
  26742. * @default null
  26743. */
  26744. this._lightNodesHash = null;
  26745. /**
  26746. * `LightsNode` sets this property to `true` by default.
  26747. *
  26748. * @type {boolean}
  26749. * @default true
  26750. */
  26751. this.global = true;
  26752. }
  26753. /**
  26754. * Overwrites the default {@link Node#customCacheKey} implementation by including
  26755. * light data into the cache key.
  26756. *
  26757. * @return {number} The custom cache key.
  26758. */
  26759. customCacheKey() {
  26760. const hashData = [];
  26761. const lights = this._lights;
  26762. for ( let i = 0; i < lights.length; i ++ ) {
  26763. const light = lights[ i ];
  26764. hashData.push( light.id );
  26765. if ( light.isSpotLight === true ) {
  26766. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  26767. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  26768. hashData.push( hashMap, hashColorNode );
  26769. }
  26770. }
  26771. return hashArray( hashData );
  26772. }
  26773. /**
  26774. * Computes a hash value for identifying the current light nodes setup.
  26775. *
  26776. * @param {NodeBuilder} builder - A reference to the current node builder.
  26777. * @return {string} The computed hash.
  26778. */
  26779. getHash( builder ) {
  26780. if ( this._lightNodesHash === null ) {
  26781. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26782. const hash = [];
  26783. for ( const lightNode of this._lightNodes ) {
  26784. hash.push( lightNode.getSelf().getHash() );
  26785. }
  26786. this._lightNodesHash = 'lights-' + hash.join( ',' );
  26787. }
  26788. return this._lightNodesHash;
  26789. }
  26790. analyze( builder ) {
  26791. const properties = builder.getDataFromNode( this );
  26792. for ( const node of properties.nodes ) {
  26793. node.build( builder );
  26794. }
  26795. }
  26796. /**
  26797. * Creates lighting nodes for each scene light. This makes it possible to further
  26798. * process lights in the node system.
  26799. *
  26800. * @param {NodeBuilder} builder - A reference to the current node builder.
  26801. */
  26802. setupLightsNode( builder ) {
  26803. const lightNodes = [];
  26804. const previousLightNodes = this._lightNodes;
  26805. const lights = sortLights( this._lights );
  26806. const nodeLibrary = builder.renderer.library;
  26807. for ( const light of lights ) {
  26808. if ( light.isNode ) {
  26809. lightNodes.push( nodeObject( light ) );
  26810. } else {
  26811. let lightNode = null;
  26812. if ( previousLightNodes !== null ) {
  26813. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  26814. }
  26815. if ( lightNode === null ) {
  26816. // find the corresponding node type for a given light
  26817. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  26818. if ( lightNodeClass === null ) {
  26819. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  26820. continue;
  26821. }
  26822. let lightNode = null;
  26823. if ( ! _lightsNodeRef.has( light ) ) {
  26824. lightNode = nodeObject( new lightNodeClass( light ) );
  26825. _lightsNodeRef.set( light, lightNode );
  26826. } else {
  26827. lightNode = _lightsNodeRef.get( light );
  26828. }
  26829. lightNodes.push( lightNode );
  26830. }
  26831. }
  26832. }
  26833. this._lightNodes = lightNodes;
  26834. }
  26835. /**
  26836. * Sets up a direct light in the lighting model.
  26837. *
  26838. * @param {Object} builder - The builder object containing the context and stack.
  26839. * @param {Object} lightNode - The light node.
  26840. * @param {Object} lightData - The light object containing color and direction properties.
  26841. */
  26842. setupDirectLight( builder, lightNode, lightData ) {
  26843. const { lightingModel, reflectedLight } = builder.context;
  26844. lightingModel.direct( {
  26845. ...lightData,
  26846. lightNode,
  26847. reflectedLight
  26848. }, builder );
  26849. }
  26850. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  26851. const { lightingModel, reflectedLight } = builder.context;
  26852. lightingModel.directRectArea( {
  26853. ...lightData,
  26854. lightNode,
  26855. reflectedLight
  26856. }, builder );
  26857. }
  26858. /**
  26859. * Setups the internal lights by building all respective
  26860. * light nodes.
  26861. *
  26862. * @param {NodeBuilder} builder - A reference to the current node builder.
  26863. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  26864. */
  26865. setupLights( builder, lightNodes ) {
  26866. for ( const lightNode of lightNodes ) {
  26867. lightNode.build( builder );
  26868. }
  26869. }
  26870. getLightNodes( builder ) {
  26871. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26872. return this._lightNodes;
  26873. }
  26874. /**
  26875. * The implementation makes sure that for each light in the scene
  26876. * there is a corresponding light node. By building the light nodes
  26877. * and evaluating the lighting model the outgoing light is computed.
  26878. *
  26879. * @param {NodeBuilder} builder - A reference to the current node builder.
  26880. * @return {Node<vec3>} A node representing the outgoing light.
  26881. */
  26882. setup( builder ) {
  26883. const currentLightsNode = builder.lightsNode;
  26884. builder.lightsNode = this;
  26885. //
  26886. let outgoingLightNode = this.outgoingLightNode;
  26887. const context = builder.context;
  26888. const lightingModel = context.lightingModel;
  26889. const properties = builder.getDataFromNode( this );
  26890. if ( lightingModel ) {
  26891. const { totalDiffuseNode, totalSpecularNode } = this;
  26892. context.outgoingLight = outgoingLightNode;
  26893. const stack = builder.addStack();
  26894. //
  26895. properties.nodes = stack.nodes;
  26896. //
  26897. lightingModel.start( builder );
  26898. //
  26899. const { backdrop, backdropAlpha } = context;
  26900. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26901. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26902. if ( backdrop !== null ) {
  26903. if ( backdropAlpha !== null ) {
  26904. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26905. } else {
  26906. totalDiffuse = vec3( backdrop );
  26907. }
  26908. context.material.transparent = true;
  26909. }
  26910. totalDiffuseNode.assign( totalDiffuse );
  26911. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26912. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26913. //
  26914. lightingModel.finish( builder );
  26915. //
  26916. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26917. } else {
  26918. properties.nodes = [];
  26919. }
  26920. //
  26921. builder.lightsNode = currentLightsNode;
  26922. return outgoingLightNode;
  26923. }
  26924. /**
  26925. * Configures this node with an array of lights.
  26926. *
  26927. * @param {Array<Light>} lights - An array of lights.
  26928. * @return {LightsNode} A reference to this node.
  26929. */
  26930. setLights( lights ) {
  26931. this._lights = lights;
  26932. this._lightNodes = null;
  26933. this._lightNodesHash = null;
  26934. return this;
  26935. }
  26936. /**
  26937. * Returns an array of the scene's lights.
  26938. *
  26939. * @return {Array<Light>} The scene's lights.
  26940. */
  26941. getLights() {
  26942. return this._lights;
  26943. }
  26944. /**
  26945. * Whether the scene has lights or not.
  26946. *
  26947. * @type {boolean}
  26948. */
  26949. get hasLights() {
  26950. return this._lights.length > 0;
  26951. }
  26952. }
  26953. /**
  26954. * TSL function for creating an instance of `LightsNode` and configuring
  26955. * it with the given array of lights.
  26956. *
  26957. * @tsl
  26958. * @function
  26959. * @param {Array<Light>} lights - An array of lights.
  26960. * @return {LightsNode} The created lights node.
  26961. */
  26962. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  26963. /**
  26964. * Base class for all shadow nodes.
  26965. *
  26966. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  26967. * Lighting nodes might share the same shadow node type or use specific ones depending on
  26968. * their requirements.
  26969. *
  26970. * @augments Node
  26971. */
  26972. class ShadowBaseNode extends Node {
  26973. static get type() {
  26974. return 'ShadowBaseNode';
  26975. }
  26976. /**
  26977. * Constructs a new shadow base node.
  26978. *
  26979. * @param {Light} light - The shadow casting light.
  26980. */
  26981. constructor( light ) {
  26982. super();
  26983. /**
  26984. * The shadow casting light.
  26985. *
  26986. * @type {Light}
  26987. */
  26988. this.light = light;
  26989. /**
  26990. * Overwritten since shadows are updated by default per render.
  26991. *
  26992. * @type {string}
  26993. * @default 'render'
  26994. */
  26995. this.updateBeforeType = NodeUpdateType.RENDER;
  26996. /**
  26997. * This flag can be used for type testing.
  26998. *
  26999. * @type {boolean}
  27000. * @readonly
  27001. * @default true
  27002. */
  27003. this.isShadowBaseNode = true;
  27004. }
  27005. /**
  27006. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  27007. *
  27008. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  27009. */
  27010. setupShadowPosition( { context, material } ) {
  27011. // Use assign inside an Fn()
  27012. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  27013. }
  27014. /**
  27015. * Can be called when the shadow isn't required anymore. That can happen when
  27016. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  27017. * to `false`.
  27018. */
  27019. dispose() {
  27020. this.updateBeforeType = NodeUpdateType.NONE;
  27021. }
  27022. }
  27023. /**
  27024. * TSL object that represents the vertex position in world space during the shadow pass.
  27025. *
  27026. * @tsl
  27027. * @type {Node<vec3>}
  27028. */
  27029. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  27030. /**
  27031. * Saves the state of the given renderer and stores it into the given state object.
  27032. *
  27033. * If not state object is provided, the function creates one.
  27034. *
  27035. * @function
  27036. * @param {Renderer} renderer - The renderer.
  27037. * @param {Object} [state={}] - The state.
  27038. * @return {Object} The state.
  27039. */
  27040. function saveRendererState( renderer, state = {} ) {
  27041. state.toneMapping = renderer.toneMapping;
  27042. state.toneMappingExposure = renderer.toneMappingExposure;
  27043. state.outputColorSpace = renderer.outputColorSpace;
  27044. state.renderTarget = renderer.getRenderTarget();
  27045. state.activeCubeFace = renderer.getActiveCubeFace();
  27046. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27047. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27048. state.pixelRatio = renderer.getPixelRatio();
  27049. state.mrt = renderer.getMRT();
  27050. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27051. state.clearAlpha = renderer.getClearAlpha();
  27052. state.autoClear = renderer.autoClear;
  27053. state.scissorTest = renderer.getScissorTest();
  27054. return state;
  27055. }
  27056. /**
  27057. * Saves the state of the given renderer and stores it into the given state object.
  27058. * Besides, the function also resets the state of the renderer to its default values.
  27059. *
  27060. * If not state object is provided, the function creates one.
  27061. *
  27062. * @function
  27063. * @param {Renderer} renderer - The renderer.
  27064. * @param {Object} [state={}] - The state.
  27065. * @return {Object} The state.
  27066. */
  27067. function resetRendererState( renderer, state ) {
  27068. state = saveRendererState( renderer, state );
  27069. renderer.setMRT( null );
  27070. renderer.setRenderObjectFunction( null );
  27071. renderer.setClearColor( 0x000000, 1 );
  27072. renderer.autoClear = true;
  27073. return state;
  27074. }
  27075. /**
  27076. * Restores the state of the given renderer from the given state object.
  27077. *
  27078. * @function
  27079. * @param {Renderer} renderer - The renderer.
  27080. * @param {Object} state - The state to restore.
  27081. */
  27082. function restoreRendererState( renderer, state ) {
  27083. renderer.toneMapping = state.toneMapping;
  27084. renderer.toneMappingExposure = state.toneMappingExposure;
  27085. renderer.outputColorSpace = state.outputColorSpace;
  27086. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  27087. renderer.setRenderObjectFunction( state.renderObjectFunction );
  27088. renderer.setPixelRatio( state.pixelRatio );
  27089. renderer.setMRT( state.mrt );
  27090. renderer.setClearColor( state.clearColor, state.clearAlpha );
  27091. renderer.autoClear = state.autoClear;
  27092. renderer.setScissorTest( state.scissorTest );
  27093. }
  27094. /**
  27095. * Saves the state of the given scene and stores it into the given state object.
  27096. *
  27097. * If not state object is provided, the function creates one.
  27098. *
  27099. * @function
  27100. * @param {Scene} scene - The scene.
  27101. * @param {Object} [state={}] - The state.
  27102. * @return {Object} The state.
  27103. */
  27104. function saveSceneState( scene, state = {} ) {
  27105. state.background = scene.background;
  27106. state.backgroundNode = scene.backgroundNode;
  27107. state.overrideMaterial = scene.overrideMaterial;
  27108. return state;
  27109. }
  27110. /**
  27111. * Saves the state of the given scene and stores it into the given state object.
  27112. * Besides, the function also resets the state of the scene to its default values.
  27113. *
  27114. * If not state object is provided, the function creates one.
  27115. *
  27116. * @function
  27117. * @param {Scene} scene - The scene.
  27118. * @param {Object} [state={}] - The state.
  27119. * @return {Object} The state.
  27120. */
  27121. function resetSceneState( scene, state ) {
  27122. state = saveSceneState( scene, state );
  27123. scene.background = null;
  27124. scene.backgroundNode = null;
  27125. scene.overrideMaterial = null;
  27126. return state;
  27127. }
  27128. /**
  27129. * Restores the state of the given scene from the given state object.
  27130. *
  27131. * @function
  27132. * @param {Scene} scene - The scene.
  27133. * @param {Object} state - The state to restore.
  27134. */
  27135. function restoreSceneState( scene, state ) {
  27136. scene.background = state.background;
  27137. scene.backgroundNode = state.backgroundNode;
  27138. scene.overrideMaterial = state.overrideMaterial;
  27139. }
  27140. /**
  27141. * Saves the state of the given renderer and scene and stores it into the given state object.
  27142. *
  27143. * If not state object is provided, the function creates one.
  27144. *
  27145. * @function
  27146. * @param {Renderer} renderer - The renderer.
  27147. * @param {Scene} scene - The scene.
  27148. * @param {Object} [state={}] - The state.
  27149. * @return {Object} The state.
  27150. */
  27151. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  27152. state = saveRendererState( renderer, state );
  27153. state = saveSceneState( scene, state );
  27154. return state;
  27155. }
  27156. /**
  27157. * Saves the state of the given renderer and scene and stores it into the given state object.
  27158. * Besides, the function also resets the state of the renderer and scene to its default values.
  27159. *
  27160. * If not state object is provided, the function creates one.
  27161. *
  27162. * @function
  27163. * @param {Renderer} renderer - The renderer.
  27164. * @param {Scene} scene - The scene.
  27165. * @param {Object} [state={}] - The state.
  27166. * @return {Object} The state.
  27167. */
  27168. function resetRendererAndSceneState( renderer, scene, state ) {
  27169. state = resetRendererState( renderer, state );
  27170. state = resetSceneState( scene, state );
  27171. return state;
  27172. }
  27173. /**
  27174. * Restores the state of the given renderer and scene from the given state object.
  27175. *
  27176. * @function
  27177. * @param {Renderer} renderer - The renderer.
  27178. * @param {Scene} scene - The scene.
  27179. * @param {Object} state - The state to restore.
  27180. */
  27181. function restoreRendererAndSceneState( renderer, scene, state ) {
  27182. restoreRendererState( renderer, state );
  27183. restoreSceneState( scene, state );
  27184. }
  27185. var RendererUtils = /*#__PURE__*/Object.freeze({
  27186. __proto__: null,
  27187. resetRendererAndSceneState: resetRendererAndSceneState,
  27188. resetRendererState: resetRendererState,
  27189. resetSceneState: resetSceneState,
  27190. restoreRendererAndSceneState: restoreRendererAndSceneState,
  27191. restoreRendererState: restoreRendererState,
  27192. restoreSceneState: restoreSceneState,
  27193. saveRendererAndSceneState: saveRendererAndSceneState,
  27194. saveRendererState: saveRendererState,
  27195. saveSceneState: saveSceneState
  27196. });
  27197. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  27198. /**
  27199. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  27200. * with a binary `[0,1]` result.
  27201. *
  27202. * @method
  27203. * @param {Object} inputs - The input parameter object.
  27204. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27205. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27206. * @return {Node<float>} The filtering result.
  27207. */
  27208. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27209. let basic = texture( depthTexture, shadowCoord.xy ).label( 't_basic' );
  27210. if ( depthTexture.isArrayTexture ) {
  27211. basic = basic.depth( depthLayer );
  27212. }
  27213. return basic.compare( shadowCoord.z );
  27214. } );
  27215. /**
  27216. * A shadow filtering function performing PCF filtering.
  27217. *
  27218. * @method
  27219. * @param {Object} inputs - The input parameter object.
  27220. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27221. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27222. * @param {LightShadow} inputs.shadow - The light shadow.
  27223. * @return {Node<float>} The filtering result.
  27224. */
  27225. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27226. const depthCompare = ( uv, compare ) => {
  27227. let depth = texture( depthTexture, uv );
  27228. if ( depthTexture.isArrayTexture ) {
  27229. depth = depth.depth( depthLayer );
  27230. }
  27231. return depth.compare( compare );
  27232. };
  27233. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27234. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27235. const texelSize = vec2( 1 ).div( mapSize );
  27236. const dx0 = texelSize.x.negate().mul( radius );
  27237. const dy0 = texelSize.y.negate().mul( radius );
  27238. const dx1 = texelSize.x.mul( radius );
  27239. const dy1 = texelSize.y.mul( radius );
  27240. const dx2 = dx0.div( 2 );
  27241. const dy2 = dy0.div( 2 );
  27242. const dx3 = dx1.div( 2 );
  27243. const dy3 = dy1.div( 2 );
  27244. return add(
  27245. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  27246. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  27247. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  27248. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  27249. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  27250. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  27251. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  27252. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  27253. depthCompare( shadowCoord.xy, shadowCoord.z ),
  27254. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  27255. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  27256. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  27257. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  27258. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  27259. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  27260. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  27261. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  27262. ).mul( 1 / 17 );
  27263. } );
  27264. /**
  27265. * A shadow filtering function performing PCF soft filtering.
  27266. *
  27267. * @method
  27268. * @param {Object} inputs - The input parameter object.
  27269. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27270. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27271. * @param {LightShadow} inputs.shadow - The light shadow.
  27272. * @return {Node<float>} The filtering result.
  27273. */
  27274. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27275. const depthCompare = ( uv, compare ) => {
  27276. let depth = texture( depthTexture, uv );
  27277. if ( depthTexture.isArrayTexture ) {
  27278. depth = depth.depth( depthLayer );
  27279. }
  27280. return depth.compare( compare );
  27281. };
  27282. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27283. const texelSize = vec2( 1 ).div( mapSize );
  27284. const dx = texelSize.x;
  27285. const dy = texelSize.y;
  27286. const uv = shadowCoord.xy;
  27287. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  27288. uv.subAssign( f.mul( texelSize ) );
  27289. return add(
  27290. depthCompare( uv, shadowCoord.z ),
  27291. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  27292. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  27293. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  27294. mix(
  27295. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  27296. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  27297. f.x
  27298. ),
  27299. mix(
  27300. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  27301. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  27302. f.x
  27303. ),
  27304. mix(
  27305. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  27306. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  27307. f.y
  27308. ),
  27309. mix(
  27310. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  27311. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  27312. f.y
  27313. ),
  27314. mix(
  27315. mix(
  27316. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  27317. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  27318. f.x
  27319. ),
  27320. mix(
  27321. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  27322. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  27323. f.x
  27324. ),
  27325. f.y
  27326. )
  27327. ).mul( 1 / 9 );
  27328. } );
  27329. /**
  27330. * A shadow filtering function performing VSM filtering.
  27331. *
  27332. * @method
  27333. * @param {Object} inputs - The input parameter object.
  27334. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27335. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27336. * @return {Node<float>} The filtering result.
  27337. */
  27338. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27339. const occlusion = float( 1 ).toVar();
  27340. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  27341. if ( depthTexture.isArrayTexture ) {
  27342. distribution = distribution.depth( depthLayer );
  27343. }
  27344. distribution = distribution.rg;
  27345. const hardShadow = step( shadowCoord.z, distribution.x );
  27346. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  27347. const distance = shadowCoord.z.sub( distribution.x );
  27348. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  27349. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  27350. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  27351. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  27352. } );
  27353. return occlusion;
  27354. } );
  27355. //
  27356. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  27357. let dist = positionWorld.sub( position ).length();
  27358. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  27359. dist = dist.saturate(); // clamp to [ 0, 1 ]
  27360. return dist;
  27361. } );
  27362. const linearShadowDistance = ( light ) => {
  27363. const camera = light.shadow.camera;
  27364. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  27365. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  27366. const referencePosition = objectPosition( light );
  27367. return linearDistance( referencePosition, nearDistance, farDistance );
  27368. };
  27369. /**
  27370. * Retrieves or creates a shadow material for the given light source.
  27371. *
  27372. * This function checks if a shadow material already exists for the provided light.
  27373. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  27374. * in the `shadowMaterialLib` for future use.
  27375. *
  27376. * @param {Light} light - The light source for which the shadow material is needed.
  27377. * If the light is a point light, a depth node is calculated
  27378. * using the linear shadow distance.
  27379. * @returns {NodeMaterial} The shadow material associated with the given light.
  27380. */
  27381. const getShadowMaterial = ( light ) => {
  27382. let material = shadowMaterialLib.get( light );
  27383. if ( material === undefined ) {
  27384. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  27385. material = new NodeMaterial();
  27386. material.colorNode = vec4( 0, 0, 0, 1 );
  27387. material.depthNode = depthNode;
  27388. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  27389. material.name = 'ShadowMaterial';
  27390. material.fog = false;
  27391. shadowMaterialLib.set( light, material );
  27392. }
  27393. return material;
  27394. };
  27395. //
  27396. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  27397. const _shadowRenderObjectKeys = [];
  27398. /**
  27399. * Creates a function to render shadow objects in a scene.
  27400. *
  27401. * @param {Renderer} renderer - The renderer.
  27402. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  27403. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  27404. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  27405. * @return {Function} A function that renders shadow objects.
  27406. *
  27407. * The returned function has the following parameters:
  27408. * @param {Object3D} object - The 3D object to render.
  27409. * @param {Scene} scene - The scene containing the object.
  27410. * @param {Camera} _camera - The camera used for rendering.
  27411. * @param {BufferGeometry} geometry - The geometry of the object.
  27412. * @param {Material} material - The material of the object.
  27413. * @param {Group} group - The group the object belongs to.
  27414. * @param {...any} params - Additional parameters for rendering.
  27415. */
  27416. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  27417. _shadowRenderObjectKeys[ 0 ] = renderer;
  27418. _shadowRenderObjectKeys[ 1 ] = shadow;
  27419. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  27420. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  27421. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  27422. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  27423. if ( useVelocity ) {
  27424. getDataFromObject( object ).useVelocity = true;
  27425. }
  27426. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27427. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  27428. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27429. }
  27430. };
  27431. renderObjectFunction.shadowType = shadowType;
  27432. renderObjectFunction.useVelocity = useVelocity;
  27433. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  27434. }
  27435. _shadowRenderObjectKeys[ 0 ] = null;
  27436. _shadowRenderObjectKeys[ 1 ] = null;
  27437. return renderObjectFunction;
  27438. };
  27439. /**
  27440. * Represents the shader code for the first VSM render pass.
  27441. *
  27442. * @method
  27443. * @param {Object} inputs - The input parameter object.
  27444. * @param {Node<float>} inputs.samples - The number of samples
  27445. * @param {Node<float>} inputs.radius - The radius.
  27446. * @param {Node<float>} inputs.size - The size.
  27447. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  27448. * @return {Node<vec2>} The VSM output.
  27449. */
  27450. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27451. const mean = float( 0 ).toVar( 'meanVertical' );
  27452. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  27453. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27454. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27455. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27456. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27457. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  27458. if ( shadowPass.value.isArrayTexture ) {
  27459. depth = depth.depth( depthLayer );
  27460. }
  27461. depth = depth.x;
  27462. mean.addAssign( depth );
  27463. squaredMean.addAssign( depth.mul( depth ) );
  27464. } );
  27465. mean.divAssign( samples );
  27466. squaredMean.divAssign( samples );
  27467. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27468. return vec2( mean, std_dev );
  27469. } );
  27470. /**
  27471. * Represents the shader code for the second VSM render pass.
  27472. *
  27473. * @method
  27474. * @param {Object} inputs - The input parameter object.
  27475. * @param {Node<float>} inputs.samples - The number of samples
  27476. * @param {Node<float>} inputs.radius - The radius.
  27477. * @param {Node<float>} inputs.size - The size.
  27478. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  27479. * @return {Node<vec2>} The VSM output.
  27480. */
  27481. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27482. const mean = float( 0 ).toVar( 'meanHorizontal' );
  27483. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  27484. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27485. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27486. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27487. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27488. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  27489. if ( shadowPass.value.isArrayTexture ) {
  27490. distribution = distribution.depth( depthLayer );
  27491. }
  27492. mean.addAssign( distribution.x );
  27493. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  27494. } );
  27495. mean.divAssign( samples );
  27496. squaredMean.divAssign( samples );
  27497. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27498. return vec2( mean, std_dev );
  27499. } );
  27500. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  27501. //
  27502. let _rendererState;
  27503. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  27504. /**
  27505. * Represents the default shadow implementation for lighting nodes.
  27506. *
  27507. * @augments ShadowBaseNode
  27508. */
  27509. class ShadowNode extends ShadowBaseNode {
  27510. static get type() {
  27511. return 'ShadowNode';
  27512. }
  27513. /**
  27514. * Constructs a new shadow node.
  27515. *
  27516. * @param {Light} light - The shadow casting light.
  27517. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  27518. */
  27519. constructor( light, shadow = null ) {
  27520. super( light );
  27521. /**
  27522. * The light shadow which defines the properties light's
  27523. * shadow.
  27524. *
  27525. * @type {?LightShadow}
  27526. * @default null
  27527. */
  27528. this.shadow = shadow || light.shadow;
  27529. /**
  27530. * A reference to the shadow map which is a render target.
  27531. *
  27532. * @type {?RenderTarget}
  27533. * @default null
  27534. */
  27535. this.shadowMap = null;
  27536. /**
  27537. * Only relevant for VSM shadows. Render target for the
  27538. * first VSM render pass.
  27539. *
  27540. * @type {?RenderTarget}
  27541. * @default null
  27542. */
  27543. this.vsmShadowMapVertical = null;
  27544. /**
  27545. * Only relevant for VSM shadows. Render target for the
  27546. * second VSM render pass.
  27547. *
  27548. * @type {?RenderTarget}
  27549. * @default null
  27550. */
  27551. this.vsmShadowMapHorizontal = null;
  27552. /**
  27553. * Only relevant for VSM shadows. Node material which
  27554. * is used to render the first VSM pass.
  27555. *
  27556. * @type {?NodeMaterial}
  27557. * @default null
  27558. */
  27559. this.vsmMaterialVertical = null;
  27560. /**
  27561. * Only relevant for VSM shadows. Node material which
  27562. * is used to render the second VSM pass.
  27563. *
  27564. * @type {?NodeMaterial}
  27565. * @default null
  27566. */
  27567. this.vsmMaterialHorizontal = null;
  27568. /**
  27569. * A reference to the output node which defines the
  27570. * final result of this shadow node.
  27571. *
  27572. * @type {?Node}
  27573. * @private
  27574. * @default null
  27575. */
  27576. this._node = null;
  27577. this._cameraFrameId = new WeakMap();
  27578. /**
  27579. * This flag can be used for type testing.
  27580. *
  27581. * @type {boolean}
  27582. * @readonly
  27583. * @default true
  27584. */
  27585. this.isShadowNode = true;
  27586. /**
  27587. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  27588. *
  27589. * @type {number}
  27590. * @readonly
  27591. * @default true
  27592. */
  27593. this.depthLayer = 0;
  27594. }
  27595. /**
  27596. * Setups the shadow filtering.
  27597. *
  27598. * @param {NodeBuilder} builder - A reference to the current node builder.
  27599. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  27600. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  27601. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27602. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  27603. * @param {LightShadow} inputs.shadow - The light shadow.
  27604. * @return {Node<float>} The result node of the shadow filtering.
  27605. */
  27606. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  27607. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  27608. .and( shadowCoord.x.lessThanEqual( 1 ) )
  27609. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  27610. .and( shadowCoord.y.lessThanEqual( 1 ) )
  27611. .and( shadowCoord.z.lessThanEqual( 1 ) );
  27612. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  27613. return frustumTest.select( shadowNode, float( 1 ) );
  27614. }
  27615. /**
  27616. * Setups the shadow coordinates.
  27617. *
  27618. * @param {NodeBuilder} builder - A reference to the current node builder.
  27619. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  27620. * @return {Node<vec3>} The shadow coordinates.
  27621. */
  27622. setupShadowCoord( builder, shadowPosition ) {
  27623. const { shadow } = this;
  27624. const { renderer } = builder;
  27625. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  27626. let shadowCoord = shadowPosition;
  27627. let coordZ;
  27628. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  27629. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  27630. coordZ = shadowCoord.z;
  27631. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  27632. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  27633. }
  27634. } else {
  27635. const w = shadowCoord.w;
  27636. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  27637. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  27638. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  27639. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  27640. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  27641. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  27642. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  27643. }
  27644. shadowCoord = vec3(
  27645. shadowCoord.x,
  27646. shadowCoord.y.oneMinus(), // follow webgpu standards
  27647. coordZ.add( bias )
  27648. );
  27649. return shadowCoord;
  27650. }
  27651. /**
  27652. * Returns the shadow filtering function for the given shadow type.
  27653. *
  27654. * @param {number} type - The shadow type.
  27655. * @return {Function} The filtering function.
  27656. */
  27657. getShadowFilterFn( type ) {
  27658. return _shadowFilterLib[ type ];
  27659. }
  27660. setupRenderTarget( shadow, builder ) {
  27661. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  27662. depthTexture.name = 'ShadowDepthTexture';
  27663. depthTexture.compareFunction = LessCompare;
  27664. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  27665. shadowMap.texture.name = 'ShadowMap';
  27666. shadowMap.texture.type = shadow.mapType;
  27667. shadowMap.depthTexture = depthTexture;
  27668. return { shadowMap, depthTexture };
  27669. }
  27670. /**
  27671. * Setups the shadow output node.
  27672. *
  27673. * @param {NodeBuilder} builder - A reference to the current node builder.
  27674. * @return {Node<vec3>} The shadow output node.
  27675. */
  27676. setupShadow( builder ) {
  27677. const { renderer } = builder;
  27678. const { light, shadow } = this;
  27679. const shadowMapType = renderer.shadowMap.type;
  27680. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  27681. shadow.camera.updateProjectionMatrix();
  27682. // VSM
  27683. if ( shadowMapType === VSMShadowMap ) {
  27684. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  27685. if ( shadowMap.depth > 1 ) {
  27686. if ( ! shadowMap._vsmShadowMapVertical ) {
  27687. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  27688. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  27689. }
  27690. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  27691. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  27692. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  27693. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  27694. }
  27695. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  27696. } else {
  27697. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27698. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27699. }
  27700. let shadowPassVertical = texture( depthTexture );
  27701. if ( depthTexture.isArrayTexture ) {
  27702. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  27703. }
  27704. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  27705. if ( depthTexture.isArrayTexture ) {
  27706. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  27707. }
  27708. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  27709. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27710. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27711. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  27712. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  27713. material.name = 'VSMVertical';
  27714. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  27715. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  27716. material.name = 'VSMHorizontal';
  27717. }
  27718. //
  27719. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  27720. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  27721. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  27722. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  27723. //
  27724. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  27725. if ( filterFn === null ) {
  27726. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  27727. }
  27728. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  27729. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  27730. let shadowColor = texture( shadowMap.texture, shadowCoord );
  27731. if ( depthTexture.isArrayTexture ) {
  27732. shadowColor = shadowColor.depth( this.depthLayer );
  27733. }
  27734. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  27735. this.shadowMap = shadowMap;
  27736. this.shadow.map = shadowMap;
  27737. return shadowOutput;
  27738. }
  27739. /**
  27740. * The implementation performs the setup of the output node. An output is only
  27741. * produces if shadow mapping is globally enabled in the renderer.
  27742. *
  27743. * @param {NodeBuilder} builder - A reference to the current node builder.
  27744. * @return {ShaderCallNodeInternal} The output node.
  27745. */
  27746. setup( builder ) {
  27747. if ( builder.renderer.shadowMap.enabled === false ) return;
  27748. return Fn( () => {
  27749. let node = this._node;
  27750. this.setupShadowPosition( builder );
  27751. if ( node === null ) {
  27752. this._node = node = this.setupShadow( builder );
  27753. }
  27754. if ( builder.material.shadowNode ) { // @deprecated, r171
  27755. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  27756. }
  27757. if ( builder.material.receivedShadowNode ) {
  27758. node = builder.material.receivedShadowNode( node );
  27759. }
  27760. return node;
  27761. } )();
  27762. }
  27763. /**
  27764. * Renders the shadow. The logic of this function could be included
  27765. * into {@link ShadowNode#updateShadow} however more specialized shadow
  27766. * nodes might require a custom shadow map rendering. By having a
  27767. * dedicated method, it's easier to overwrite the default behavior.
  27768. *
  27769. * @param {NodeFrame} frame - A reference to the current node frame.
  27770. */
  27771. renderShadow( frame ) {
  27772. const { shadow, shadowMap, light } = this;
  27773. const { renderer, scene } = frame;
  27774. shadow.updateMatrices( light );
  27775. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  27776. renderer.render( scene, shadow.camera );
  27777. }
  27778. /**
  27779. * Updates the shadow.
  27780. *
  27781. * @param {NodeFrame} frame - A reference to the current node frame.
  27782. */
  27783. updateShadow( frame ) {
  27784. const { shadowMap, light, shadow } = this;
  27785. const { renderer, scene, camera } = frame;
  27786. const shadowType = renderer.shadowMap.type;
  27787. const depthVersion = shadowMap.depthTexture.version;
  27788. this._depthVersionCached = depthVersion;
  27789. const _shadowCameraLayer = shadow.camera.layers.mask;
  27790. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  27791. shadow.camera.layers.mask = camera.layers.mask;
  27792. }
  27793. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27794. const currentMRT = renderer.getMRT();
  27795. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  27796. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  27797. scene.overrideMaterial = getShadowMaterial( light );
  27798. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  27799. renderer.setClearColor( 0x000000, 0 );
  27800. renderer.setRenderTarget( shadowMap );
  27801. this.renderShadow( frame );
  27802. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27803. // vsm blur pass
  27804. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  27805. this.vsmPass( renderer );
  27806. }
  27807. shadow.camera.layers.mask = _shadowCameraLayer;
  27808. restoreRendererAndSceneState( renderer, scene, _rendererState );
  27809. }
  27810. /**
  27811. * For VSM additional render passes are required.
  27812. *
  27813. * @param {Renderer} renderer - A reference to the current renderer.
  27814. */
  27815. vsmPass( renderer ) {
  27816. const { shadow } = this;
  27817. const depth = this.shadowMap.depth;
  27818. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  27819. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  27820. renderer.setRenderTarget( this.vsmShadowMapVertical );
  27821. _quadMesh.material = this.vsmMaterialVertical;
  27822. _quadMesh.render( renderer );
  27823. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  27824. _quadMesh.material = this.vsmMaterialHorizontal;
  27825. _quadMesh.render( renderer );
  27826. }
  27827. /**
  27828. * Frees the internal resources of this shadow node.
  27829. */
  27830. dispose() {
  27831. this.shadowMap.dispose();
  27832. this.shadowMap = null;
  27833. if ( this.vsmShadowMapVertical !== null ) {
  27834. this.vsmShadowMapVertical.dispose();
  27835. this.vsmShadowMapVertical = null;
  27836. this.vsmMaterialVertical.dispose();
  27837. this.vsmMaterialVertical = null;
  27838. }
  27839. if ( this.vsmShadowMapHorizontal !== null ) {
  27840. this.vsmShadowMapHorizontal.dispose();
  27841. this.vsmShadowMapHorizontal = null;
  27842. this.vsmMaterialHorizontal.dispose();
  27843. this.vsmMaterialHorizontal = null;
  27844. }
  27845. super.dispose();
  27846. }
  27847. /**
  27848. * The implementation performs the update of the shadow map if necessary.
  27849. *
  27850. * @param {NodeFrame} frame - A reference to the current node frame.
  27851. */
  27852. updateBefore( frame ) {
  27853. const { shadow } = this;
  27854. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  27855. if ( needsUpdate ) {
  27856. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  27857. needsUpdate = false;
  27858. }
  27859. this._cameraFrameId[ frame.camera ] = frame.frameId;
  27860. }
  27861. if ( needsUpdate ) {
  27862. this.updateShadow( frame );
  27863. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  27864. shadow.needsUpdate = false;
  27865. }
  27866. }
  27867. }
  27868. }
  27869. /**
  27870. * TSL function for creating an instance of `ShadowNode`.
  27871. *
  27872. * @tsl
  27873. * @function
  27874. * @param {Light} light - The shadow casting light.
  27875. * @param {?LightShadow} [shadow] - The light shadow.
  27876. * @return {ShadowNode} The created shadow node.
  27877. */
  27878. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  27879. const _clearColor$1 = /*@__PURE__*/ new Color();
  27880. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  27881. // vector suitable for 2D texture mapping. This code uses the following layout for the
  27882. // 2D texture:
  27883. //
  27884. // xzXZ
  27885. // y Y
  27886. //
  27887. // Y - Positive y direction
  27888. // y - Negative y direction
  27889. // X - Positive x direction
  27890. // x - Negative x direction
  27891. // Z - Positive z direction
  27892. // z - Negative z direction
  27893. //
  27894. // Source and test bed:
  27895. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  27896. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  27897. const v = pos.toVar();
  27898. // Number of texels to avoid at the edge of each square
  27899. const absV = abs( v );
  27900. // Intersect unit cube
  27901. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  27902. absV.mulAssign( scaleToCube );
  27903. // Apply scale to avoid seams
  27904. // two texels less per square (one texel will do for NEAREST)
  27905. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  27906. // Unwrap
  27907. // space: -1 ... 1 range for each square
  27908. //
  27909. // #X## dim := ( 4 , 2 )
  27910. // # # center := ( 1 , 1 )
  27911. const planar = vec2( v.xy ).toVar();
  27912. const almostATexel = texelSizeY.mul( 1.5 );
  27913. const almostOne = almostATexel.oneMinus();
  27914. If( absV.z.greaterThanEqual( almostOne ), () => {
  27915. If( v.z.greaterThan( 0.0 ), () => {
  27916. planar.x.assign( sub( 4.0, v.x ) );
  27917. } );
  27918. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  27919. const signX = sign( v.x );
  27920. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  27921. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  27922. const signY = sign( v.y );
  27923. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  27924. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  27925. } );
  27926. // Transform to UV space
  27927. // scale := 0.5 / dim
  27928. // translate := ( center + 0.5 ) / dim
  27929. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  27930. } ).setLayout( {
  27931. name: 'cubeToUV',
  27932. type: 'vec2',
  27933. inputs: [
  27934. { name: 'pos', type: 'vec3' },
  27935. { name: 'texelSizeY', type: 'float' }
  27936. ]
  27937. } );
  27938. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  27939. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  27940. } );
  27941. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  27942. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27943. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  27944. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  27945. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  27946. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  27947. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  27948. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  27949. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  27950. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  27951. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  27952. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  27953. .mul( 1.0 / 9.0 );
  27954. } );
  27955. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  27956. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  27957. // the vector from the light to the world-space position of the fragment.
  27958. const lightToPosition = shadowCoord.xyz.toVar();
  27959. const lightToPositionLength = lightToPosition.length();
  27960. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  27961. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  27962. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  27963. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  27964. const result = float( 1.0 ).toVar();
  27965. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  27966. // dp = normalized distance from light to fragment position
  27967. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  27968. dp.addAssign( bias );
  27969. // bd3D = base direction 3D
  27970. const bd3D = lightToPosition.normalize();
  27971. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  27972. // percentage-closer filtering
  27973. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  27974. } );
  27975. return result;
  27976. } );
  27977. const _viewport = /*@__PURE__*/ new Vector4();
  27978. const _viewportSize = /*@__PURE__*/ new Vector2();
  27979. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  27980. /**
  27981. * Represents the shadow implementation for point light nodes.
  27982. *
  27983. * @augments ShadowNode
  27984. */
  27985. class PointShadowNode extends ShadowNode {
  27986. static get type() {
  27987. return 'PointShadowNode';
  27988. }
  27989. /**
  27990. * Constructs a new point shadow node.
  27991. *
  27992. * @param {PointLight} light - The shadow casting point light.
  27993. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  27994. */
  27995. constructor( light, shadow = null ) {
  27996. super( light, shadow );
  27997. }
  27998. /**
  27999. * Overwrites the default implementation to return point light shadow specific
  28000. * filtering functions.
  28001. *
  28002. * @param {number} type - The shadow type.
  28003. * @return {Function} The filtering function.
  28004. */
  28005. getShadowFilterFn( type ) {
  28006. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  28007. }
  28008. /**
  28009. * Overwrites the default implementation so the unaltered shadow position is used.
  28010. *
  28011. * @param {NodeBuilder} builder - A reference to the current node builder.
  28012. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28013. * @return {Node<vec3>} The shadow coordinates.
  28014. */
  28015. setupShadowCoord( builder, shadowPosition ) {
  28016. return shadowPosition;
  28017. }
  28018. /**
  28019. * Overwrites the default implementation to only use point light specific
  28020. * shadow filter functions.
  28021. *
  28022. * @param {NodeBuilder} builder - A reference to the current node builder.
  28023. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28024. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28025. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  28026. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28027. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28028. * @param {LightShadow} inputs.shadow - The light shadow.
  28029. * @return {Node<float>} The result node of the shadow filtering.
  28030. */
  28031. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  28032. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  28033. }
  28034. /**
  28035. * Overwrites the default implementation with point light specific
  28036. * rendering code.
  28037. *
  28038. * @param {NodeFrame} frame - A reference to the current node frame.
  28039. */
  28040. renderShadow( frame ) {
  28041. const { shadow, shadowMap, light } = this;
  28042. const { renderer, scene } = frame;
  28043. const shadowFrameExtents = shadow.getFrameExtents();
  28044. _shadowMapSize.copy( shadow.mapSize );
  28045. _shadowMapSize.multiply( shadowFrameExtents );
  28046. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  28047. _viewportSize.copy( shadow.mapSize );
  28048. //
  28049. const previousAutoClear = renderer.autoClear;
  28050. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  28051. const previousClearAlpha = renderer.getClearAlpha();
  28052. renderer.autoClear = false;
  28053. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  28054. renderer.clear();
  28055. const viewportCount = shadow.getViewportCount();
  28056. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  28057. const viewport = shadow.getViewport( vp );
  28058. const x = _viewportSize.x * viewport.x;
  28059. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  28060. _viewport.set(
  28061. x,
  28062. y,
  28063. _viewportSize.x * viewport.z,
  28064. _viewportSize.y * viewport.w
  28065. );
  28066. shadowMap.viewport.copy( _viewport );
  28067. shadow.updateMatrices( light, vp );
  28068. renderer.render( scene, shadow.camera );
  28069. }
  28070. //
  28071. renderer.autoClear = previousAutoClear;
  28072. renderer.setClearColor( previousClearColor, previousClearAlpha );
  28073. }
  28074. }
  28075. /**
  28076. * TSL function for creating an instance of `PointShadowNode`.
  28077. *
  28078. * @tsl
  28079. * @function
  28080. * @param {PointLight} light - The shadow casting point light.
  28081. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28082. * @return {PointShadowNode} The created point shadow node.
  28083. */
  28084. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  28085. /**
  28086. * Base class for analytic light nodes.
  28087. *
  28088. * @augments LightingNode
  28089. */
  28090. class AnalyticLightNode extends LightingNode {
  28091. static get type() {
  28092. return 'AnalyticLightNode';
  28093. }
  28094. /**
  28095. * Constructs a new analytic light node.
  28096. *
  28097. * @param {?Light} [light=null] - The light source.
  28098. */
  28099. constructor( light = null ) {
  28100. super();
  28101. /**
  28102. * The light source.
  28103. *
  28104. * @type {?Light}
  28105. * @default null
  28106. */
  28107. this.light = light;
  28108. /**
  28109. * The light's color value.
  28110. *
  28111. * @type {Color}
  28112. */
  28113. this.color = new Color();
  28114. /**
  28115. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  28116. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  28117. *
  28118. * @type {Node}
  28119. */
  28120. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  28121. /**
  28122. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  28123. * The final color node is represented by a different node when using shadows.
  28124. *
  28125. * @type {?Node}
  28126. * @default null
  28127. */
  28128. this.baseColorNode = null;
  28129. /**
  28130. * Represents the light's shadow.
  28131. *
  28132. * @type {?ShadowNode}
  28133. * @default null
  28134. */
  28135. this.shadowNode = null;
  28136. /**
  28137. * Represents the light's shadow color.
  28138. *
  28139. * @type {?Node}
  28140. * @default null
  28141. */
  28142. this.shadowColorNode = null;
  28143. /**
  28144. * This flag can be used for type testing.
  28145. *
  28146. * @type {boolean}
  28147. * @readonly
  28148. * @default true
  28149. */
  28150. this.isAnalyticLightNode = true;
  28151. /**
  28152. * Overwritten since analytic light nodes are updated
  28153. * once per frame.
  28154. *
  28155. * @type {string}
  28156. * @default 'frame'
  28157. */
  28158. this.updateType = NodeUpdateType.FRAME;
  28159. }
  28160. /**
  28161. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  28162. * `light.id` and `light.castShadow` into the cache key.
  28163. *
  28164. * @return {number} The custom cache key.
  28165. */
  28166. customCacheKey() {
  28167. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  28168. }
  28169. getHash() {
  28170. return this.light.uuid;
  28171. }
  28172. getLightVector( builder ) {
  28173. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  28174. }
  28175. /**
  28176. * Sets up the direct lighting for the analytic light node.
  28177. *
  28178. * @abstract
  28179. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28180. * @return {Object|undefined} The direct light data (color and direction).
  28181. */
  28182. setupDirect( /*builder*/ ) { }
  28183. /**
  28184. * Sets up the direct rect area lighting for the analytic light node.
  28185. *
  28186. * @abstract
  28187. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28188. * @return {Object|undefined} The direct rect area light data.
  28189. */
  28190. setupDirectRectArea( /*builder*/ ) { }
  28191. /**
  28192. * Setups the shadow node for this light. The method exists so concrete light classes
  28193. * can setup different types of shadow nodes.
  28194. *
  28195. * @return {ShadowNode} The created shadow node.
  28196. */
  28197. setupShadowNode() {
  28198. return shadow( this.light );
  28199. }
  28200. /**
  28201. * Setups the shadow for this light. This method is only executed if the light
  28202. * cast shadows and the current build object receives shadows. It incorporates
  28203. * shadows into the lighting computation.
  28204. *
  28205. * @param {NodeBuilder} builder - The current node builder.
  28206. */
  28207. setupShadow( builder ) {
  28208. const { renderer } = builder;
  28209. if ( renderer.shadowMap.enabled === false ) return;
  28210. let shadowColorNode = this.shadowColorNode;
  28211. if ( shadowColorNode === null ) {
  28212. const customShadowNode = this.light.shadow.shadowNode;
  28213. let shadowNode;
  28214. if ( customShadowNode !== undefined ) {
  28215. shadowNode = nodeObject( customShadowNode );
  28216. } else {
  28217. shadowNode = this.setupShadowNode();
  28218. }
  28219. this.shadowNode = shadowNode;
  28220. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  28221. this.baseColorNode = this.colorNode;
  28222. }
  28223. //
  28224. this.colorNode = shadowColorNode;
  28225. }
  28226. /**
  28227. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  28228. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  28229. * invocate the respective interface methods.
  28230. *
  28231. * @param {NodeBuilder} builder - The current node builder.
  28232. */
  28233. setup( builder ) {
  28234. this.colorNode = this.baseColorNode || this.colorNode;
  28235. if ( this.light.castShadow ) {
  28236. if ( builder.object.receiveShadow ) {
  28237. this.setupShadow( builder );
  28238. }
  28239. } else if ( this.shadowNode !== null ) {
  28240. this.shadowNode.dispose();
  28241. this.shadowNode = null;
  28242. this.shadowColorNode = null;
  28243. }
  28244. const directLightData = this.setupDirect( builder );
  28245. const directRectAreaLightData = this.setupDirectRectArea( builder );
  28246. if ( directLightData ) {
  28247. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  28248. }
  28249. if ( directRectAreaLightData ) {
  28250. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  28251. }
  28252. }
  28253. /**
  28254. * The update method is used to update light uniforms per frame.
  28255. * Potentially overwritten in concrete light nodes to update light
  28256. * specific uniforms.
  28257. *
  28258. * @param {NodeFrame} frame - A reference to the current node frame.
  28259. */
  28260. update( /*frame*/ ) {
  28261. const { light } = this;
  28262. this.color.copy( light.color ).multiplyScalar( light.intensity );
  28263. }
  28264. }
  28265. /**
  28266. * Represents a `discard` shader operation in TSL.
  28267. *
  28268. * @method
  28269. * @param {Object} inputs - The input parameter object.
  28270. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  28271. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  28272. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  28273. * @return {Node<float>} The distance falloff.
  28274. */
  28275. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  28276. // based upon Frostbite 3 Moving to Physically-based Rendering
  28277. // page 32, equation 26: E[window1]
  28278. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28279. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  28280. return cutoffDistance.greaterThan( 0 ).select(
  28281. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  28282. distanceFalloff
  28283. );
  28284. } ); // validated
  28285. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  28286. const lightDirection = lightVector.normalize();
  28287. const lightDistance = lightVector.length();
  28288. const attenuation = getDistanceAttenuation( {
  28289. lightDistance,
  28290. cutoffDistance,
  28291. decayExponent
  28292. } );
  28293. const lightColor = color.mul( attenuation );
  28294. return { lightDirection, lightColor };
  28295. };
  28296. /**
  28297. * Module for representing point lights as nodes.
  28298. *
  28299. * @augments AnalyticLightNode
  28300. */
  28301. class PointLightNode extends AnalyticLightNode {
  28302. static get type() {
  28303. return 'PointLightNode';
  28304. }
  28305. /**
  28306. * Constructs a new point light node.
  28307. *
  28308. * @param {?PointLight} [light=null] - The point light source.
  28309. */
  28310. constructor( light = null ) {
  28311. super( light );
  28312. /**
  28313. * Uniform node representing the cutoff distance.
  28314. *
  28315. * @type {UniformNode<float>}
  28316. */
  28317. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  28318. /**
  28319. * Uniform node representing the decay exponent.
  28320. *
  28321. * @type {UniformNode<float>}
  28322. */
  28323. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  28324. }
  28325. /**
  28326. * Overwritten to updated point light specific uniforms.
  28327. *
  28328. * @param {NodeFrame} frame - A reference to the current node frame.
  28329. */
  28330. update( frame ) {
  28331. const { light } = this;
  28332. super.update( frame );
  28333. this.cutoffDistanceNode.value = light.distance;
  28334. this.decayExponentNode.value = light.decay;
  28335. }
  28336. /**
  28337. * Overwritten to setup point light specific shadow.
  28338. *
  28339. * @return {PointShadowNode}
  28340. */
  28341. setupShadowNode() {
  28342. return pointShadow( this.light );
  28343. }
  28344. setupDirect( builder ) {
  28345. return directPointLight( {
  28346. color: this.colorNode,
  28347. lightVector: this.getLightVector( builder ),
  28348. cutoffDistance: this.cutoffDistanceNode,
  28349. decayExponent: this.decayExponentNode
  28350. } );
  28351. }
  28352. }
  28353. /**
  28354. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  28355. *
  28356. * @tsl
  28357. * @function
  28358. * @param {Node<vec2>} coord - The uv coordinates.
  28359. * @return {Node<float>} The result data.
  28360. */
  28361. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  28362. const uv = coord.mul( 2.0 );
  28363. const cx = uv.x.floor();
  28364. const cy = uv.y.floor();
  28365. const result = cx.add( cy ).mod( 2.0 );
  28366. return result.sign();
  28367. } );
  28368. /**
  28369. * Generates a circle based on the uv coordinates.
  28370. *
  28371. * @tsl
  28372. * @function
  28373. * @param {Node<vec2>} coord - The uv to generate the circle.
  28374. * @return {Node<float>} The circle shape.
  28375. */
  28376. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  28377. const alpha = float( 1 ).toVar();
  28378. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  28379. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  28380. const dlen = float( len2.fwidth() ).toVar();
  28381. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  28382. } else {
  28383. len2.greaterThan( 1.0 ).discard();
  28384. }
  28385. return alpha;
  28386. } );
  28387. // Three.js Transpiler
  28388. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  28389. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  28390. const f = float( f_immutable ).toVar();
  28391. const t = float( t_immutable ).toVar();
  28392. const b = bool( b_immutable ).toVar();
  28393. return select( b, t, f );
  28394. } ).setLayout( {
  28395. name: 'mx_select',
  28396. type: 'float',
  28397. inputs: [
  28398. { name: 'b', type: 'bool' },
  28399. { name: 't', type: 'float' },
  28400. { name: 'f', type: 'float' }
  28401. ]
  28402. } );
  28403. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  28404. const b = bool( b_immutable ).toVar();
  28405. const val = float( val_immutable ).toVar();
  28406. return select( b, val.negate(), val );
  28407. } ).setLayout( {
  28408. name: 'mx_negate_if',
  28409. type: 'float',
  28410. inputs: [
  28411. { name: 'val', type: 'float' },
  28412. { name: 'b', type: 'bool' }
  28413. ]
  28414. } );
  28415. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28416. const x = float( x_immutable ).toVar();
  28417. return int( floor( x ) );
  28418. } ).setLayout( {
  28419. name: 'mx_floor',
  28420. type: 'int',
  28421. inputs: [
  28422. { name: 'x', type: 'float' }
  28423. ]
  28424. } );
  28425. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  28426. const x = float( x_immutable ).toVar();
  28427. i.assign( mx_floor( x ) );
  28428. return x.sub( float( i ) );
  28429. } );
  28430. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28431. const t = float( t_immutable ).toVar();
  28432. const s = float( s_immutable ).toVar();
  28433. const v3 = float( v3_immutable ).toVar();
  28434. const v2 = float( v2_immutable ).toVar();
  28435. const v1 = float( v1_immutable ).toVar();
  28436. const v0 = float( v0_immutable ).toVar();
  28437. const s1 = float( sub( 1.0, s ) ).toVar();
  28438. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28439. } ).setLayout( {
  28440. name: 'mx_bilerp_0',
  28441. type: 'float',
  28442. inputs: [
  28443. { name: 'v0', type: 'float' },
  28444. { name: 'v1', type: 'float' },
  28445. { name: 'v2', type: 'float' },
  28446. { name: 'v3', type: 'float' },
  28447. { name: 's', type: 'float' },
  28448. { name: 't', type: 'float' }
  28449. ]
  28450. } );
  28451. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28452. const t = float( t_immutable ).toVar();
  28453. const s = float( s_immutable ).toVar();
  28454. const v3 = vec3( v3_immutable ).toVar();
  28455. const v2 = vec3( v2_immutable ).toVar();
  28456. const v1 = vec3( v1_immutable ).toVar();
  28457. const v0 = vec3( v0_immutable ).toVar();
  28458. const s1 = float( sub( 1.0, s ) ).toVar();
  28459. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28460. } ).setLayout( {
  28461. name: 'mx_bilerp_1',
  28462. type: 'vec3',
  28463. inputs: [
  28464. { name: 'v0', type: 'vec3' },
  28465. { name: 'v1', type: 'vec3' },
  28466. { name: 'v2', type: 'vec3' },
  28467. { name: 'v3', type: 'vec3' },
  28468. { name: 's', type: 'float' },
  28469. { name: 't', type: 'float' }
  28470. ]
  28471. } );
  28472. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  28473. 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 ] ) => {
  28474. const r = float( r_immutable ).toVar();
  28475. const t = float( t_immutable ).toVar();
  28476. const s = float( s_immutable ).toVar();
  28477. const v7 = float( v7_immutable ).toVar();
  28478. const v6 = float( v6_immutable ).toVar();
  28479. const v5 = float( v5_immutable ).toVar();
  28480. const v4 = float( v4_immutable ).toVar();
  28481. const v3 = float( v3_immutable ).toVar();
  28482. const v2 = float( v2_immutable ).toVar();
  28483. const v1 = float( v1_immutable ).toVar();
  28484. const v0 = float( v0_immutable ).toVar();
  28485. const s1 = float( sub( 1.0, s ) ).toVar();
  28486. const t1 = float( sub( 1.0, t ) ).toVar();
  28487. const r1 = float( sub( 1.0, r ) ).toVar();
  28488. 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 ) ) ) ) ) );
  28489. } ).setLayout( {
  28490. name: 'mx_trilerp_0',
  28491. type: 'float',
  28492. inputs: [
  28493. { name: 'v0', type: 'float' },
  28494. { name: 'v1', type: 'float' },
  28495. { name: 'v2', type: 'float' },
  28496. { name: 'v3', type: 'float' },
  28497. { name: 'v4', type: 'float' },
  28498. { name: 'v5', type: 'float' },
  28499. { name: 'v6', type: 'float' },
  28500. { name: 'v7', type: 'float' },
  28501. { name: 's', type: 'float' },
  28502. { name: 't', type: 'float' },
  28503. { name: 'r', type: 'float' }
  28504. ]
  28505. } );
  28506. 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 ] ) => {
  28507. const r = float( r_immutable ).toVar();
  28508. const t = float( t_immutable ).toVar();
  28509. const s = float( s_immutable ).toVar();
  28510. const v7 = vec3( v7_immutable ).toVar();
  28511. const v6 = vec3( v6_immutable ).toVar();
  28512. const v5 = vec3( v5_immutable ).toVar();
  28513. const v4 = vec3( v4_immutable ).toVar();
  28514. const v3 = vec3( v3_immutable ).toVar();
  28515. const v2 = vec3( v2_immutable ).toVar();
  28516. const v1 = vec3( v1_immutable ).toVar();
  28517. const v0 = vec3( v0_immutable ).toVar();
  28518. const s1 = float( sub( 1.0, s ) ).toVar();
  28519. const t1 = float( sub( 1.0, t ) ).toVar();
  28520. const r1 = float( sub( 1.0, r ) ).toVar();
  28521. 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 ) ) ) ) ) );
  28522. } ).setLayout( {
  28523. name: 'mx_trilerp_1',
  28524. type: 'vec3',
  28525. inputs: [
  28526. { name: 'v0', type: 'vec3' },
  28527. { name: 'v1', type: 'vec3' },
  28528. { name: 'v2', type: 'vec3' },
  28529. { name: 'v3', type: 'vec3' },
  28530. { name: 'v4', type: 'vec3' },
  28531. { name: 'v5', type: 'vec3' },
  28532. { name: 'v6', type: 'vec3' },
  28533. { name: 'v7', type: 'vec3' },
  28534. { name: 's', type: 'float' },
  28535. { name: 't', type: 'float' },
  28536. { name: 'r', type: 'float' }
  28537. ]
  28538. } );
  28539. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  28540. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28541. const y = float( y_immutable ).toVar();
  28542. const x = float( x_immutable ).toVar();
  28543. const hash = uint( hash_immutable ).toVar();
  28544. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  28545. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  28546. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  28547. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28548. } ).setLayout( {
  28549. name: 'mx_gradient_float_0',
  28550. type: 'float',
  28551. inputs: [
  28552. { name: 'hash', type: 'uint' },
  28553. { name: 'x', type: 'float' },
  28554. { name: 'y', type: 'float' }
  28555. ]
  28556. } );
  28557. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28558. const z = float( z_immutable ).toVar();
  28559. const y = float( y_immutable ).toVar();
  28560. const x = float( x_immutable ).toVar();
  28561. const hash = uint( hash_immutable ).toVar();
  28562. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  28563. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  28564. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  28565. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28566. } ).setLayout( {
  28567. name: 'mx_gradient_float_1',
  28568. type: 'float',
  28569. inputs: [
  28570. { name: 'hash', type: 'uint' },
  28571. { name: 'x', type: 'float' },
  28572. { name: 'y', type: 'float' },
  28573. { name: 'z', type: 'float' }
  28574. ]
  28575. } );
  28576. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  28577. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28578. const y = float( y_immutable ).toVar();
  28579. const x = float( x_immutable ).toVar();
  28580. const hash = uvec3( hash_immutable ).toVar();
  28581. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  28582. } ).setLayout( {
  28583. name: 'mx_gradient_vec3_0',
  28584. type: 'vec3',
  28585. inputs: [
  28586. { name: 'hash', type: 'uvec3' },
  28587. { name: 'x', type: 'float' },
  28588. { name: 'y', type: 'float' }
  28589. ]
  28590. } );
  28591. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28592. const z = float( z_immutable ).toVar();
  28593. const y = float( y_immutable ).toVar();
  28594. const x = float( x_immutable ).toVar();
  28595. const hash = uvec3( hash_immutable ).toVar();
  28596. 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 ) );
  28597. } ).setLayout( {
  28598. name: 'mx_gradient_vec3_1',
  28599. type: 'vec3',
  28600. inputs: [
  28601. { name: 'hash', type: 'uvec3' },
  28602. { name: 'x', type: 'float' },
  28603. { name: 'y', type: 'float' },
  28604. { name: 'z', type: 'float' }
  28605. ]
  28606. } );
  28607. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  28608. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28609. const v = float( v_immutable ).toVar();
  28610. return mul( 0.6616, v );
  28611. } ).setLayout( {
  28612. name: 'mx_gradient_scale2d_0',
  28613. type: 'float',
  28614. inputs: [
  28615. { name: 'v', type: 'float' }
  28616. ]
  28617. } );
  28618. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28619. const v = float( v_immutable ).toVar();
  28620. return mul( 0.9820, v );
  28621. } ).setLayout( {
  28622. name: 'mx_gradient_scale3d_0',
  28623. type: 'float',
  28624. inputs: [
  28625. { name: 'v', type: 'float' }
  28626. ]
  28627. } );
  28628. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28629. const v = vec3( v_immutable ).toVar();
  28630. return mul( 0.6616, v );
  28631. } ).setLayout( {
  28632. name: 'mx_gradient_scale2d_1',
  28633. type: 'vec3',
  28634. inputs: [
  28635. { name: 'v', type: 'vec3' }
  28636. ]
  28637. } );
  28638. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  28639. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28640. const v = vec3( v_immutable ).toVar();
  28641. return mul( 0.9820, v );
  28642. } ).setLayout( {
  28643. name: 'mx_gradient_scale3d_1',
  28644. type: 'vec3',
  28645. inputs: [
  28646. { name: 'v', type: 'vec3' }
  28647. ]
  28648. } );
  28649. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  28650. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  28651. const k = int( k_immutable ).toVar();
  28652. const x = uint( x_immutable ).toVar();
  28653. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  28654. } ).setLayout( {
  28655. name: 'mx_rotl32',
  28656. type: 'uint',
  28657. inputs: [
  28658. { name: 'x', type: 'uint' },
  28659. { name: 'k', type: 'int' }
  28660. ]
  28661. } );
  28662. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  28663. a.subAssign( c );
  28664. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  28665. c.addAssign( b );
  28666. b.subAssign( a );
  28667. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  28668. a.addAssign( c );
  28669. c.subAssign( b );
  28670. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  28671. b.addAssign( a );
  28672. a.subAssign( c );
  28673. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  28674. c.addAssign( b );
  28675. b.subAssign( a );
  28676. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  28677. a.addAssign( c );
  28678. c.subAssign( b );
  28679. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  28680. b.addAssign( a );
  28681. } );
  28682. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  28683. const c = uint( c_immutable ).toVar();
  28684. const b = uint( b_immutable ).toVar();
  28685. const a = uint( a_immutable ).toVar();
  28686. c.bitXorAssign( b );
  28687. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  28688. a.bitXorAssign( c );
  28689. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  28690. b.bitXorAssign( a );
  28691. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  28692. c.bitXorAssign( b );
  28693. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  28694. a.bitXorAssign( c );
  28695. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  28696. b.bitXorAssign( a );
  28697. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  28698. c.bitXorAssign( b );
  28699. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  28700. return c;
  28701. } ).setLayout( {
  28702. name: 'mx_bjfinal',
  28703. type: 'uint',
  28704. inputs: [
  28705. { name: 'a', type: 'uint' },
  28706. { name: 'b', type: 'uint' },
  28707. { name: 'c', type: 'uint' }
  28708. ]
  28709. } );
  28710. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  28711. const bits = uint( bits_immutable ).toVar();
  28712. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  28713. } ).setLayout( {
  28714. name: 'mx_bits_to_01',
  28715. type: 'float',
  28716. inputs: [
  28717. { name: 'bits', type: 'uint' }
  28718. ]
  28719. } );
  28720. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  28721. const t = float( t_immutable ).toVar();
  28722. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  28723. } ).setLayout( {
  28724. name: 'mx_fade',
  28725. type: 'float',
  28726. inputs: [
  28727. { name: 't', type: 'float' }
  28728. ]
  28729. } );
  28730. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28731. const x = int( x_immutable ).toVar();
  28732. const len = uint( uint( 1 ) ).toVar();
  28733. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  28734. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  28735. } ).setLayout( {
  28736. name: 'mx_hash_int_0',
  28737. type: 'uint',
  28738. inputs: [
  28739. { name: 'x', type: 'int' }
  28740. ]
  28741. } );
  28742. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  28743. const y = int( y_immutable ).toVar();
  28744. const x = int( x_immutable ).toVar();
  28745. const len = uint( uint( 2 ) ).toVar();
  28746. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28747. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28748. a.addAssign( uint( x ) );
  28749. b.addAssign( uint( y ) );
  28750. return mx_bjfinal( a, b, c );
  28751. } ).setLayout( {
  28752. name: 'mx_hash_int_1',
  28753. type: 'uint',
  28754. inputs: [
  28755. { name: 'x', type: 'int' },
  28756. { name: 'y', type: 'int' }
  28757. ]
  28758. } );
  28759. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  28760. const z = int( z_immutable ).toVar();
  28761. const y = int( y_immutable ).toVar();
  28762. const x = int( x_immutable ).toVar();
  28763. const len = uint( uint( 3 ) ).toVar();
  28764. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28765. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28766. a.addAssign( uint( x ) );
  28767. b.addAssign( uint( y ) );
  28768. c.addAssign( uint( z ) );
  28769. return mx_bjfinal( a, b, c );
  28770. } ).setLayout( {
  28771. name: 'mx_hash_int_2',
  28772. type: 'uint',
  28773. inputs: [
  28774. { name: 'x', type: 'int' },
  28775. { name: 'y', type: 'int' },
  28776. { name: 'z', type: 'int' }
  28777. ]
  28778. } );
  28779. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  28780. const xx = int( xx_immutable ).toVar();
  28781. const z = int( z_immutable ).toVar();
  28782. const y = int( y_immutable ).toVar();
  28783. const x = int( x_immutable ).toVar();
  28784. const len = uint( uint( 4 ) ).toVar();
  28785. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28786. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28787. a.addAssign( uint( x ) );
  28788. b.addAssign( uint( y ) );
  28789. c.addAssign( uint( z ) );
  28790. mx_bjmix( a, b, c );
  28791. a.addAssign( uint( xx ) );
  28792. return mx_bjfinal( a, b, c );
  28793. } ).setLayout( {
  28794. name: 'mx_hash_int_3',
  28795. type: 'uint',
  28796. inputs: [
  28797. { name: 'x', type: 'int' },
  28798. { name: 'y', type: 'int' },
  28799. { name: 'z', type: 'int' },
  28800. { name: 'xx', type: 'int' }
  28801. ]
  28802. } );
  28803. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  28804. const yy = int( yy_immutable ).toVar();
  28805. const xx = int( xx_immutable ).toVar();
  28806. const z = int( z_immutable ).toVar();
  28807. const y = int( y_immutable ).toVar();
  28808. const x = int( x_immutable ).toVar();
  28809. const len = uint( uint( 5 ) ).toVar();
  28810. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28811. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28812. a.addAssign( uint( x ) );
  28813. b.addAssign( uint( y ) );
  28814. c.addAssign( uint( z ) );
  28815. mx_bjmix( a, b, c );
  28816. a.addAssign( uint( xx ) );
  28817. b.addAssign( uint( yy ) );
  28818. return mx_bjfinal( a, b, c );
  28819. } ).setLayout( {
  28820. name: 'mx_hash_int_4',
  28821. type: 'uint',
  28822. inputs: [
  28823. { name: 'x', type: 'int' },
  28824. { name: 'y', type: 'int' },
  28825. { name: 'z', type: 'int' },
  28826. { name: 'xx', type: 'int' },
  28827. { name: 'yy', type: 'int' }
  28828. ]
  28829. } );
  28830. 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 ] );
  28831. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  28832. const y = int( y_immutable ).toVar();
  28833. const x = int( x_immutable ).toVar();
  28834. const h = uint( mx_hash_int( x, y ) ).toVar();
  28835. const result = uvec3().toVar();
  28836. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  28837. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  28838. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  28839. return result;
  28840. } ).setLayout( {
  28841. name: 'mx_hash_vec3_0',
  28842. type: 'uvec3',
  28843. inputs: [
  28844. { name: 'x', type: 'int' },
  28845. { name: 'y', type: 'int' }
  28846. ]
  28847. } );
  28848. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  28849. const z = int( z_immutable ).toVar();
  28850. const y = int( y_immutable ).toVar();
  28851. const x = int( x_immutable ).toVar();
  28852. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  28853. const result = uvec3().toVar();
  28854. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  28855. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  28856. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  28857. return result;
  28858. } ).setLayout( {
  28859. name: 'mx_hash_vec3_1',
  28860. type: 'uvec3',
  28861. inputs: [
  28862. { name: 'x', type: 'int' },
  28863. { name: 'y', type: 'int' },
  28864. { name: 'z', type: 'int' }
  28865. ]
  28866. } );
  28867. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  28868. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28869. const p = vec2( p_immutable ).toVar();
  28870. const X = int().toVar(), Y = int().toVar();
  28871. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28872. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28873. const u = float( mx_fade( fx ) ).toVar();
  28874. const v = float( mx_fade( fy ) ).toVar();
  28875. 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();
  28876. return mx_gradient_scale2d( result );
  28877. } ).setLayout( {
  28878. name: 'mx_perlin_noise_float_0',
  28879. type: 'float',
  28880. inputs: [
  28881. { name: 'p', type: 'vec2' }
  28882. ]
  28883. } );
  28884. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28885. const p = vec3( p_immutable ).toVar();
  28886. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28887. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28888. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28889. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  28890. const u = float( mx_fade( fx ) ).toVar();
  28891. const v = float( mx_fade( fy ) ).toVar();
  28892. const w = float( mx_fade( fz ) ).toVar();
  28893. 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();
  28894. return mx_gradient_scale3d( result );
  28895. } ).setLayout( {
  28896. name: 'mx_perlin_noise_float_1',
  28897. type: 'float',
  28898. inputs: [
  28899. { name: 'p', type: 'vec3' }
  28900. ]
  28901. } );
  28902. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  28903. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28904. const p = vec2( p_immutable ).toVar();
  28905. const X = int().toVar(), Y = int().toVar();
  28906. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28907. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28908. const u = float( mx_fade( fx ) ).toVar();
  28909. const v = float( mx_fade( fy ) ).toVar();
  28910. 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();
  28911. return mx_gradient_scale2d( result );
  28912. } ).setLayout( {
  28913. name: 'mx_perlin_noise_vec3_0',
  28914. type: 'vec3',
  28915. inputs: [
  28916. { name: 'p', type: 'vec2' }
  28917. ]
  28918. } );
  28919. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28920. const p = vec3( p_immutable ).toVar();
  28921. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28922. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28923. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28924. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  28925. const u = float( mx_fade( fx ) ).toVar();
  28926. const v = float( mx_fade( fy ) ).toVar();
  28927. const w = float( mx_fade( fz ) ).toVar();
  28928. 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();
  28929. return mx_gradient_scale3d( result );
  28930. } ).setLayout( {
  28931. name: 'mx_perlin_noise_vec3_1',
  28932. type: 'vec3',
  28933. inputs: [
  28934. { name: 'p', type: 'vec3' }
  28935. ]
  28936. } );
  28937. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  28938. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28939. const p = float( p_immutable ).toVar();
  28940. const ix = int( mx_floor( p ) ).toVar();
  28941. return mx_bits_to_01( mx_hash_int( ix ) );
  28942. } ).setLayout( {
  28943. name: 'mx_cell_noise_float_0',
  28944. type: 'float',
  28945. inputs: [
  28946. { name: 'p', type: 'float' }
  28947. ]
  28948. } );
  28949. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28950. const p = vec2( p_immutable ).toVar();
  28951. const ix = int( mx_floor( p.x ) ).toVar();
  28952. const iy = int( mx_floor( p.y ) ).toVar();
  28953. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  28954. } ).setLayout( {
  28955. name: 'mx_cell_noise_float_1',
  28956. type: 'float',
  28957. inputs: [
  28958. { name: 'p', type: 'vec2' }
  28959. ]
  28960. } );
  28961. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28962. const p = vec3( p_immutable ).toVar();
  28963. const ix = int( mx_floor( p.x ) ).toVar();
  28964. const iy = int( mx_floor( p.y ) ).toVar();
  28965. const iz = int( mx_floor( p.z ) ).toVar();
  28966. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  28967. } ).setLayout( {
  28968. name: 'mx_cell_noise_float_2',
  28969. type: 'float',
  28970. inputs: [
  28971. { name: 'p', type: 'vec3' }
  28972. ]
  28973. } );
  28974. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28975. const p = vec4( p_immutable ).toVar();
  28976. const ix = int( mx_floor( p.x ) ).toVar();
  28977. const iy = int( mx_floor( p.y ) ).toVar();
  28978. const iz = int( mx_floor( p.z ) ).toVar();
  28979. const iw = int( mx_floor( p.w ) ).toVar();
  28980. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  28981. } ).setLayout( {
  28982. name: 'mx_cell_noise_float_3',
  28983. type: 'float',
  28984. inputs: [
  28985. { name: 'p', type: 'vec4' }
  28986. ]
  28987. } );
  28988. 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 ] );
  28989. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28990. const p = float( p_immutable ).toVar();
  28991. const ix = int( mx_floor( p ) ).toVar();
  28992. 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 ) ) ) );
  28993. } ).setLayout( {
  28994. name: 'mx_cell_noise_vec3_0',
  28995. type: 'vec3',
  28996. inputs: [
  28997. { name: 'p', type: 'float' }
  28998. ]
  28999. } );
  29000. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29001. const p = vec2( p_immutable ).toVar();
  29002. const ix = int( mx_floor( p.x ) ).toVar();
  29003. const iy = int( mx_floor( p.y ) ).toVar();
  29004. 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 ) ) ) );
  29005. } ).setLayout( {
  29006. name: 'mx_cell_noise_vec3_1',
  29007. type: 'vec3',
  29008. inputs: [
  29009. { name: 'p', type: 'vec2' }
  29010. ]
  29011. } );
  29012. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29013. const p = vec3( p_immutable ).toVar();
  29014. const ix = int( mx_floor( p.x ) ).toVar();
  29015. const iy = int( mx_floor( p.y ) ).toVar();
  29016. const iz = int( mx_floor( p.z ) ).toVar();
  29017. 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 ) ) ) );
  29018. } ).setLayout( {
  29019. name: 'mx_cell_noise_vec3_2',
  29020. type: 'vec3',
  29021. inputs: [
  29022. { name: 'p', type: 'vec3' }
  29023. ]
  29024. } );
  29025. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29026. const p = vec4( p_immutable ).toVar();
  29027. const ix = int( mx_floor( p.x ) ).toVar();
  29028. const iy = int( mx_floor( p.y ) ).toVar();
  29029. const iz = int( mx_floor( p.z ) ).toVar();
  29030. const iw = int( mx_floor( p.w ) ).toVar();
  29031. 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 ) ) ) );
  29032. } ).setLayout( {
  29033. name: 'mx_cell_noise_vec3_3',
  29034. type: 'vec3',
  29035. inputs: [
  29036. { name: 'p', type: 'vec4' }
  29037. ]
  29038. } );
  29039. 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 ] );
  29040. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29041. const diminish = float( diminish_immutable ).toVar();
  29042. const lacunarity = float( lacunarity_immutable ).toVar();
  29043. const octaves = int( octaves_immutable ).toVar();
  29044. const p = vec3( p_immutable ).toVar();
  29045. const result = float( 0.0 ).toVar();
  29046. const amplitude = float( 1.0 ).toVar();
  29047. Loop( octaves, () => {
  29048. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  29049. amplitude.mulAssign( diminish );
  29050. p.mulAssign( lacunarity );
  29051. } );
  29052. return result;
  29053. } ).setLayout( {
  29054. name: 'mx_fractal_noise_float',
  29055. type: 'float',
  29056. inputs: [
  29057. { name: 'p', type: 'vec3' },
  29058. { name: 'octaves', type: 'int' },
  29059. { name: 'lacunarity', type: 'float' },
  29060. { name: 'diminish', type: 'float' }
  29061. ]
  29062. } );
  29063. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29064. const diminish = float( diminish_immutable ).toVar();
  29065. const lacunarity = float( lacunarity_immutable ).toVar();
  29066. const octaves = int( octaves_immutable ).toVar();
  29067. const p = vec3( p_immutable ).toVar();
  29068. const result = vec3( 0.0 ).toVar();
  29069. const amplitude = float( 1.0 ).toVar();
  29070. Loop( octaves, () => {
  29071. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  29072. amplitude.mulAssign( diminish );
  29073. p.mulAssign( lacunarity );
  29074. } );
  29075. return result;
  29076. } ).setLayout( {
  29077. name: 'mx_fractal_noise_vec3',
  29078. type: 'vec3',
  29079. inputs: [
  29080. { name: 'p', type: 'vec3' },
  29081. { name: 'octaves', type: 'int' },
  29082. { name: 'lacunarity', type: 'float' },
  29083. { name: 'diminish', type: 'float' }
  29084. ]
  29085. } );
  29086. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29087. const diminish = float( diminish_immutable ).toVar();
  29088. const lacunarity = float( lacunarity_immutable ).toVar();
  29089. const octaves = int( octaves_immutable ).toVar();
  29090. const p = vec3( p_immutable ).toVar();
  29091. 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 ) );
  29092. } ).setLayout( {
  29093. name: 'mx_fractal_noise_vec2',
  29094. type: 'vec2',
  29095. inputs: [
  29096. { name: 'p', type: 'vec3' },
  29097. { name: 'octaves', type: 'int' },
  29098. { name: 'lacunarity', type: 'float' },
  29099. { name: 'diminish', type: 'float' }
  29100. ]
  29101. } );
  29102. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29103. const diminish = float( diminish_immutable ).toVar();
  29104. const lacunarity = float( lacunarity_immutable ).toVar();
  29105. const octaves = int( octaves_immutable ).toVar();
  29106. const p = vec3( p_immutable ).toVar();
  29107. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  29108. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  29109. return vec4( c, f );
  29110. } ).setLayout( {
  29111. name: 'mx_fractal_noise_vec4',
  29112. type: 'vec4',
  29113. inputs: [
  29114. { name: 'p', type: 'vec3' },
  29115. { name: 'octaves', type: 'int' },
  29116. { name: 'lacunarity', type: 'float' },
  29117. { name: 'diminish', type: 'float' }
  29118. ]
  29119. } );
  29120. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  29121. const metric = int( metric_immutable ).toVar();
  29122. const jitter = float( jitter_immutable ).toVar();
  29123. const yoff = int( yoff_immutable ).toVar();
  29124. const xoff = int( xoff_immutable ).toVar();
  29125. const y = int( y_immutable ).toVar();
  29126. const x = int( x_immutable ).toVar();
  29127. const p = vec2( p_immutable ).toVar();
  29128. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  29129. const off = vec2( tmp.x, tmp.y ).toVar();
  29130. off.subAssign( 0.5 );
  29131. off.mulAssign( jitter );
  29132. off.addAssign( 0.5 );
  29133. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  29134. const diff = vec2( cellpos.sub( p ) ).toVar();
  29135. If( metric.equal( int( 2 ) ), () => {
  29136. return abs( diff.x ).add( abs( diff.y ) );
  29137. } );
  29138. If( metric.equal( int( 3 ) ), () => {
  29139. return max$1( abs( diff.x ), abs( diff.y ) );
  29140. } );
  29141. return dot( diff, diff );
  29142. } ).setLayout( {
  29143. name: 'mx_worley_distance_0',
  29144. type: 'float',
  29145. inputs: [
  29146. { name: 'p', type: 'vec2' },
  29147. { name: 'x', type: 'int' },
  29148. { name: 'y', type: 'int' },
  29149. { name: 'xoff', type: 'int' },
  29150. { name: 'yoff', type: 'int' },
  29151. { name: 'jitter', type: 'float' },
  29152. { name: 'metric', type: 'int' }
  29153. ]
  29154. } );
  29155. 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 ] ) => {
  29156. const metric = int( metric_immutable ).toVar();
  29157. const jitter = float( jitter_immutable ).toVar();
  29158. const zoff = int( zoff_immutable ).toVar();
  29159. const yoff = int( yoff_immutable ).toVar();
  29160. const xoff = int( xoff_immutable ).toVar();
  29161. const z = int( z_immutable ).toVar();
  29162. const y = int( y_immutable ).toVar();
  29163. const x = int( x_immutable ).toVar();
  29164. const p = vec3( p_immutable ).toVar();
  29165. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  29166. off.subAssign( 0.5 );
  29167. off.mulAssign( jitter );
  29168. off.addAssign( 0.5 );
  29169. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  29170. const diff = vec3( cellpos.sub( p ) ).toVar();
  29171. If( metric.equal( int( 2 ) ), () => {
  29172. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  29173. } );
  29174. If( metric.equal( int( 3 ) ), () => {
  29175. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  29176. } );
  29177. return dot( diff, diff );
  29178. } ).setLayout( {
  29179. name: 'mx_worley_distance_1',
  29180. type: 'float',
  29181. inputs: [
  29182. { name: 'p', type: 'vec3' },
  29183. { name: 'x', type: 'int' },
  29184. { name: 'y', type: 'int' },
  29185. { name: 'z', type: 'int' },
  29186. { name: 'xoff', type: 'int' },
  29187. { name: 'yoff', type: 'int' },
  29188. { name: 'zoff', type: 'int' },
  29189. { name: 'jitter', type: 'float' },
  29190. { name: 'metric', type: 'int' }
  29191. ]
  29192. } );
  29193. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  29194. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29195. const metric = int( metric_immutable ).toVar();
  29196. const jitter = float( jitter_immutable ).toVar();
  29197. const p = vec2( p_immutable ).toVar();
  29198. const X = int().toVar(), Y = int().toVar();
  29199. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29200. const sqdist = float( 1e6 ).toVar();
  29201. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29202. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29203. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29204. sqdist.assign( min$1( sqdist, dist ) );
  29205. } );
  29206. } );
  29207. If( metric.equal( int( 0 ) ), () => {
  29208. sqdist.assign( sqrt( sqdist ) );
  29209. } );
  29210. return sqdist;
  29211. } ).setLayout( {
  29212. name: 'mx_worley_noise_float_0',
  29213. type: 'float',
  29214. inputs: [
  29215. { name: 'p', type: 'vec2' },
  29216. { name: 'jitter', type: 'float' },
  29217. { name: 'metric', type: 'int' }
  29218. ]
  29219. } );
  29220. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29221. const metric = int( metric_immutable ).toVar();
  29222. const jitter = float( jitter_immutable ).toVar();
  29223. const p = vec2( p_immutable ).toVar();
  29224. const X = int().toVar(), Y = int().toVar();
  29225. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29226. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29227. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29228. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29229. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29230. If( dist.lessThan( sqdist.x ), () => {
  29231. sqdist.y.assign( sqdist.x );
  29232. sqdist.x.assign( dist );
  29233. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29234. sqdist.y.assign( dist );
  29235. } );
  29236. } );
  29237. } );
  29238. If( metric.equal( int( 0 ) ), () => {
  29239. sqdist.assign( sqrt( sqdist ) );
  29240. } );
  29241. return sqdist;
  29242. } ).setLayout( {
  29243. name: 'mx_worley_noise_vec2_0',
  29244. type: 'vec2',
  29245. inputs: [
  29246. { name: 'p', type: 'vec2' },
  29247. { name: 'jitter', type: 'float' },
  29248. { name: 'metric', type: 'int' }
  29249. ]
  29250. } );
  29251. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29252. const metric = int( metric_immutable ).toVar();
  29253. const jitter = float( jitter_immutable ).toVar();
  29254. const p = vec2( p_immutable ).toVar();
  29255. const X = int().toVar(), Y = int().toVar();
  29256. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29257. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29258. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29259. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29260. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29261. If( dist.lessThan( sqdist.x ), () => {
  29262. sqdist.z.assign( sqdist.y );
  29263. sqdist.y.assign( sqdist.x );
  29264. sqdist.x.assign( dist );
  29265. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29266. sqdist.z.assign( sqdist.y );
  29267. sqdist.y.assign( dist );
  29268. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29269. sqdist.z.assign( dist );
  29270. } );
  29271. } );
  29272. } );
  29273. If( metric.equal( int( 0 ) ), () => {
  29274. sqdist.assign( sqrt( sqdist ) );
  29275. } );
  29276. return sqdist;
  29277. } ).setLayout( {
  29278. name: 'mx_worley_noise_vec3_0',
  29279. type: 'vec3',
  29280. inputs: [
  29281. { name: 'p', type: 'vec2' },
  29282. { name: 'jitter', type: 'float' },
  29283. { name: 'metric', type: 'int' }
  29284. ]
  29285. } );
  29286. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29287. const metric = int( metric_immutable ).toVar();
  29288. const jitter = float( jitter_immutable ).toVar();
  29289. const p = vec3( p_immutable ).toVar();
  29290. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29291. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29292. const sqdist = float( 1e6 ).toVar();
  29293. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29294. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29295. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29296. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29297. sqdist.assign( min$1( sqdist, dist ) );
  29298. } );
  29299. } );
  29300. } );
  29301. If( metric.equal( int( 0 ) ), () => {
  29302. sqdist.assign( sqrt( sqdist ) );
  29303. } );
  29304. return sqdist;
  29305. } ).setLayout( {
  29306. name: 'mx_worley_noise_float_1',
  29307. type: 'float',
  29308. inputs: [
  29309. { name: 'p', type: 'vec3' },
  29310. { name: 'jitter', type: 'float' },
  29311. { name: 'metric', type: 'int' }
  29312. ]
  29313. } );
  29314. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  29315. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29316. const metric = int( metric_immutable ).toVar();
  29317. const jitter = float( jitter_immutable ).toVar();
  29318. const p = vec3( p_immutable ).toVar();
  29319. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29320. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29321. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29322. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29323. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29324. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29325. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29326. If( dist.lessThan( sqdist.x ), () => {
  29327. sqdist.y.assign( sqdist.x );
  29328. sqdist.x.assign( dist );
  29329. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29330. sqdist.y.assign( dist );
  29331. } );
  29332. } );
  29333. } );
  29334. } );
  29335. If( metric.equal( int( 0 ) ), () => {
  29336. sqdist.assign( sqrt( sqdist ) );
  29337. } );
  29338. return sqdist;
  29339. } ).setLayout( {
  29340. name: 'mx_worley_noise_vec2_1',
  29341. type: 'vec2',
  29342. inputs: [
  29343. { name: 'p', type: 'vec3' },
  29344. { name: 'jitter', type: 'float' },
  29345. { name: 'metric', type: 'int' }
  29346. ]
  29347. } );
  29348. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  29349. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29350. const metric = int( metric_immutable ).toVar();
  29351. const jitter = float( jitter_immutable ).toVar();
  29352. const p = vec3( p_immutable ).toVar();
  29353. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29354. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29355. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29356. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29357. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29358. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29359. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29360. If( dist.lessThan( sqdist.x ), () => {
  29361. sqdist.z.assign( sqdist.y );
  29362. sqdist.y.assign( sqdist.x );
  29363. sqdist.x.assign( dist );
  29364. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29365. sqdist.z.assign( sqdist.y );
  29366. sqdist.y.assign( dist );
  29367. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29368. sqdist.z.assign( dist );
  29369. } );
  29370. } );
  29371. } );
  29372. } );
  29373. If( metric.equal( int( 0 ) ), () => {
  29374. sqdist.assign( sqrt( sqdist ) );
  29375. } );
  29376. return sqdist;
  29377. } ).setLayout( {
  29378. name: 'mx_worley_noise_vec3_1',
  29379. type: 'vec3',
  29380. inputs: [
  29381. { name: 'p', type: 'vec3' },
  29382. { name: 'jitter', type: 'float' },
  29383. { name: 'metric', type: 'int' }
  29384. ]
  29385. } );
  29386. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  29387. // Three.js Transpiler
  29388. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  29389. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  29390. const s = hsv.y;
  29391. const v = hsv.z;
  29392. const result = vec3().toVar();
  29393. If( s.lessThan( 0.0001 ), () => {
  29394. result.assign( vec3( v, v, v ) );
  29395. } ).Else( () => {
  29396. let h = hsv.x;
  29397. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  29398. const hi = int( trunc( h ) );
  29399. const f = h.sub( float( hi ) );
  29400. const p = v.mul( s.oneMinus() );
  29401. const q = v.mul( s.mul( f ).oneMinus() );
  29402. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  29403. If( hi.equal( int( 0 ) ), () => {
  29404. result.assign( vec3( v, t, p ) );
  29405. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  29406. result.assign( vec3( q, v, p ) );
  29407. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  29408. result.assign( vec3( p, v, t ) );
  29409. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  29410. result.assign( vec3( p, q, v ) );
  29411. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  29412. result.assign( vec3( t, p, v ) );
  29413. } ).Else( () => {
  29414. result.assign( vec3( v, p, q ) );
  29415. } );
  29416. } );
  29417. return result;
  29418. } ).setLayout( {
  29419. name: 'mx_hsvtorgb',
  29420. type: 'vec3',
  29421. inputs: [
  29422. { name: 'hsv', type: 'vec3' }
  29423. ]
  29424. } );
  29425. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  29426. const c = vec3( c_immutable ).toVar();
  29427. const r = float( c.x ).toVar();
  29428. const g = float( c.y ).toVar();
  29429. const b = float( c.z ).toVar();
  29430. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  29431. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  29432. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  29433. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  29434. v.assign( maxcomp );
  29435. If( maxcomp.greaterThan( 0.0 ), () => {
  29436. s.assign( delta.div( maxcomp ) );
  29437. } ).Else( () => {
  29438. s.assign( 0.0 );
  29439. } );
  29440. If( s.lessThanEqual( 0.0 ), () => {
  29441. h.assign( 0.0 );
  29442. } ).Else( () => {
  29443. If( r.greaterThanEqual( maxcomp ), () => {
  29444. h.assign( g.sub( b ).div( delta ) );
  29445. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  29446. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  29447. } ).Else( () => {
  29448. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  29449. } );
  29450. h.mulAssign( 1.0 / 6.0 );
  29451. If( h.lessThan( 0.0 ), () => {
  29452. h.addAssign( 1.0 );
  29453. } );
  29454. } );
  29455. return vec3( h, s, v );
  29456. } ).setLayout( {
  29457. name: 'mx_rgbtohsv',
  29458. type: 'vec3',
  29459. inputs: [
  29460. { name: 'c', type: 'vec3' }
  29461. ]
  29462. } );
  29463. // Three.js Transpiler
  29464. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  29465. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  29466. const color = vec3( color_immutable ).toVar();
  29467. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  29468. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  29469. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  29470. return mix( linSeg, powSeg, isAbove );
  29471. } ).setLayout( {
  29472. name: 'mx_srgb_texture_to_lin_rec709',
  29473. type: 'vec3',
  29474. inputs: [
  29475. { name: 'color', type: 'vec3' }
  29476. ]
  29477. } );
  29478. const mx_aastep = ( threshold, value ) => {
  29479. threshold = float( threshold );
  29480. value = float( value );
  29481. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  29482. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  29483. };
  29484. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  29485. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  29486. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  29487. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  29488. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  29489. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  29490. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  29491. const mx_safepower = ( in1, in2 = 1 ) => {
  29492. in1 = float( in1 );
  29493. return in1.abs().pow( in2 ).mul( in1.sign() );
  29494. };
  29495. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  29496. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29497. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29498. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29499. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  29500. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  29501. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  29502. return noise_vec4.mul( amplitude ).add( pivot );
  29503. };
  29504. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29505. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29506. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29507. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  29508. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29509. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29510. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29511. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29512. /**
  29513. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  29514. *
  29515. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  29516. *
  29517. * ```js
  29518. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  29519. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  29520. * ```
  29521. *
  29522. * @tsl
  29523. * @function
  29524. * @param {Node<vec3>} normal - The normal to correct.
  29525. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  29526. * @param {Node<vec3>} cubePos - The cube position.
  29527. * @return {Node<vec3>} The parallax corrected normal.
  29528. */
  29529. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  29530. const nDir = normalize( normal ).toVar();
  29531. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29532. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29533. const rbminmax = vec3().toVar();
  29534. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  29535. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  29536. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  29537. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar();
  29538. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  29539. return boxIntersection.sub( cubePos );
  29540. } );
  29541. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  29542. // normal is assumed to have unit length
  29543. const x = normal.x, y = normal.y, z = normal.z;
  29544. // band 0
  29545. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  29546. // band 1
  29547. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  29548. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  29549. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  29550. // band 2
  29551. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  29552. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  29553. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  29554. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  29555. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  29556. return result;
  29557. } );
  29558. // constants
  29559. var TSL = /*#__PURE__*/Object.freeze({
  29560. __proto__: null,
  29561. BRDF_GGX: BRDF_GGX,
  29562. BRDF_Lambert: BRDF_Lambert,
  29563. BasicPointShadowFilter: BasicPointShadowFilter,
  29564. BasicShadowFilter: BasicShadowFilter,
  29565. Break: Break,
  29566. Const: Const,
  29567. Continue: Continue,
  29568. DFGApprox: DFGApprox,
  29569. D_GGX: D_GGX,
  29570. Discard: Discard,
  29571. EPSILON: EPSILON,
  29572. F_Schlick: F_Schlick,
  29573. Fn: Fn,
  29574. INFINITY: INFINITY,
  29575. If: If,
  29576. Loop: Loop,
  29577. NodeAccess: NodeAccess,
  29578. NodeShaderStage: NodeShaderStage,
  29579. NodeType: NodeType,
  29580. NodeUpdateType: NodeUpdateType,
  29581. PCFShadowFilter: PCFShadowFilter,
  29582. PCFSoftShadowFilter: PCFSoftShadowFilter,
  29583. PI: PI,
  29584. PI2: PI2,
  29585. PointShadowFilter: PointShadowFilter,
  29586. Return: Return,
  29587. Schlick_to_F0: Schlick_to_F0,
  29588. ScriptableNodeResources: ScriptableNodeResources,
  29589. ShaderNode: ShaderNode,
  29590. Stack: Stack,
  29591. Switch: Switch,
  29592. TBNViewMatrix: TBNViewMatrix,
  29593. VSMShadowFilter: VSMShadowFilter,
  29594. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  29595. Var: Var,
  29596. abs: abs,
  29597. acesFilmicToneMapping: acesFilmicToneMapping,
  29598. acos: acos,
  29599. add: add,
  29600. addMethodChaining: addMethodChaining,
  29601. addNodeElement: addNodeElement,
  29602. agxToneMapping: agxToneMapping,
  29603. all: all,
  29604. alphaT: alphaT,
  29605. and: and,
  29606. anisotropy: anisotropy,
  29607. anisotropyB: anisotropyB,
  29608. anisotropyT: anisotropyT,
  29609. any: any,
  29610. append: append,
  29611. array: array,
  29612. arrayBuffer: arrayBuffer,
  29613. asin: asin,
  29614. assign: assign,
  29615. atan: atan,
  29616. atan2: atan2,
  29617. atomicAdd: atomicAdd,
  29618. atomicAnd: atomicAnd,
  29619. atomicFunc: atomicFunc,
  29620. atomicLoad: atomicLoad,
  29621. atomicMax: atomicMax,
  29622. atomicMin: atomicMin,
  29623. atomicOr: atomicOr,
  29624. atomicStore: atomicStore,
  29625. atomicSub: atomicSub,
  29626. atomicXor: atomicXor,
  29627. attenuationColor: attenuationColor,
  29628. attenuationDistance: attenuationDistance,
  29629. attribute: attribute,
  29630. attributeArray: attributeArray,
  29631. backgroundBlurriness: backgroundBlurriness,
  29632. backgroundIntensity: backgroundIntensity,
  29633. backgroundRotation: backgroundRotation,
  29634. batch: batch,
  29635. billboarding: billboarding,
  29636. bitAnd: bitAnd,
  29637. bitNot: bitNot,
  29638. bitOr: bitOr,
  29639. bitXor: bitXor,
  29640. bitangentGeometry: bitangentGeometry,
  29641. bitangentLocal: bitangentLocal,
  29642. bitangentView: bitangentView,
  29643. bitangentWorld: bitangentWorld,
  29644. bitcast: bitcast,
  29645. blendBurn: blendBurn,
  29646. blendColor: blendColor,
  29647. blendDodge: blendDodge,
  29648. blendOverlay: blendOverlay,
  29649. blendScreen: blendScreen,
  29650. blur: blur,
  29651. bool: bool,
  29652. buffer: buffer,
  29653. bufferAttribute: bufferAttribute,
  29654. bumpMap: bumpMap,
  29655. burn: burn,
  29656. bvec2: bvec2,
  29657. bvec3: bvec3,
  29658. bvec4: bvec4,
  29659. bypass: bypass,
  29660. cache: cache,
  29661. call: call,
  29662. cameraFar: cameraFar,
  29663. cameraIndex: cameraIndex,
  29664. cameraNear: cameraNear,
  29665. cameraNormalMatrix: cameraNormalMatrix,
  29666. cameraPosition: cameraPosition,
  29667. cameraProjectionMatrix: cameraProjectionMatrix,
  29668. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  29669. cameraViewMatrix: cameraViewMatrix,
  29670. cameraWorldMatrix: cameraWorldMatrix,
  29671. cbrt: cbrt,
  29672. cdl: cdl,
  29673. ceil: ceil,
  29674. checker: checker,
  29675. cineonToneMapping: cineonToneMapping,
  29676. clamp: clamp,
  29677. clearcoat: clearcoat,
  29678. clearcoatRoughness: clearcoatRoughness,
  29679. code: code,
  29680. color: color,
  29681. colorSpaceToWorking: colorSpaceToWorking,
  29682. colorToDirection: colorToDirection,
  29683. compute: compute,
  29684. computeSkinning: computeSkinning,
  29685. cond: cond,
  29686. context: context,
  29687. convert: convert,
  29688. convertColorSpace: convertColorSpace,
  29689. convertToTexture: convertToTexture,
  29690. cos: cos,
  29691. cross: cross,
  29692. cubeTexture: cubeTexture,
  29693. cubeToUV: cubeToUV,
  29694. dFdx: dFdx,
  29695. dFdy: dFdy,
  29696. dashSize: dashSize,
  29697. debug: debug,
  29698. decrement: decrement,
  29699. decrementBefore: decrementBefore,
  29700. defaultBuildStages: defaultBuildStages,
  29701. defaultShaderStages: defaultShaderStages,
  29702. defined: defined,
  29703. degrees: degrees,
  29704. deltaTime: deltaTime,
  29705. densityFog: densityFog,
  29706. densityFogFactor: densityFogFactor,
  29707. depth: depth,
  29708. depthPass: depthPass,
  29709. difference: difference,
  29710. diffuseColor: diffuseColor,
  29711. directPointLight: directPointLight,
  29712. directionToColor: directionToColor,
  29713. dispersion: dispersion,
  29714. distance: distance,
  29715. div: div,
  29716. dodge: dodge,
  29717. dot: dot,
  29718. drawIndex: drawIndex,
  29719. dynamicBufferAttribute: dynamicBufferAttribute,
  29720. element: element,
  29721. emissive: emissive,
  29722. equal: equal,
  29723. equals: equals,
  29724. equirectUV: equirectUV,
  29725. exp: exp,
  29726. exp2: exp2,
  29727. expression: expression,
  29728. faceDirection: faceDirection,
  29729. faceForward: faceForward,
  29730. faceforward: faceforward,
  29731. float: float,
  29732. floor: floor,
  29733. fog: fog,
  29734. fract: fract,
  29735. frameGroup: frameGroup,
  29736. frameId: frameId,
  29737. frontFacing: frontFacing,
  29738. fwidth: fwidth,
  29739. gain: gain,
  29740. gapSize: gapSize,
  29741. getConstNodeType: getConstNodeType,
  29742. getCurrentStack: getCurrentStack,
  29743. getDirection: getDirection,
  29744. getDistanceAttenuation: getDistanceAttenuation,
  29745. getGeometryRoughness: getGeometryRoughness,
  29746. getNormalFromDepth: getNormalFromDepth,
  29747. getParallaxCorrectNormal: getParallaxCorrectNormal,
  29748. getRoughness: getRoughness,
  29749. getScreenPosition: getScreenPosition,
  29750. getShIrradianceAt: getShIrradianceAt,
  29751. getShadowMaterial: getShadowMaterial,
  29752. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  29753. getTextureIndex: getTextureIndex,
  29754. getViewPosition: getViewPosition,
  29755. globalId: globalId,
  29756. glsl: glsl,
  29757. glslFn: glslFn,
  29758. grayscale: grayscale,
  29759. greaterThan: greaterThan,
  29760. greaterThanEqual: greaterThanEqual,
  29761. hash: hash,
  29762. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  29763. highpModelViewMatrix: highpModelViewMatrix,
  29764. hue: hue,
  29765. increment: increment,
  29766. incrementBefore: incrementBefore,
  29767. instance: instance,
  29768. instanceIndex: instanceIndex,
  29769. instancedArray: instancedArray,
  29770. instancedBufferAttribute: instancedBufferAttribute,
  29771. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  29772. instancedMesh: instancedMesh,
  29773. int: int,
  29774. inverseSqrt: inverseSqrt,
  29775. inversesqrt: inversesqrt,
  29776. invocationLocalIndex: invocationLocalIndex,
  29777. invocationSubgroupIndex: invocationSubgroupIndex,
  29778. ior: ior,
  29779. iridescence: iridescence,
  29780. iridescenceIOR: iridescenceIOR,
  29781. iridescenceThickness: iridescenceThickness,
  29782. ivec2: ivec2,
  29783. ivec3: ivec3,
  29784. ivec4: ivec4,
  29785. js: js,
  29786. label: label,
  29787. length: length,
  29788. lengthSq: lengthSq,
  29789. lessThan: lessThan,
  29790. lessThanEqual: lessThanEqual,
  29791. lightPosition: lightPosition,
  29792. lightProjectionUV: lightProjectionUV,
  29793. lightShadowMatrix: lightShadowMatrix,
  29794. lightTargetDirection: lightTargetDirection,
  29795. lightTargetPosition: lightTargetPosition,
  29796. lightViewPosition: lightViewPosition,
  29797. lightingContext: lightingContext,
  29798. lights: lights,
  29799. linearDepth: linearDepth,
  29800. linearToneMapping: linearToneMapping,
  29801. localId: localId,
  29802. log: log,
  29803. log2: log2,
  29804. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  29805. loop: loop,
  29806. luminance: luminance,
  29807. mat2: mat2,
  29808. mat3: mat3,
  29809. mat4: mat4,
  29810. matcapUV: matcapUV,
  29811. materialAO: materialAO,
  29812. materialAlphaTest: materialAlphaTest,
  29813. materialAnisotropy: materialAnisotropy,
  29814. materialAnisotropyVector: materialAnisotropyVector,
  29815. materialAttenuationColor: materialAttenuationColor,
  29816. materialAttenuationDistance: materialAttenuationDistance,
  29817. materialClearcoat: materialClearcoat,
  29818. materialClearcoatNormal: materialClearcoatNormal,
  29819. materialClearcoatRoughness: materialClearcoatRoughness,
  29820. materialColor: materialColor,
  29821. materialDispersion: materialDispersion,
  29822. materialEmissive: materialEmissive,
  29823. materialEnvIntensity: materialEnvIntensity,
  29824. materialEnvRotation: materialEnvRotation,
  29825. materialIOR: materialIOR,
  29826. materialIridescence: materialIridescence,
  29827. materialIridescenceIOR: materialIridescenceIOR,
  29828. materialIridescenceThickness: materialIridescenceThickness,
  29829. materialLightMap: materialLightMap,
  29830. materialLineDashOffset: materialLineDashOffset,
  29831. materialLineDashSize: materialLineDashSize,
  29832. materialLineGapSize: materialLineGapSize,
  29833. materialLineScale: materialLineScale,
  29834. materialLineWidth: materialLineWidth,
  29835. materialMetalness: materialMetalness,
  29836. materialNormal: materialNormal,
  29837. materialOpacity: materialOpacity,
  29838. materialPointSize: materialPointSize,
  29839. materialReference: materialReference,
  29840. materialReflectivity: materialReflectivity,
  29841. materialRefractionRatio: materialRefractionRatio,
  29842. materialRotation: materialRotation,
  29843. materialRoughness: materialRoughness,
  29844. materialSheen: materialSheen,
  29845. materialSheenRoughness: materialSheenRoughness,
  29846. materialShininess: materialShininess,
  29847. materialSpecular: materialSpecular,
  29848. materialSpecularColor: materialSpecularColor,
  29849. materialSpecularIntensity: materialSpecularIntensity,
  29850. materialSpecularStrength: materialSpecularStrength,
  29851. materialThickness: materialThickness,
  29852. materialTransmission: materialTransmission,
  29853. max: max$1,
  29854. maxMipLevel: maxMipLevel,
  29855. mediumpModelViewMatrix: mediumpModelViewMatrix,
  29856. metalness: metalness,
  29857. min: min$1,
  29858. mix: mix,
  29859. mixElement: mixElement,
  29860. mod: mod,
  29861. modInt: modInt,
  29862. modelDirection: modelDirection,
  29863. modelNormalMatrix: modelNormalMatrix,
  29864. modelPosition: modelPosition,
  29865. modelRadius: modelRadius,
  29866. modelScale: modelScale,
  29867. modelViewMatrix: modelViewMatrix,
  29868. modelViewPosition: modelViewPosition,
  29869. modelViewProjection: modelViewProjection,
  29870. modelWorldMatrix: modelWorldMatrix,
  29871. modelWorldMatrixInverse: modelWorldMatrixInverse,
  29872. morphReference: morphReference,
  29873. mrt: mrt,
  29874. mul: mul,
  29875. mx_aastep: mx_aastep,
  29876. mx_cell_noise_float: mx_cell_noise_float,
  29877. mx_contrast: mx_contrast,
  29878. mx_fractal_noise_float: mx_fractal_noise_float,
  29879. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  29880. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  29881. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  29882. mx_hsvtorgb: mx_hsvtorgb,
  29883. mx_noise_float: mx_noise_float,
  29884. mx_noise_vec3: mx_noise_vec3,
  29885. mx_noise_vec4: mx_noise_vec4,
  29886. mx_ramplr: mx_ramplr,
  29887. mx_ramptb: mx_ramptb,
  29888. mx_rgbtohsv: mx_rgbtohsv,
  29889. mx_safepower: mx_safepower,
  29890. mx_splitlr: mx_splitlr,
  29891. mx_splittb: mx_splittb,
  29892. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  29893. mx_transform_uv: mx_transform_uv,
  29894. mx_worley_noise_float: mx_worley_noise_float,
  29895. mx_worley_noise_vec2: mx_worley_noise_vec2,
  29896. mx_worley_noise_vec3: mx_worley_noise_vec3,
  29897. negate: negate,
  29898. neutralToneMapping: neutralToneMapping,
  29899. nodeArray: nodeArray,
  29900. nodeImmutable: nodeImmutable,
  29901. nodeObject: nodeObject,
  29902. nodeObjects: nodeObjects,
  29903. nodeProxy: nodeProxy,
  29904. normalFlat: normalFlat,
  29905. normalGeometry: normalGeometry,
  29906. normalLocal: normalLocal,
  29907. normalMap: normalMap,
  29908. normalView: normalView,
  29909. normalWorld: normalWorld,
  29910. normalize: normalize,
  29911. not: not,
  29912. notEqual: notEqual,
  29913. numWorkgroups: numWorkgroups,
  29914. objectDirection: objectDirection,
  29915. objectGroup: objectGroup,
  29916. objectPosition: objectPosition,
  29917. objectRadius: objectRadius,
  29918. objectScale: objectScale,
  29919. objectViewPosition: objectViewPosition,
  29920. objectWorldMatrix: objectWorldMatrix,
  29921. oneMinus: oneMinus,
  29922. or: or,
  29923. orthographicDepthToViewZ: orthographicDepthToViewZ,
  29924. oscSawtooth: oscSawtooth,
  29925. oscSine: oscSine,
  29926. oscSquare: oscSquare,
  29927. oscTriangle: oscTriangle,
  29928. output: output,
  29929. outputStruct: outputStruct,
  29930. overlay: overlay,
  29931. overloadingFn: overloadingFn,
  29932. parabola: parabola,
  29933. parallaxDirection: parallaxDirection,
  29934. parallaxUV: parallaxUV,
  29935. parameter: parameter,
  29936. pass: pass,
  29937. passTexture: passTexture,
  29938. pcurve: pcurve,
  29939. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  29940. pmremTexture: pmremTexture,
  29941. pointShadow: pointShadow,
  29942. pointUV: pointUV,
  29943. pointWidth: pointWidth,
  29944. positionGeometry: positionGeometry,
  29945. positionLocal: positionLocal,
  29946. positionPrevious: positionPrevious,
  29947. positionView: positionView,
  29948. positionViewDirection: positionViewDirection,
  29949. positionWorld: positionWorld,
  29950. positionWorldDirection: positionWorldDirection,
  29951. posterize: posterize,
  29952. pow: pow,
  29953. pow2: pow2,
  29954. pow3: pow3,
  29955. pow4: pow4,
  29956. property: property,
  29957. radians: radians,
  29958. rand: rand,
  29959. range: range,
  29960. rangeFog: rangeFog,
  29961. rangeFogFactor: rangeFogFactor,
  29962. reciprocal: reciprocal,
  29963. reference: reference,
  29964. referenceBuffer: referenceBuffer,
  29965. reflect: reflect,
  29966. reflectVector: reflectVector,
  29967. reflectView: reflectView,
  29968. reflector: reflector,
  29969. refract: refract,
  29970. refractVector: refractVector,
  29971. refractView: refractView,
  29972. reinhardToneMapping: reinhardToneMapping,
  29973. remainder: remainder,
  29974. remap: remap,
  29975. remapClamp: remapClamp,
  29976. renderGroup: renderGroup,
  29977. renderOutput: renderOutput,
  29978. rendererReference: rendererReference,
  29979. rotate: rotate,
  29980. rotateUV: rotateUV,
  29981. roughness: roughness,
  29982. round: round,
  29983. rtt: rtt,
  29984. sRGBTransferEOTF: sRGBTransferEOTF,
  29985. sRGBTransferOETF: sRGBTransferOETF,
  29986. sampler: sampler,
  29987. samplerComparison: samplerComparison,
  29988. saturate: saturate,
  29989. saturation: saturation,
  29990. screen: screen,
  29991. screenCoordinate: screenCoordinate,
  29992. screenSize: screenSize,
  29993. screenUV: screenUV,
  29994. scriptable: scriptable,
  29995. scriptableValue: scriptableValue,
  29996. select: select,
  29997. setCurrentStack: setCurrentStack,
  29998. shaderStages: shaderStages,
  29999. shadow: shadow,
  30000. shadowPositionWorld: shadowPositionWorld,
  30001. shapeCircle: shapeCircle,
  30002. sharedUniformGroup: sharedUniformGroup,
  30003. sheen: sheen,
  30004. sheenRoughness: sheenRoughness,
  30005. shiftLeft: shiftLeft,
  30006. shiftRight: shiftRight,
  30007. shininess: shininess,
  30008. sign: sign,
  30009. sin: sin,
  30010. sinc: sinc,
  30011. skinning: skinning,
  30012. smoothstep: smoothstep,
  30013. smoothstepElement: smoothstepElement,
  30014. specularColor: specularColor,
  30015. specularF90: specularF90,
  30016. spherizeUV: spherizeUV,
  30017. split: split,
  30018. spritesheetUV: spritesheetUV,
  30019. sqrt: sqrt,
  30020. stack: stack,
  30021. step: step,
  30022. storage: storage,
  30023. storageBarrier: storageBarrier,
  30024. storageObject: storageObject,
  30025. storageTexture: storageTexture,
  30026. string: string,
  30027. struct: struct,
  30028. sub: sub,
  30029. subgroupIndex: subgroupIndex,
  30030. subgroupSize: subgroupSize,
  30031. tan: tan,
  30032. tangentGeometry: tangentGeometry,
  30033. tangentLocal: tangentLocal,
  30034. tangentView: tangentView,
  30035. tangentWorld: tangentWorld,
  30036. temp: temp,
  30037. texture: texture,
  30038. texture3D: texture3D,
  30039. textureBarrier: textureBarrier,
  30040. textureBicubic: textureBicubic,
  30041. textureCubeUV: textureCubeUV,
  30042. textureLoad: textureLoad,
  30043. textureSize: textureSize,
  30044. textureStore: textureStore,
  30045. thickness: thickness,
  30046. time: time,
  30047. timerDelta: timerDelta,
  30048. timerGlobal: timerGlobal,
  30049. timerLocal: timerLocal,
  30050. toOutputColorSpace: toOutputColorSpace,
  30051. toWorkingColorSpace: toWorkingColorSpace,
  30052. toneMapping: toneMapping,
  30053. toneMappingExposure: toneMappingExposure,
  30054. toonOutlinePass: toonOutlinePass,
  30055. transformDirection: transformDirection,
  30056. transformNormal: transformNormal,
  30057. transformNormalToView: transformNormalToView,
  30058. transformedBentNormalView: transformedBentNormalView,
  30059. transformedBitangentView: transformedBitangentView,
  30060. transformedBitangentWorld: transformedBitangentWorld,
  30061. transformedClearcoatNormalView: transformedClearcoatNormalView,
  30062. transformedNormalView: transformedNormalView,
  30063. transformedNormalWorld: transformedNormalWorld,
  30064. transformedTangentView: transformedTangentView,
  30065. transformedTangentWorld: transformedTangentWorld,
  30066. transmission: transmission,
  30067. transpose: transpose,
  30068. triNoise3D: triNoise3D,
  30069. triplanarTexture: triplanarTexture,
  30070. triplanarTextures: triplanarTextures,
  30071. trunc: trunc,
  30072. tslFn: tslFn,
  30073. uint: uint,
  30074. uniform: uniform,
  30075. uniformArray: uniformArray,
  30076. uniformGroup: uniformGroup,
  30077. uniforms: uniforms,
  30078. userData: userData,
  30079. uv: uv,
  30080. uvec2: uvec2,
  30081. uvec3: uvec3,
  30082. uvec4: uvec4,
  30083. varying: varying,
  30084. varyingProperty: varyingProperty,
  30085. vec2: vec2,
  30086. vec3: vec3,
  30087. vec4: vec4,
  30088. vectorComponents: vectorComponents,
  30089. velocity: velocity,
  30090. vertexColor: vertexColor,
  30091. vertexIndex: vertexIndex,
  30092. vertexStage: vertexStage,
  30093. vibrance: vibrance,
  30094. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  30095. viewZToOrthographicDepth: viewZToOrthographicDepth,
  30096. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  30097. viewport: viewport,
  30098. viewportBottomLeft: viewportBottomLeft,
  30099. viewportCoordinate: viewportCoordinate,
  30100. viewportDepthTexture: viewportDepthTexture,
  30101. viewportLinearDepth: viewportLinearDepth,
  30102. viewportMipTexture: viewportMipTexture,
  30103. viewportResolution: viewportResolution,
  30104. viewportSafeUV: viewportSafeUV,
  30105. viewportSharedTexture: viewportSharedTexture,
  30106. viewportSize: viewportSize,
  30107. viewportTexture: viewportTexture,
  30108. viewportTopLeft: viewportTopLeft,
  30109. viewportUV: viewportUV,
  30110. wgsl: wgsl,
  30111. wgslFn: wgslFn,
  30112. workgroupArray: workgroupArray,
  30113. workgroupBarrier: workgroupBarrier,
  30114. workgroupId: workgroupId,
  30115. workingToColorSpace: workingToColorSpace,
  30116. xor: xor
  30117. });
  30118. const _clearColor = /*@__PURE__*/ new Color4();
  30119. /**
  30120. * This renderer module manages the background.
  30121. *
  30122. * @private
  30123. * @augments DataMap
  30124. */
  30125. class Background extends DataMap {
  30126. /**
  30127. * Constructs a new background management component.
  30128. *
  30129. * @param {Renderer} renderer - The renderer.
  30130. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  30131. */
  30132. constructor( renderer, nodes ) {
  30133. super();
  30134. /**
  30135. * The renderer.
  30136. *
  30137. * @type {Renderer}
  30138. */
  30139. this.renderer = renderer;
  30140. /**
  30141. * Renderer component for managing nodes related logic.
  30142. *
  30143. * @type {Nodes}
  30144. */
  30145. this.nodes = nodes;
  30146. }
  30147. /**
  30148. * Updates the background for the given scene. Depending on how `Scene.background`
  30149. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  30150. * or add a mesh to the render list for rendering the background as a textured plane
  30151. * or skybox.
  30152. *
  30153. * @param {Scene} scene - The scene.
  30154. * @param {RenderList} renderList - The current render list.
  30155. * @param {RenderContext} renderContext - The current render context.
  30156. */
  30157. update( scene, renderList, renderContext ) {
  30158. const renderer = this.renderer;
  30159. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  30160. let forceClear = false;
  30161. if ( background === null ) {
  30162. // no background settings, use clear color configuration from the renderer
  30163. renderer._clearColor.getRGB( _clearColor );
  30164. _clearColor.a = renderer._clearColor.a;
  30165. } else if ( background.isColor === true ) {
  30166. // background is an opaque color
  30167. background.getRGB( _clearColor );
  30168. _clearColor.a = 1;
  30169. forceClear = true;
  30170. } else if ( background.isNode === true ) {
  30171. const sceneData = this.get( scene );
  30172. const backgroundNode = background;
  30173. _clearColor.copy( renderer._clearColor );
  30174. let backgroundMesh = sceneData.backgroundMesh;
  30175. if ( backgroundMesh === undefined ) {
  30176. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  30177. // @TODO: Add Texture2D support using node context
  30178. getUV: () => backgroundRotation.mul( normalWorld ),
  30179. getTextureLevel: () => backgroundBlurriness
  30180. } );
  30181. let viewProj = modelViewProjection;
  30182. viewProj = viewProj.setZ( viewProj.w );
  30183. const nodeMaterial = new NodeMaterial();
  30184. nodeMaterial.name = 'Background.material';
  30185. nodeMaterial.side = BackSide;
  30186. nodeMaterial.depthTest = false;
  30187. nodeMaterial.depthWrite = false;
  30188. nodeMaterial.allowOverride = false;
  30189. nodeMaterial.fog = false;
  30190. nodeMaterial.lights = false;
  30191. nodeMaterial.vertexNode = viewProj;
  30192. nodeMaterial.colorNode = backgroundMeshNode;
  30193. sceneData.backgroundMeshNode = backgroundMeshNode;
  30194. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  30195. backgroundMesh.frustumCulled = false;
  30196. backgroundMesh.name = 'Background.mesh';
  30197. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  30198. this.matrixWorld.copyPosition( camera.matrixWorld );
  30199. };
  30200. function onBackgroundDispose() {
  30201. background.removeEventListener( 'dispose', onBackgroundDispose );
  30202. backgroundMesh.material.dispose();
  30203. backgroundMesh.geometry.dispose();
  30204. }
  30205. background.addEventListener( 'dispose', onBackgroundDispose );
  30206. }
  30207. const backgroundCacheKey = backgroundNode.getCacheKey();
  30208. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  30209. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  30210. sceneData.backgroundMeshNode.needsUpdate = true;
  30211. backgroundMesh.material.needsUpdate = true;
  30212. sceneData.backgroundCacheKey = backgroundCacheKey;
  30213. }
  30214. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  30215. } else {
  30216. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  30217. }
  30218. //
  30219. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  30220. if ( environmentBlendMode === 'additive' ) {
  30221. _clearColor.set( 0, 0, 0, 1 );
  30222. } else if ( environmentBlendMode === 'alpha-blend' ) {
  30223. _clearColor.set( 0, 0, 0, 0 );
  30224. }
  30225. //
  30226. if ( renderer.autoClear === true || forceClear === true ) {
  30227. const clearColorValue = renderContext.clearColorValue;
  30228. clearColorValue.r = _clearColor.r;
  30229. clearColorValue.g = _clearColor.g;
  30230. clearColorValue.b = _clearColor.b;
  30231. clearColorValue.a = _clearColor.a;
  30232. // premultiply alpha
  30233. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  30234. clearColorValue.r *= clearColorValue.a;
  30235. clearColorValue.g *= clearColorValue.a;
  30236. clearColorValue.b *= clearColorValue.a;
  30237. }
  30238. //
  30239. renderContext.depthClearValue = renderer._clearDepth;
  30240. renderContext.stencilClearValue = renderer._clearStencil;
  30241. renderContext.clearColor = renderer.autoClearColor === true;
  30242. renderContext.clearDepth = renderer.autoClearDepth === true;
  30243. renderContext.clearStencil = renderer.autoClearStencil === true;
  30244. } else {
  30245. renderContext.clearColor = false;
  30246. renderContext.clearDepth = false;
  30247. renderContext.clearStencil = false;
  30248. }
  30249. }
  30250. }
  30251. let _id$6 = 0;
  30252. /**
  30253. * A bind group represents a collection of bindings and thus a collection
  30254. * or resources. Bind groups are assigned to pipelines to provide them
  30255. * with the required resources (like uniform buffers or textures).
  30256. *
  30257. * @private
  30258. */
  30259. class BindGroup {
  30260. /**
  30261. * Constructs a new bind group.
  30262. *
  30263. * @param {string} name - The bind group's name.
  30264. * @param {Array<Binding>} bindings - An array of bindings.
  30265. * @param {number} index - The group index.
  30266. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  30267. */
  30268. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  30269. /**
  30270. * The bind group's name.
  30271. *
  30272. * @type {string}
  30273. */
  30274. this.name = name;
  30275. /**
  30276. * An array of bindings.
  30277. *
  30278. * @type {Array<Binding>}
  30279. */
  30280. this.bindings = bindings;
  30281. /**
  30282. * The group index.
  30283. *
  30284. * @type {number}
  30285. */
  30286. this.index = index;
  30287. /**
  30288. * An array of reference bindings.
  30289. *
  30290. * @type {Array<Binding>}
  30291. */
  30292. this.bindingsReference = bindingsReference;
  30293. /**
  30294. * The group's ID.
  30295. *
  30296. * @type {number}
  30297. */
  30298. this.id = _id$6 ++;
  30299. }
  30300. }
  30301. /**
  30302. * This module represents the state of a node builder after it was
  30303. * used to build the nodes for a render object. The state holds the
  30304. * results of the build for further processing in the renderer.
  30305. *
  30306. * Render objects with identical cache keys share the same node builder state.
  30307. *
  30308. * @private
  30309. */
  30310. class NodeBuilderState {
  30311. /**
  30312. * Constructs a new node builder state.
  30313. *
  30314. * @param {string} vertexShader - The native vertex shader code.
  30315. * @param {string} fragmentShader - The native fragment shader code.
  30316. * @param {string} computeShader - The native compute shader code.
  30317. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  30318. * @param {Array<BindGroup>} bindings - An array of bind groups.
  30319. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  30320. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  30321. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  30322. * @param {NodeMaterialObserver} observer - A node material observer.
  30323. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  30324. */
  30325. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  30326. /**
  30327. * The native vertex shader code.
  30328. *
  30329. * @type {string}
  30330. */
  30331. this.vertexShader = vertexShader;
  30332. /**
  30333. * The native fragment shader code.
  30334. *
  30335. * @type {string}
  30336. */
  30337. this.fragmentShader = fragmentShader;
  30338. /**
  30339. * The native compute shader code.
  30340. *
  30341. * @type {string}
  30342. */
  30343. this.computeShader = computeShader;
  30344. /**
  30345. * An array with transform attribute objects.
  30346. * Only relevant when using compute shaders with WebGL 2.
  30347. *
  30348. * @type {Array<Object>}
  30349. */
  30350. this.transforms = transforms;
  30351. /**
  30352. * An array of node attributes representing
  30353. * the attributes of the shaders.
  30354. *
  30355. * @type {Array<NodeAttribute>}
  30356. */
  30357. this.nodeAttributes = nodeAttributes;
  30358. /**
  30359. * An array of bind groups representing the uniform or storage
  30360. * buffers, texture or samplers of the shader.
  30361. *
  30362. * @type {Array<BindGroup>}
  30363. */
  30364. this.bindings = bindings;
  30365. /**
  30366. * An array of nodes that implement their `update()` method.
  30367. *
  30368. * @type {Array<Node>}
  30369. */
  30370. this.updateNodes = updateNodes;
  30371. /**
  30372. * An array of nodes that implement their `updateBefore()` method.
  30373. *
  30374. * @type {Array<Node>}
  30375. */
  30376. this.updateBeforeNodes = updateBeforeNodes;
  30377. /**
  30378. * An array of nodes that implement their `updateAfter()` method.
  30379. *
  30380. * @type {Array<Node>}
  30381. */
  30382. this.updateAfterNodes = updateAfterNodes;
  30383. /**
  30384. * A node material observer.
  30385. *
  30386. * @type {NodeMaterialObserver}
  30387. */
  30388. this.observer = observer;
  30389. /**
  30390. * How often this state is used by render objects.
  30391. *
  30392. * @type {number}
  30393. */
  30394. this.usedTimes = 0;
  30395. }
  30396. /**
  30397. * This method is used to create a array of bind groups based
  30398. * on the existing bind groups of this state. Shared groups are
  30399. * not cloned.
  30400. *
  30401. * @return {Array<BindGroup>} A array of bind groups.
  30402. */
  30403. createBindings() {
  30404. const bindings = [];
  30405. for ( const instanceGroup of this.bindings ) {
  30406. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  30407. if ( shared !== true ) {
  30408. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  30409. bindings.push( bindingsGroup );
  30410. for ( const instanceBinding of instanceGroup.bindings ) {
  30411. bindingsGroup.bindings.push( instanceBinding.clone() );
  30412. }
  30413. } else {
  30414. bindings.push( instanceGroup );
  30415. }
  30416. }
  30417. return bindings;
  30418. }
  30419. }
  30420. /**
  30421. * {@link NodeBuilder} is going to create instances of this class during the build process
  30422. * of nodes. They represent the final shader attributes that are going to be generated
  30423. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  30424. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  30425. */
  30426. class NodeAttribute {
  30427. /**
  30428. * Constructs a new node attribute.
  30429. *
  30430. * @param {string} name - The name of the attribute.
  30431. * @param {string} type - The type of the attribute.
  30432. * @param {?Node} node - An optional reference to the node.
  30433. */
  30434. constructor( name, type, node = null ) {
  30435. /**
  30436. * This flag can be used for type testing.
  30437. *
  30438. * @type {boolean}
  30439. * @readonly
  30440. * @default true
  30441. */
  30442. this.isNodeAttribute = true;
  30443. /**
  30444. * The name of the attribute.
  30445. *
  30446. * @type {string}
  30447. */
  30448. this.name = name;
  30449. /**
  30450. * The type of the attribute.
  30451. *
  30452. * @type {string}
  30453. */
  30454. this.type = type;
  30455. /**
  30456. * An optional reference to the node.
  30457. *
  30458. * @type {?Node}
  30459. * @default null
  30460. */
  30461. this.node = node;
  30462. }
  30463. }
  30464. /**
  30465. * {@link NodeBuilder} is going to create instances of this class during the build process
  30466. * of nodes. They represent the final shader uniforms that are going to be generated
  30467. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  30468. * for this purpose.
  30469. */
  30470. class NodeUniform {
  30471. /**
  30472. * Constructs a new node uniform.
  30473. *
  30474. * @param {string} name - The name of the uniform.
  30475. * @param {string} type - The type of the uniform.
  30476. * @param {UniformNode} node - An reference to the node.
  30477. */
  30478. constructor( name, type, node ) {
  30479. /**
  30480. * This flag can be used for type testing.
  30481. *
  30482. * @type {boolean}
  30483. * @readonly
  30484. * @default true
  30485. */
  30486. this.isNodeUniform = true;
  30487. /**
  30488. * The name of the uniform.
  30489. *
  30490. * @type {string}
  30491. */
  30492. this.name = name;
  30493. /**
  30494. * The type of the uniform.
  30495. *
  30496. * @type {string}
  30497. */
  30498. this.type = type;
  30499. /**
  30500. * An reference to the node.
  30501. *
  30502. * @type {UniformNode}
  30503. */
  30504. this.node = node.getSelf();
  30505. }
  30506. /**
  30507. * The value of the uniform node.
  30508. *
  30509. * @type {any}
  30510. */
  30511. get value() {
  30512. return this.node.value;
  30513. }
  30514. set value( val ) {
  30515. this.node.value = val;
  30516. }
  30517. /**
  30518. * The id of the uniform node.
  30519. *
  30520. * @type {number}
  30521. */
  30522. get id() {
  30523. return this.node.id;
  30524. }
  30525. /**
  30526. * The uniform node's group.
  30527. *
  30528. * @type {UniformGroupNode}
  30529. */
  30530. get groupNode() {
  30531. return this.node.groupNode;
  30532. }
  30533. }
  30534. /**
  30535. * {@link NodeBuilder} is going to create instances of this class during the build process
  30536. * of nodes. They represent the final shader variables that are going to be generated
  30537. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  30538. * this purpose.
  30539. */
  30540. class NodeVar {
  30541. /**
  30542. * Constructs a new node variable.
  30543. *
  30544. * @param {string} name - The name of the variable.
  30545. * @param {string} type - The type of the variable.
  30546. * @param {boolean} [readOnly=false] - The read-only flag.
  30547. * @param {?number} [count=null] - The size.
  30548. */
  30549. constructor( name, type, readOnly = false, count = null ) {
  30550. /**
  30551. * This flag can be used for type testing.
  30552. *
  30553. * @type {boolean}
  30554. * @readonly
  30555. * @default true
  30556. */
  30557. this.isNodeVar = true;
  30558. /**
  30559. * The name of the variable.
  30560. *
  30561. * @type {string}
  30562. */
  30563. this.name = name;
  30564. /**
  30565. * The type of the variable.
  30566. *
  30567. * @type {string}
  30568. */
  30569. this.type = type;
  30570. /**
  30571. * The read-only flag.
  30572. *
  30573. * @type {boolean}
  30574. */
  30575. this.readOnly = readOnly;
  30576. /**
  30577. * The size.
  30578. *
  30579. * @type {?number}
  30580. */
  30581. this.count = count;
  30582. }
  30583. }
  30584. /**
  30585. * {@link NodeBuilder} is going to create instances of this class during the build process
  30586. * of nodes. They represent the final shader varyings that are going to be generated
  30587. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  30588. * this purpose.
  30589. *
  30590. * @augments NodeVar
  30591. */
  30592. class NodeVarying extends NodeVar {
  30593. /**
  30594. * Constructs a new node varying.
  30595. *
  30596. * @param {string} name - The name of the varying.
  30597. * @param {string} type - The type of the varying.
  30598. * @param {?string} interpolationType - The interpolation type of the varying.
  30599. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  30600. */
  30601. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  30602. super( name, type );
  30603. /**
  30604. * Whether this varying requires interpolation or not. This property can be used
  30605. * to check if the varying can be optimized for a variable.
  30606. *
  30607. * @type {boolean}
  30608. * @default false
  30609. */
  30610. this.needsInterpolation = false;
  30611. /**
  30612. * This flag can be used for type testing.
  30613. *
  30614. * @type {boolean}
  30615. * @readonly
  30616. * @default true
  30617. */
  30618. this.isNodeVarying = true;
  30619. /**
  30620. * The interpolation type of the varying data.
  30621. *
  30622. * @type {?string}
  30623. * @default null
  30624. */
  30625. this.interpolationType = interpolationType;
  30626. /**
  30627. * The interpolation sampling type of varying data.
  30628. *
  30629. * @type {?string}
  30630. * @default null
  30631. */
  30632. this.interpolationSampling = interpolationSampling;
  30633. }
  30634. }
  30635. /**
  30636. * {@link NodeBuilder} is going to create instances of this class during the build process
  30637. * of nodes. They represent user-defined, native shader code portions that are going to be
  30638. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  30639. * for this purpose.
  30640. */
  30641. class NodeCode {
  30642. /**
  30643. * Constructs a new code node.
  30644. *
  30645. * @param {string} name - The name of the code.
  30646. * @param {string} type - The node type.
  30647. * @param {string} [code=''] - The native shader code.
  30648. */
  30649. constructor( name, type, code = '' ) {
  30650. /**
  30651. * The name of the code.
  30652. *
  30653. * @type {string}
  30654. */
  30655. this.name = name;
  30656. /**
  30657. * The node type.
  30658. *
  30659. * @type {string}
  30660. */
  30661. this.type = type;
  30662. /**
  30663. * The native shader code.
  30664. *
  30665. * @type {string}
  30666. * @default ''
  30667. */
  30668. this.code = code;
  30669. Object.defineProperty( this, 'isNodeCode', { value: true } );
  30670. }
  30671. }
  30672. let _id$5 = 0;
  30673. /**
  30674. * This utility class is used in {@link NodeBuilder} as an internal
  30675. * cache data structure for node data.
  30676. */
  30677. class NodeCache {
  30678. /**
  30679. * Constructs a new node cache.
  30680. *
  30681. * @param {?NodeCache} parent - A reference to a parent cache.
  30682. */
  30683. constructor( parent = null ) {
  30684. /**
  30685. * The id of the cache.
  30686. *
  30687. * @type {number}
  30688. * @readonly
  30689. */
  30690. this.id = _id$5 ++;
  30691. /**
  30692. * A weak map for managing node data.
  30693. *
  30694. * @type {WeakMap<Node, Object>}
  30695. */
  30696. this.nodesData = new WeakMap();
  30697. /**
  30698. * Reference to a parent node cache.
  30699. *
  30700. * @type {?NodeCache}
  30701. * @default null
  30702. */
  30703. this.parent = parent;
  30704. }
  30705. /**
  30706. * Returns the data for the given node.
  30707. *
  30708. * @param {Node} node - The node.
  30709. * @return {?Object} The data for the node.
  30710. */
  30711. getData( node ) {
  30712. let data = this.nodesData.get( node );
  30713. if ( data === undefined && this.parent !== null ) {
  30714. data = this.parent.getData( node );
  30715. }
  30716. return data;
  30717. }
  30718. /**
  30719. * Sets the data for a given node.
  30720. *
  30721. * @param {Node} node - The node.
  30722. * @param {Object} data - The data that should be cached.
  30723. */
  30724. setData( node, data ) {
  30725. this.nodesData.set( node, data );
  30726. }
  30727. }
  30728. class StructType {
  30729. constructor( name, members ) {
  30730. this.name = name;
  30731. this.members = members;
  30732. this.output = false;
  30733. }
  30734. }
  30735. /**
  30736. * Abstract base class for uniforms.
  30737. *
  30738. * @abstract
  30739. * @private
  30740. */
  30741. class Uniform {
  30742. /**
  30743. * Constructs a new uniform.
  30744. *
  30745. * @param {string} name - The uniform's name.
  30746. * @param {any} value - The uniform's value.
  30747. */
  30748. constructor( name, value ) {
  30749. /**
  30750. * The uniform's name.
  30751. *
  30752. * @type {string}
  30753. */
  30754. this.name = name;
  30755. /**
  30756. * The uniform's value.
  30757. *
  30758. * @type {any}
  30759. */
  30760. this.value = value;
  30761. /**
  30762. * Used to build the uniform buffer according to the STD140 layout.
  30763. * Derived uniforms will set this property to a data type specific
  30764. * value.
  30765. *
  30766. * @type {number}
  30767. */
  30768. this.boundary = 0;
  30769. /**
  30770. * The item size. Derived uniforms will set this property to a data
  30771. * type specific value.
  30772. *
  30773. * @type {number}
  30774. */
  30775. this.itemSize = 0;
  30776. /**
  30777. * This property is set by {@link UniformsGroup} and marks
  30778. * the start position in the uniform buffer.
  30779. *
  30780. * @type {number}
  30781. */
  30782. this.offset = 0;
  30783. }
  30784. /**
  30785. * Sets the uniform's value.
  30786. *
  30787. * @param {any} value - The value to set.
  30788. */
  30789. setValue( value ) {
  30790. this.value = value;
  30791. }
  30792. /**
  30793. * Returns the uniform's value.
  30794. *
  30795. * @return {any} The value.
  30796. */
  30797. getValue() {
  30798. return this.value;
  30799. }
  30800. }
  30801. /**
  30802. * Represents a Number uniform.
  30803. *
  30804. * @private
  30805. * @augments Uniform
  30806. */
  30807. class NumberUniform extends Uniform {
  30808. /**
  30809. * Constructs a new Number uniform.
  30810. *
  30811. * @param {string} name - The uniform's name.
  30812. * @param {number} value - The uniform's value.
  30813. */
  30814. constructor( name, value = 0 ) {
  30815. super( name, value );
  30816. /**
  30817. * This flag can be used for type testing.
  30818. *
  30819. * @type {boolean}
  30820. * @readonly
  30821. * @default true
  30822. */
  30823. this.isNumberUniform = true;
  30824. this.boundary = 4;
  30825. this.itemSize = 1;
  30826. }
  30827. }
  30828. /**
  30829. * Represents a Vector2 uniform.
  30830. *
  30831. * @private
  30832. * @augments Uniform
  30833. */
  30834. class Vector2Uniform extends Uniform {
  30835. /**
  30836. * Constructs a new Number uniform.
  30837. *
  30838. * @param {string} name - The uniform's name.
  30839. * @param {Vector2} value - The uniform's value.
  30840. */
  30841. constructor( name, value = new Vector2() ) {
  30842. super( name, value );
  30843. /**
  30844. * This flag can be used for type testing.
  30845. *
  30846. * @type {boolean}
  30847. * @readonly
  30848. * @default true
  30849. */
  30850. this.isVector2Uniform = true;
  30851. this.boundary = 8;
  30852. this.itemSize = 2;
  30853. }
  30854. }
  30855. /**
  30856. * Represents a Vector3 uniform.
  30857. *
  30858. * @private
  30859. * @augments Uniform
  30860. */
  30861. class Vector3Uniform extends Uniform {
  30862. /**
  30863. * Constructs a new Number uniform.
  30864. *
  30865. * @param {string} name - The uniform's name.
  30866. * @param {Vector3} value - The uniform's value.
  30867. */
  30868. constructor( name, value = new Vector3() ) {
  30869. super( name, value );
  30870. /**
  30871. * This flag can be used for type testing.
  30872. *
  30873. * @type {boolean}
  30874. * @readonly
  30875. * @default true
  30876. */
  30877. this.isVector3Uniform = true;
  30878. this.boundary = 16;
  30879. this.itemSize = 3;
  30880. }
  30881. }
  30882. /**
  30883. * Represents a Vector4 uniform.
  30884. *
  30885. * @private
  30886. * @augments Uniform
  30887. */
  30888. class Vector4Uniform extends Uniform {
  30889. /**
  30890. * Constructs a new Number uniform.
  30891. *
  30892. * @param {string} name - The uniform's name.
  30893. * @param {Vector4} value - The uniform's value.
  30894. */
  30895. constructor( name, value = new Vector4() ) {
  30896. super( name, value );
  30897. /**
  30898. * This flag can be used for type testing.
  30899. *
  30900. * @type {boolean}
  30901. * @readonly
  30902. * @default true
  30903. */
  30904. this.isVector4Uniform = true;
  30905. this.boundary = 16;
  30906. this.itemSize = 4;
  30907. }
  30908. }
  30909. /**
  30910. * Represents a Color uniform.
  30911. *
  30912. * @private
  30913. * @augments Uniform
  30914. */
  30915. class ColorUniform extends Uniform {
  30916. /**
  30917. * Constructs a new Number uniform.
  30918. *
  30919. * @param {string} name - The uniform's name.
  30920. * @param {Color} value - The uniform's value.
  30921. */
  30922. constructor( name, value = new Color() ) {
  30923. super( name, value );
  30924. /**
  30925. * This flag can be used for type testing.
  30926. *
  30927. * @type {boolean}
  30928. * @readonly
  30929. * @default true
  30930. */
  30931. this.isColorUniform = true;
  30932. this.boundary = 16;
  30933. this.itemSize = 3;
  30934. }
  30935. }
  30936. /**
  30937. * Represents a Matrix2 uniform.
  30938. *
  30939. * @private
  30940. * @augments Uniform
  30941. */
  30942. class Matrix2Uniform extends Uniform {
  30943. /**
  30944. * Constructs a new Number uniform.
  30945. *
  30946. * @param {string} name - The uniform's name.
  30947. * @param {Matrix2} value - The uniform's value.
  30948. */
  30949. constructor( name, value = new Matrix2() ) {
  30950. super( name, value );
  30951. /**
  30952. * This flag can be used for type testing.
  30953. *
  30954. * @type {boolean}
  30955. * @readonly
  30956. * @default true
  30957. */
  30958. this.isMatrix2Uniform = true;
  30959. this.boundary = 16;
  30960. this.itemSize = 4;
  30961. }
  30962. }
  30963. /**
  30964. * Represents a Matrix3 uniform.
  30965. *
  30966. * @private
  30967. * @augments Uniform
  30968. */
  30969. class Matrix3Uniform extends Uniform {
  30970. /**
  30971. * Constructs a new Number uniform.
  30972. *
  30973. * @param {string} name - The uniform's name.
  30974. * @param {Matrix3} value - The uniform's value.
  30975. */
  30976. constructor( name, value = new Matrix3() ) {
  30977. super( name, value );
  30978. /**
  30979. * This flag can be used for type testing.
  30980. *
  30981. * @type {boolean}
  30982. * @readonly
  30983. * @default true
  30984. */
  30985. this.isMatrix3Uniform = true;
  30986. this.boundary = 48;
  30987. this.itemSize = 12;
  30988. }
  30989. }
  30990. /**
  30991. * Represents a Matrix4 uniform.
  30992. *
  30993. * @private
  30994. * @augments Uniform
  30995. */
  30996. class Matrix4Uniform extends Uniform {
  30997. /**
  30998. * Constructs a new Number uniform.
  30999. *
  31000. * @param {string} name - The uniform's name.
  31001. * @param {Matrix4} value - The uniform's value.
  31002. */
  31003. constructor( name, value = new Matrix4() ) {
  31004. super( name, value );
  31005. /**
  31006. * This flag can be used for type testing.
  31007. *
  31008. * @type {boolean}
  31009. * @readonly
  31010. * @default true
  31011. */
  31012. this.isMatrix4Uniform = true;
  31013. this.boundary = 64;
  31014. this.itemSize = 16;
  31015. }
  31016. }
  31017. /**
  31018. * A special form of Number uniform binding type.
  31019. * It's value is managed by a node object.
  31020. *
  31021. * @private
  31022. * @augments NumberUniform
  31023. */
  31024. class NumberNodeUniform extends NumberUniform {
  31025. /**
  31026. * Constructs a new node-based Number uniform.
  31027. *
  31028. * @param {NodeUniform} nodeUniform - The node uniform.
  31029. */
  31030. constructor( nodeUniform ) {
  31031. super( nodeUniform.name, nodeUniform.value );
  31032. /**
  31033. * The node uniform.
  31034. *
  31035. * @type {NodeUniform}
  31036. */
  31037. this.nodeUniform = nodeUniform;
  31038. }
  31039. /**
  31040. * Overwritten to return the value of the node uniform.
  31041. *
  31042. * @return {number} The value.
  31043. */
  31044. getValue() {
  31045. return this.nodeUniform.value;
  31046. }
  31047. /**
  31048. * Returns the node uniform data type.
  31049. *
  31050. * @return {string} The data type.
  31051. */
  31052. getType() {
  31053. return this.nodeUniform.type;
  31054. }
  31055. }
  31056. /**
  31057. * A special form of Vector2 uniform binding type.
  31058. * It's value is managed by a node object.
  31059. *
  31060. * @private
  31061. * @augments Vector2Uniform
  31062. */
  31063. class Vector2NodeUniform extends Vector2Uniform {
  31064. /**
  31065. * Constructs a new node-based Vector2 uniform.
  31066. *
  31067. * @param {NodeUniform} nodeUniform - The node uniform.
  31068. */
  31069. constructor( nodeUniform ) {
  31070. super( nodeUniform.name, nodeUniform.value );
  31071. /**
  31072. * The node uniform.
  31073. *
  31074. * @type {NodeUniform}
  31075. */
  31076. this.nodeUniform = nodeUniform;
  31077. }
  31078. /**
  31079. * Overwritten to return the value of the node uniform.
  31080. *
  31081. * @return {Vector2} The value.
  31082. */
  31083. getValue() {
  31084. return this.nodeUniform.value;
  31085. }
  31086. /**
  31087. * Returns the node uniform data type.
  31088. *
  31089. * @return {string} The data type.
  31090. */
  31091. getType() {
  31092. return this.nodeUniform.type;
  31093. }
  31094. }
  31095. /**
  31096. * A special form of Vector3 uniform binding type.
  31097. * It's value is managed by a node object.
  31098. *
  31099. * @private
  31100. * @augments Vector3Uniform
  31101. */
  31102. class Vector3NodeUniform extends Vector3Uniform {
  31103. /**
  31104. * Constructs a new node-based Vector3 uniform.
  31105. *
  31106. * @param {NodeUniform} nodeUniform - The node uniform.
  31107. */
  31108. constructor( nodeUniform ) {
  31109. super( nodeUniform.name, nodeUniform.value );
  31110. /**
  31111. * The node uniform.
  31112. *
  31113. * @type {NodeUniform}
  31114. */
  31115. this.nodeUniform = nodeUniform;
  31116. }
  31117. /**
  31118. * Overwritten to return the value of the node uniform.
  31119. *
  31120. * @return {Vector3} The value.
  31121. */
  31122. getValue() {
  31123. return this.nodeUniform.value;
  31124. }
  31125. /**
  31126. * Returns the node uniform data type.
  31127. *
  31128. * @return {string} The data type.
  31129. */
  31130. getType() {
  31131. return this.nodeUniform.type;
  31132. }
  31133. }
  31134. /**
  31135. * A special form of Vector4 uniform binding type.
  31136. * It's value is managed by a node object.
  31137. *
  31138. * @private
  31139. * @augments Vector4Uniform
  31140. */
  31141. class Vector4NodeUniform extends Vector4Uniform {
  31142. /**
  31143. * Constructs a new node-based Vector4 uniform.
  31144. *
  31145. * @param {NodeUniform} nodeUniform - The node uniform.
  31146. */
  31147. constructor( nodeUniform ) {
  31148. super( nodeUniform.name, nodeUniform.value );
  31149. /**
  31150. * The node uniform.
  31151. *
  31152. * @type {NodeUniform}
  31153. */
  31154. this.nodeUniform = nodeUniform;
  31155. }
  31156. /**
  31157. * Overwritten to return the value of the node uniform.
  31158. *
  31159. * @return {Vector4} The value.
  31160. */
  31161. getValue() {
  31162. return this.nodeUniform.value;
  31163. }
  31164. /**
  31165. * Returns the node uniform data type.
  31166. *
  31167. * @return {string} The data type.
  31168. */
  31169. getType() {
  31170. return this.nodeUniform.type;
  31171. }
  31172. }
  31173. /**
  31174. * A special form of Color uniform binding type.
  31175. * It's value is managed by a node object.
  31176. *
  31177. * @private
  31178. * @augments ColorUniform
  31179. */
  31180. class ColorNodeUniform extends ColorUniform {
  31181. /**
  31182. * Constructs a new node-based Color uniform.
  31183. *
  31184. * @param {NodeUniform} nodeUniform - The node uniform.
  31185. */
  31186. constructor( nodeUniform ) {
  31187. super( nodeUniform.name, nodeUniform.value );
  31188. /**
  31189. * The node uniform.
  31190. *
  31191. * @type {NodeUniform}
  31192. */
  31193. this.nodeUniform = nodeUniform;
  31194. }
  31195. /**
  31196. * Overwritten to return the value of the node uniform.
  31197. *
  31198. * @return {Color} The value.
  31199. */
  31200. getValue() {
  31201. return this.nodeUniform.value;
  31202. }
  31203. /**
  31204. * Returns the node uniform data type.
  31205. *
  31206. * @return {string} The data type.
  31207. */
  31208. getType() {
  31209. return this.nodeUniform.type;
  31210. }
  31211. }
  31212. /**
  31213. * A special form of Matrix2 uniform binding type.
  31214. * It's value is managed by a node object.
  31215. *
  31216. * @private
  31217. * @augments Matrix2Uniform
  31218. */
  31219. class Matrix2NodeUniform extends Matrix2Uniform {
  31220. /**
  31221. * Constructs a new node-based Matrix2 uniform.
  31222. *
  31223. * @param {NodeUniform} nodeUniform - The node uniform.
  31224. */
  31225. constructor( nodeUniform ) {
  31226. super( nodeUniform.name, nodeUniform.value );
  31227. /**
  31228. * The node uniform.
  31229. *
  31230. * @type {NodeUniform}
  31231. */
  31232. this.nodeUniform = nodeUniform;
  31233. }
  31234. /**
  31235. * Overwritten to return the value of the node uniform.
  31236. *
  31237. * @return {Matrix2} The value.
  31238. */
  31239. getValue() {
  31240. return this.nodeUniform.value;
  31241. }
  31242. /**
  31243. * Returns the node uniform data type.
  31244. *
  31245. * @return {string} The data type.
  31246. */
  31247. getType() {
  31248. return this.nodeUniform.type;
  31249. }
  31250. }
  31251. /**
  31252. * A special form of Matrix3 uniform binding type.
  31253. * It's value is managed by a node object.
  31254. *
  31255. * @private
  31256. * @augments Matrix3Uniform
  31257. */
  31258. class Matrix3NodeUniform extends Matrix3Uniform {
  31259. /**
  31260. * Constructs a new node-based Matrix3 uniform.
  31261. *
  31262. * @param {NodeUniform} nodeUniform - The node uniform.
  31263. */
  31264. constructor( nodeUniform ) {
  31265. super( nodeUniform.name, nodeUniform.value );
  31266. /**
  31267. * The node uniform.
  31268. *
  31269. * @type {NodeUniform}
  31270. */
  31271. this.nodeUniform = nodeUniform;
  31272. }
  31273. /**
  31274. * Overwritten to return the value of the node uniform.
  31275. *
  31276. * @return {Matrix3} The value.
  31277. */
  31278. getValue() {
  31279. return this.nodeUniform.value;
  31280. }
  31281. /**
  31282. * Returns the node uniform data type.
  31283. *
  31284. * @return {string} The data type.
  31285. */
  31286. getType() {
  31287. return this.nodeUniform.type;
  31288. }
  31289. }
  31290. /**
  31291. * A special form of Matrix4 uniform binding type.
  31292. * It's value is managed by a node object.
  31293. *
  31294. * @private
  31295. * @augments Matrix4Uniform
  31296. */
  31297. class Matrix4NodeUniform extends Matrix4Uniform {
  31298. /**
  31299. * Constructs a new node-based Matrix4 uniform.
  31300. *
  31301. * @param {NodeUniform} nodeUniform - The node uniform.
  31302. */
  31303. constructor( nodeUniform ) {
  31304. super( nodeUniform.name, nodeUniform.value );
  31305. /**
  31306. * The node uniform.
  31307. *
  31308. * @type {NodeUniform}
  31309. */
  31310. this.nodeUniform = nodeUniform;
  31311. }
  31312. /**
  31313. * Overwritten to return the value of the node uniform.
  31314. *
  31315. * @return {Matrix4} The value.
  31316. */
  31317. getValue() {
  31318. return this.nodeUniform.value;
  31319. }
  31320. /**
  31321. * Returns the node uniform data type.
  31322. *
  31323. * @return {string} The data type.
  31324. */
  31325. getType() {
  31326. return this.nodeUniform.type;
  31327. }
  31328. }
  31329. const rendererCache = new WeakMap();
  31330. const typeFromArray = new Map( [
  31331. [ Int8Array, 'int' ],
  31332. [ Int16Array, 'int' ],
  31333. [ Int32Array, 'int' ],
  31334. [ Uint8Array, 'uint' ],
  31335. [ Uint16Array, 'uint' ],
  31336. [ Uint32Array, 'uint' ],
  31337. [ Float32Array, 'float' ]
  31338. ] );
  31339. const toFloat = ( value ) => {
  31340. if ( /e/g.test( value ) ) {
  31341. return String( value ).replace( /\+/g, '' );
  31342. } else {
  31343. value = Number( value );
  31344. return value + ( value % 1 ? '' : '.0' );
  31345. }
  31346. };
  31347. /**
  31348. * Base class for builders which generate a shader program based
  31349. * on a 3D object and its node material definition.
  31350. */
  31351. class NodeBuilder {
  31352. /**
  31353. * Constructs a new node builder.
  31354. *
  31355. * @param {Object3D} object - The 3D object.
  31356. * @param {Renderer} renderer - The current renderer.
  31357. * @param {NodeParser} parser - A reference to a node parser.
  31358. */
  31359. constructor( object, renderer, parser ) {
  31360. /**
  31361. * The 3D object.
  31362. *
  31363. * @type {Object3D}
  31364. */
  31365. this.object = object;
  31366. /**
  31367. * The material of the 3D object.
  31368. *
  31369. * @type {?Material}
  31370. */
  31371. this.material = ( object && object.material ) || null;
  31372. /**
  31373. * The geometry of the 3D object.
  31374. *
  31375. * @type {?BufferGeometry}
  31376. */
  31377. this.geometry = ( object && object.geometry ) || null;
  31378. /**
  31379. * The current renderer.
  31380. *
  31381. * @type {Renderer}
  31382. */
  31383. this.renderer = renderer;
  31384. /**
  31385. * A reference to a node parser.
  31386. *
  31387. * @type {NodeParser}
  31388. */
  31389. this.parser = parser;
  31390. /**
  31391. * The scene the 3D object belongs to.
  31392. *
  31393. * @type {?Scene}
  31394. * @default null
  31395. */
  31396. this.scene = null;
  31397. /**
  31398. * The camera the 3D object is rendered with.
  31399. *
  31400. * @type {?Camera}
  31401. * @default null
  31402. */
  31403. this.camera = null;
  31404. /**
  31405. * A list of all nodes the builder is processing
  31406. * for this 3D object.
  31407. *
  31408. * @type {Array<Node>}
  31409. */
  31410. this.nodes = [];
  31411. /**
  31412. * A list of all sequential nodes.
  31413. *
  31414. * @type {Array<Node>}
  31415. */
  31416. this.sequentialNodes = [];
  31417. /**
  31418. * A list of all nodes which {@link Node#update} method should be executed.
  31419. *
  31420. * @type {Array<Node>}
  31421. */
  31422. this.updateNodes = [];
  31423. /**
  31424. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  31425. *
  31426. * @type {Array<Node>}
  31427. */
  31428. this.updateBeforeNodes = [];
  31429. /**
  31430. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  31431. *
  31432. * @type {Array<Node>}
  31433. */
  31434. this.updateAfterNodes = [];
  31435. /**
  31436. * A dictionary that assigns each node to a unique hash.
  31437. *
  31438. * @type {Object<number,Node>}
  31439. */
  31440. this.hashNodes = {};
  31441. /**
  31442. * A reference to a node material observer.
  31443. *
  31444. * @type {?NodeMaterialObserver}
  31445. * @default null
  31446. */
  31447. this.observer = null;
  31448. /**
  31449. * A reference to the current lights node.
  31450. *
  31451. * @type {?LightsNode}
  31452. * @default null
  31453. */
  31454. this.lightsNode = null;
  31455. /**
  31456. * A reference to the current environment node.
  31457. *
  31458. * @type {?Node}
  31459. * @default null
  31460. */
  31461. this.environmentNode = null;
  31462. /**
  31463. * A reference to the current fog node.
  31464. *
  31465. * @type {?FogNode}
  31466. * @default null
  31467. */
  31468. this.fogNode = null;
  31469. /**
  31470. * The current clipping context.
  31471. *
  31472. * @type {?ClippingContext}
  31473. */
  31474. this.clippingContext = null;
  31475. /**
  31476. * The generated vertex shader.
  31477. *
  31478. * @type {?string}
  31479. */
  31480. this.vertexShader = null;
  31481. /**
  31482. * The generated fragment shader.
  31483. *
  31484. * @type {?string}
  31485. */
  31486. this.fragmentShader = null;
  31487. /**
  31488. * The generated compute shader.
  31489. *
  31490. * @type {?string}
  31491. */
  31492. this.computeShader = null;
  31493. /**
  31494. * Nodes used in the primary flow of code generation.
  31495. *
  31496. * @type {Object<string,Array<Node>>}
  31497. */
  31498. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  31499. /**
  31500. * Nodes code from `.flowNodes`.
  31501. *
  31502. * @type {Object<string,string>}
  31503. */
  31504. this.flowCode = { vertex: '', fragment: '', compute: '' };
  31505. /**
  31506. * This dictionary holds the node uniforms of the builder.
  31507. * The uniforms are maintained in an array for each shader stage.
  31508. *
  31509. * @type {Object}
  31510. */
  31511. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  31512. /**
  31513. * This dictionary holds the output structs of the builder.
  31514. * The structs are maintained in an array for each shader stage.
  31515. *
  31516. * @type {Object}
  31517. */
  31518. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  31519. /**
  31520. * This dictionary holds the bindings for each shader stage.
  31521. *
  31522. * @type {Object}
  31523. */
  31524. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  31525. /**
  31526. * This dictionary maintains the binding indices per bind group.
  31527. *
  31528. * @type {Object}
  31529. */
  31530. this.bindingsIndexes = {};
  31531. /**
  31532. * Reference to the array of bind groups.
  31533. *
  31534. * @type {?Array<BindGroup>}
  31535. */
  31536. this.bindGroups = null;
  31537. /**
  31538. * This array holds the node attributes of this builder
  31539. * created via {@link AttributeNode}.
  31540. *
  31541. * @type {Array<NodeAttribute>}
  31542. */
  31543. this.attributes = [];
  31544. /**
  31545. * This array holds the node attributes of this builder
  31546. * created via {@link BufferAttributeNode}.
  31547. *
  31548. * @type {Array<NodeAttribute>}
  31549. */
  31550. this.bufferAttributes = [];
  31551. /**
  31552. * This array holds the node varyings of this builder.
  31553. *
  31554. * @type {Array<NodeVarying>}
  31555. */
  31556. this.varyings = [];
  31557. /**
  31558. * This dictionary holds the (native) node codes of this builder.
  31559. * The codes are maintained in an array for each shader stage.
  31560. *
  31561. * @type {Object<string,Array<NodeCode>>}
  31562. */
  31563. this.codes = {};
  31564. /**
  31565. * This dictionary holds the node variables of this builder.
  31566. * The variables are maintained in an array for each shader stage.
  31567. * This dictionary is also used to count the number of variables
  31568. * according to their type (const, vars).
  31569. *
  31570. * @type {Object<string,Array<NodeVar>|number>}
  31571. */
  31572. this.vars = {};
  31573. /**
  31574. * This dictionary holds the declarations for each shader stage.
  31575. *
  31576. * @type {Object}
  31577. */
  31578. this.declarations = {};
  31579. /**
  31580. * Current code flow.
  31581. * All code generated in this stack will be stored in `.flow`.
  31582. *
  31583. * @type {{code: string}}
  31584. */
  31585. this.flow = { code: '' };
  31586. /**
  31587. * A chain of nodes.
  31588. * Used to check recursive calls in node-graph.
  31589. *
  31590. * @type {Array<Node>}
  31591. */
  31592. this.chaining = [];
  31593. /**
  31594. * The current stack.
  31595. * This reflects the current process in the code block hierarchy,
  31596. * it is useful to know if the current process is inside a conditional for example.
  31597. *
  31598. * @type {StackNode}
  31599. */
  31600. this.stack = stack();
  31601. /**
  31602. * List of stack nodes.
  31603. * The current stack hierarchy is stored in an array.
  31604. *
  31605. * @type {Array<StackNode>}
  31606. */
  31607. this.stacks = [];
  31608. /**
  31609. * A tab value. Used for shader string generation.
  31610. *
  31611. * @type {string}
  31612. * @default '\t'
  31613. */
  31614. this.tab = '\t';
  31615. /**
  31616. * Reference to the current function node.
  31617. *
  31618. * @type {?FunctionNode}
  31619. * @default null
  31620. */
  31621. this.currentFunctionNode = null;
  31622. /**
  31623. * The builder's context.
  31624. *
  31625. * @type {Object}
  31626. */
  31627. this.context = {
  31628. material: this.material
  31629. };
  31630. /**
  31631. * The builder's cache.
  31632. *
  31633. * @type {NodeCache}
  31634. */
  31635. this.cache = new NodeCache();
  31636. /**
  31637. * Since the {@link NodeBuilder#cache} might be temporarily
  31638. * overwritten by other caches, this member retains the reference
  31639. * to the builder's own cache.
  31640. *
  31641. * @type {NodeCache}
  31642. * @default this.cache
  31643. */
  31644. this.globalCache = this.cache;
  31645. this.flowsData = new WeakMap();
  31646. /**
  31647. * The current shader stage.
  31648. *
  31649. * @type {?('vertex'|'fragment'|'compute'|'any')}
  31650. */
  31651. this.shaderStage = null;
  31652. /**
  31653. * The current build stage.
  31654. *
  31655. * @type {?('setup'|'analyze'|'generate')}
  31656. */
  31657. this.buildStage = null;
  31658. }
  31659. /**
  31660. * Returns the bind groups of the current renderer.
  31661. *
  31662. * @return {ChainMap} The cache.
  31663. */
  31664. getBindGroupsCache() {
  31665. let bindGroupsCache = rendererCache.get( this.renderer );
  31666. if ( bindGroupsCache === undefined ) {
  31667. bindGroupsCache = new ChainMap();
  31668. rendererCache.set( this.renderer, bindGroupsCache );
  31669. }
  31670. return bindGroupsCache;
  31671. }
  31672. /**
  31673. * Factory method for creating an instance of {@link RenderTarget} with the given
  31674. * dimensions and options.
  31675. *
  31676. * @param {number} width - The width of the render target.
  31677. * @param {number} height - The height of the render target.
  31678. * @param {Object} options - The options of the render target.
  31679. * @return {RenderTarget} The render target.
  31680. */
  31681. createRenderTarget( width, height, options ) {
  31682. return new RenderTarget( width, height, options );
  31683. }
  31684. /**
  31685. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  31686. * dimensions and options.
  31687. *
  31688. * @param {number} size - The size of the cube render target.
  31689. * @param {Object} options - The options of the cube render target.
  31690. * @return {CubeRenderTarget} The cube render target.
  31691. */
  31692. createCubeRenderTarget( size, options ) {
  31693. return new CubeRenderTarget( size, options );
  31694. }
  31695. /**
  31696. * Whether the given node is included in the internal array of nodes or not.
  31697. *
  31698. * @param {Node} node - The node to test.
  31699. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  31700. */
  31701. includes( node ) {
  31702. return this.nodes.includes( node );
  31703. }
  31704. /**
  31705. * Returns the output struct name which is required by
  31706. * {@link OutputStructNode}.
  31707. *
  31708. * @abstract
  31709. * @return {string} The name of the output struct.
  31710. */
  31711. getOutputStructName() {}
  31712. /**
  31713. * Returns a bind group for the given group name and binding.
  31714. *
  31715. * @private
  31716. * @param {string} groupName - The group name.
  31717. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  31718. * @return {BindGroup} The bind group
  31719. */
  31720. _getBindGroup( groupName, bindings ) {
  31721. const bindGroupsCache = this.getBindGroupsCache();
  31722. //
  31723. const bindingsArray = [];
  31724. let sharedGroup = true;
  31725. for ( const binding of bindings ) {
  31726. bindingsArray.push( binding );
  31727. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  31728. }
  31729. //
  31730. let bindGroup;
  31731. if ( sharedGroup ) {
  31732. bindGroup = bindGroupsCache.get( bindingsArray );
  31733. if ( bindGroup === undefined ) {
  31734. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31735. bindGroupsCache.set( bindingsArray, bindGroup );
  31736. }
  31737. } else {
  31738. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31739. }
  31740. return bindGroup;
  31741. }
  31742. /**
  31743. * Returns an array of node uniform groups for the given group name and shader stage.
  31744. *
  31745. * @param {string} groupName - The group name.
  31746. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31747. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  31748. */
  31749. getBindGroupArray( groupName, shaderStage ) {
  31750. const bindings = this.bindings[ shaderStage ];
  31751. let bindGroup = bindings[ groupName ];
  31752. if ( bindGroup === undefined ) {
  31753. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  31754. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  31755. }
  31756. bindings[ groupName ] = bindGroup = [];
  31757. }
  31758. return bindGroup;
  31759. }
  31760. /**
  31761. * Returns a list bindings of all shader stages separated by groups.
  31762. *
  31763. * @return {Array<BindGroup>} The list of bindings.
  31764. */
  31765. getBindings() {
  31766. let bindingsGroups = this.bindGroups;
  31767. if ( bindingsGroups === null ) {
  31768. const groups = {};
  31769. const bindings = this.bindings;
  31770. for ( const shaderStage of shaderStages ) {
  31771. for ( const groupName in bindings[ shaderStage ] ) {
  31772. const uniforms = bindings[ shaderStage ][ groupName ];
  31773. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  31774. groupUniforms.push( ...uniforms );
  31775. }
  31776. }
  31777. bindingsGroups = [];
  31778. for ( const groupName in groups ) {
  31779. const group = groups[ groupName ];
  31780. const bindingsGroup = this._getBindGroup( groupName, group );
  31781. bindingsGroups.push( bindingsGroup );
  31782. }
  31783. this.bindGroups = bindingsGroups;
  31784. }
  31785. return bindingsGroups;
  31786. }
  31787. /**
  31788. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  31789. */
  31790. sortBindingGroups() {
  31791. const bindingsGroups = this.getBindings();
  31792. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  31793. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  31794. const bindingGroup = bindingsGroups[ i ];
  31795. this.bindingsIndexes[ bindingGroup.name ].group = i;
  31796. bindingGroup.index = i;
  31797. }
  31798. }
  31799. /**
  31800. * The builder maintains each node in a hash-based dictionary.
  31801. * This method sets the given node (value) with the given hash (key) into this dictionary.
  31802. *
  31803. * @param {Node} node - The node to add.
  31804. * @param {number} hash - The hash of the node.
  31805. */
  31806. setHashNode( node, hash ) {
  31807. this.hashNodes[ hash ] = node;
  31808. }
  31809. /**
  31810. * Adds a node to this builder.
  31811. *
  31812. * @param {Node} node - The node to add.
  31813. */
  31814. addNode( node ) {
  31815. if ( this.nodes.includes( node ) === false ) {
  31816. this.nodes.push( node );
  31817. this.setHashNode( node, node.getHash( this ) );
  31818. }
  31819. }
  31820. /**
  31821. * It is used to add Nodes that will be used as FRAME and RENDER events,
  31822. * and need to follow a certain sequence in the calls to work correctly.
  31823. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  31824. *
  31825. * @param {Node} node - The node to add.
  31826. */
  31827. addSequentialNode( node ) {
  31828. if ( this.sequentialNodes.includes( node ) === false ) {
  31829. this.sequentialNodes.push( node );
  31830. }
  31831. }
  31832. /**
  31833. * Checks the update types of nodes
  31834. */
  31835. buildUpdateNodes() {
  31836. for ( const node of this.nodes ) {
  31837. const updateType = node.getUpdateType();
  31838. if ( updateType !== NodeUpdateType.NONE ) {
  31839. this.updateNodes.push( node.getSelf() );
  31840. }
  31841. }
  31842. for ( const node of this.sequentialNodes ) {
  31843. const updateBeforeType = node.getUpdateBeforeType();
  31844. const updateAfterType = node.getUpdateAfterType();
  31845. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  31846. this.updateBeforeNodes.push( node.getSelf() );
  31847. }
  31848. if ( updateAfterType !== NodeUpdateType.NONE ) {
  31849. this.updateAfterNodes.push( node.getSelf() );
  31850. }
  31851. }
  31852. }
  31853. /**
  31854. * A reference the current node which is the
  31855. * last node in the chain of nodes.
  31856. *
  31857. * @type {Node}
  31858. */
  31859. get currentNode() {
  31860. return this.chaining[ this.chaining.length - 1 ];
  31861. }
  31862. /**
  31863. * Whether the given texture is filtered or not.
  31864. *
  31865. * @param {Texture} texture - The texture to check.
  31866. * @return {boolean} Whether the given texture is filtered or not.
  31867. */
  31868. isFilteredTexture( texture ) {
  31869. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  31870. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  31871. }
  31872. /**
  31873. * Adds the given node to the internal node chain.
  31874. * This is used to check recursive calls in node-graph.
  31875. *
  31876. * @param {Node} node - The node to add.
  31877. */
  31878. addChain( node ) {
  31879. /*
  31880. if ( this.chaining.indexOf( node ) !== - 1 ) {
  31881. console.warn( 'Recursive node: ', node );
  31882. }
  31883. */
  31884. this.chaining.push( node );
  31885. }
  31886. /**
  31887. * Removes the given node from the internal node chain.
  31888. *
  31889. * @param {Node} node - The node to remove.
  31890. */
  31891. removeChain( node ) {
  31892. const lastChain = this.chaining.pop();
  31893. if ( lastChain !== node ) {
  31894. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  31895. }
  31896. }
  31897. /**
  31898. * Returns the native shader method name for a given generic name. E.g.
  31899. * the method name `textureDimensions` matches the WGSL name but must be
  31900. * resolved to `textureSize` in GLSL.
  31901. *
  31902. * @abstract
  31903. * @param {string} method - The method name to resolve.
  31904. * @return {string} The resolved method name.
  31905. */
  31906. getMethod( method ) {
  31907. return method;
  31908. }
  31909. /**
  31910. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  31911. *
  31912. * @param {number} hash - The hash of the node.
  31913. * @return {Node} The found node.
  31914. */
  31915. getNodeFromHash( hash ) {
  31916. return this.hashNodes[ hash ];
  31917. }
  31918. /**
  31919. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  31920. *
  31921. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  31922. * @param {Node} node - The node to add.
  31923. * @return {Node} The node.
  31924. */
  31925. addFlow( shaderStage, node ) {
  31926. this.flowNodes[ shaderStage ].push( node );
  31927. return node;
  31928. }
  31929. /**
  31930. * Sets builder's context.
  31931. *
  31932. * @param {Object} context - The context to set.
  31933. */
  31934. setContext( context ) {
  31935. this.context = context;
  31936. }
  31937. /**
  31938. * Returns the builder's current context.
  31939. *
  31940. * @return {Object} The builder's current context.
  31941. */
  31942. getContext() {
  31943. return this.context;
  31944. }
  31945. /**
  31946. * Gets a context used in shader construction that can be shared across different materials.
  31947. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  31948. *
  31949. * @return {Object} The builder's current context without material.
  31950. */
  31951. getSharedContext() {
  31952. ({ ...this.context });
  31953. return this.context;
  31954. }
  31955. /**
  31956. * Sets builder's cache.
  31957. *
  31958. * @param {NodeCache} cache - The cache to set.
  31959. */
  31960. setCache( cache ) {
  31961. this.cache = cache;
  31962. }
  31963. /**
  31964. * Returns the builder's current cache.
  31965. *
  31966. * @return {NodeCache} The builder's current cache.
  31967. */
  31968. getCache() {
  31969. return this.cache;
  31970. }
  31971. /**
  31972. * Returns a cache for the given node.
  31973. *
  31974. * @param {Node} node - The node.
  31975. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  31976. * @return {NodeCache} The cache.
  31977. */
  31978. getCacheFromNode( node, parent = true ) {
  31979. const data = this.getDataFromNode( node );
  31980. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  31981. return data.cache;
  31982. }
  31983. /**
  31984. * Whether the requested feature is available or not.
  31985. *
  31986. * @abstract
  31987. * @param {string} name - The requested feature.
  31988. * @return {boolean} Whether the requested feature is supported or not.
  31989. */
  31990. isAvailable( /*name*/ ) {
  31991. return false;
  31992. }
  31993. /**
  31994. * Returns the vertexIndex input variable as a native shader string.
  31995. *
  31996. * @abstract
  31997. * @return {string} The instanceIndex shader string.
  31998. */
  31999. getVertexIndex() {
  32000. console.warn( 'Abstract function.' );
  32001. }
  32002. /**
  32003. * Returns the instanceIndex input variable as a native shader string.
  32004. *
  32005. * @abstract
  32006. * @return {string} The instanceIndex shader string.
  32007. */
  32008. getInstanceIndex() {
  32009. console.warn( 'Abstract function.' );
  32010. }
  32011. /**
  32012. * Returns the drawIndex input variable as a native shader string.
  32013. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  32014. *
  32015. * @abstract
  32016. * @return {?string} The drawIndex shader string.
  32017. */
  32018. getDrawIndex() {
  32019. console.warn( 'Abstract function.' );
  32020. }
  32021. /**
  32022. * Returns the frontFacing input variable as a native shader string.
  32023. *
  32024. * @abstract
  32025. * @return {string} The frontFacing shader string.
  32026. */
  32027. getFrontFacing() {
  32028. console.warn( 'Abstract function.' );
  32029. }
  32030. /**
  32031. * Returns the fragCoord input variable as a native shader string.
  32032. *
  32033. * @abstract
  32034. * @return {string} The fragCoord shader string.
  32035. */
  32036. getFragCoord() {
  32037. console.warn( 'Abstract function.' );
  32038. }
  32039. /**
  32040. * Whether to flip texture data along its vertical axis or not. WebGL needs
  32041. * this method evaluate to `true`, WebGPU to `false`.
  32042. *
  32043. * @abstract
  32044. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  32045. */
  32046. isFlipY() {
  32047. return false;
  32048. }
  32049. /**
  32050. * Calling this method increases the usage count for the given node by one.
  32051. *
  32052. * @param {Node} node - The node to increase the usage count for.
  32053. * @return {number} The updated usage count.
  32054. */
  32055. increaseUsage( node ) {
  32056. const nodeData = this.getDataFromNode( node );
  32057. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  32058. return nodeData.usageCount;
  32059. }
  32060. /**
  32061. * Generates a texture sample shader string for the given texture data.
  32062. *
  32063. * @abstract
  32064. * @param {Texture} texture - The texture.
  32065. * @param {string} textureProperty - The texture property name.
  32066. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32067. * @return {string} The generated shader string.
  32068. */
  32069. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  32070. console.warn( 'Abstract function.' );
  32071. }
  32072. /**
  32073. * Generates a texture LOD shader string for the given texture data.
  32074. *
  32075. * @abstract
  32076. * @param {Texture} texture - The texture.
  32077. * @param {string} textureProperty - The texture property name.
  32078. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32079. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  32080. * @param {string} levelSnippet - Snippet defining the mip level.
  32081. * @return {string} The generated shader string.
  32082. */
  32083. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  32084. console.warn( 'Abstract function.' );
  32085. }
  32086. /**
  32087. * Generates the array declaration string.
  32088. *
  32089. * @param {string} type - The type.
  32090. * @param {?number} [count] - The count.
  32091. * @return {string} The generated value as a shader string.
  32092. */
  32093. generateArrayDeclaration( type, count ) {
  32094. return this.getType( type ) + '[ ' + count + ' ]';
  32095. }
  32096. /**
  32097. * Generates the array shader string for the given type and value.
  32098. *
  32099. * @param {string} type - The type.
  32100. * @param {?number} [count] - The count.
  32101. * @param {?Array<Node>} [values=null] - The default values.
  32102. * @return {string} The generated value as a shader string.
  32103. */
  32104. generateArray( type, count, values = null ) {
  32105. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  32106. for ( let i = 0; i < count; i ++ ) {
  32107. const value = values ? values[ i ] : null;
  32108. if ( value !== null ) {
  32109. snippet += value.build( this, type );
  32110. } else {
  32111. snippet += this.generateConst( type );
  32112. }
  32113. if ( i < count - 1 ) snippet += ', ';
  32114. }
  32115. snippet += ' )';
  32116. return snippet;
  32117. }
  32118. /**
  32119. * Generates the struct shader string.
  32120. *
  32121. * @param {string} type - The type.
  32122. * @param {Array<Object>} [membersLayout] - The count.
  32123. * @param {?Array<Node>} [values=null] - The default values.
  32124. * @return {string} The generated value as a shader string.
  32125. */
  32126. generateStruct( type, membersLayout, values = null ) {
  32127. const snippets = [];
  32128. for ( const member of membersLayout ) {
  32129. const { name, type } = member;
  32130. if ( values && values[ name ] && values[ name ].isNode ) {
  32131. snippets.push( values[ name ].build( this, type ) );
  32132. } else {
  32133. snippets.push( this.generateConst( type ) );
  32134. }
  32135. }
  32136. return type + '( ' + snippets.join( ', ' ) + ' )';
  32137. }
  32138. /**
  32139. * Generates the shader string for the given type and value.
  32140. *
  32141. * @param {string} type - The type.
  32142. * @param {?any} [value=null] - The value.
  32143. * @return {string} The generated value as a shader string.
  32144. */
  32145. generateConst( type, value = null ) {
  32146. if ( value === null ) {
  32147. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  32148. else if ( type === 'bool' ) value = false;
  32149. else if ( type === 'color' ) value = new Color();
  32150. else if ( type === 'vec2' ) value = new Vector2();
  32151. else if ( type === 'vec3' ) value = new Vector3();
  32152. else if ( type === 'vec4' ) value = new Vector4();
  32153. }
  32154. if ( type === 'float' ) return toFloat( value );
  32155. if ( type === 'int' ) return `${ Math.round( value ) }`;
  32156. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  32157. if ( type === 'bool' ) return value ? 'true' : 'false';
  32158. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  32159. const typeLength = this.getTypeLength( type );
  32160. const componentType = this.getComponentType( type );
  32161. const generateConst = value => this.generateConst( componentType, value );
  32162. if ( typeLength === 2 ) {
  32163. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  32164. } else if ( typeLength === 3 ) {
  32165. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  32166. } else if ( typeLength === 4 && type !== 'mat2' ) {
  32167. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  32168. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  32169. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  32170. } else if ( typeLength > 4 ) {
  32171. return `${ this.getType( type ) }()`;
  32172. }
  32173. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  32174. }
  32175. /**
  32176. * It might be necessary to convert certain data types to different ones
  32177. * so this method can be used to hide the conversion.
  32178. *
  32179. * @param {string} type - The type.
  32180. * @return {string} The updated type.
  32181. */
  32182. getType( type ) {
  32183. if ( type === 'color' ) return 'vec3';
  32184. return type;
  32185. }
  32186. /**
  32187. * Whether the given attribute name is defined in the geometry or not.
  32188. *
  32189. * @param {string} name - The attribute name.
  32190. * @return {boolean} Whether the given attribute name is defined in the geometry.
  32191. */
  32192. hasGeometryAttribute( name ) {
  32193. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  32194. }
  32195. /**
  32196. * Returns a node attribute for the given name and type.
  32197. *
  32198. * @param {string} name - The attribute's name.
  32199. * @param {string} type - The attribute's type.
  32200. * @return {NodeAttribute} The node attribute.
  32201. */
  32202. getAttribute( name, type ) {
  32203. const attributes = this.attributes;
  32204. // find attribute
  32205. for ( const attribute of attributes ) {
  32206. if ( attribute.name === name ) {
  32207. return attribute;
  32208. }
  32209. }
  32210. // create a new if no exist
  32211. const attribute = new NodeAttribute( name, type );
  32212. this.registerDeclaration( attribute );
  32213. attributes.push( attribute );
  32214. return attribute;
  32215. }
  32216. /**
  32217. * Returns for the given node and shader stage the property name for the shader.
  32218. *
  32219. * @param {Node} node - The node.
  32220. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32221. * @return {string} The property name.
  32222. */
  32223. getPropertyName( node/*, shaderStage*/ ) {
  32224. return node.name;
  32225. }
  32226. /**
  32227. * Whether the given type is a vector type or not.
  32228. *
  32229. * @param {string} type - The type to check.
  32230. * @return {boolean} Whether the given type is a vector type or not.
  32231. */
  32232. isVector( type ) {
  32233. return /vec\d/.test( type );
  32234. }
  32235. /**
  32236. * Whether the given type is a matrix type or not.
  32237. *
  32238. * @param {string} type - The type to check.
  32239. * @return {boolean} Whether the given type is a matrix type or not.
  32240. */
  32241. isMatrix( type ) {
  32242. return /mat\d/.test( type );
  32243. }
  32244. /**
  32245. * Whether the given type is a reference type or not.
  32246. *
  32247. * @param {string} type - The type to check.
  32248. * @return {boolean} Whether the given type is a reference type or not.
  32249. */
  32250. isReference( type ) {
  32251. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  32252. }
  32253. /**
  32254. * Checks if the given texture requires a manual conversion to the working color space.
  32255. *
  32256. * @abstract
  32257. * @param {Texture} texture - The texture to check.
  32258. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  32259. */
  32260. needsToWorkingColorSpace( /*texture*/ ) {
  32261. return false;
  32262. }
  32263. /**
  32264. * Returns the component type of a given texture.
  32265. *
  32266. * @param {Texture} texture - The texture.
  32267. * @return {string} The component type.
  32268. */
  32269. getComponentTypeFromTexture( texture ) {
  32270. const type = texture.type;
  32271. if ( texture.isDataTexture ) {
  32272. if ( type === IntType ) return 'int';
  32273. if ( type === UnsignedIntType ) return 'uint';
  32274. }
  32275. return 'float';
  32276. }
  32277. /**
  32278. * Returns the element type for a given type.
  32279. *
  32280. * @param {string} type - The type.
  32281. * @return {string} The element type.
  32282. */
  32283. getElementType( type ) {
  32284. if ( type === 'mat2' ) return 'vec2';
  32285. if ( type === 'mat3' ) return 'vec3';
  32286. if ( type === 'mat4' ) return 'vec4';
  32287. return this.getComponentType( type );
  32288. }
  32289. /**
  32290. * Returns the component type for a given type.
  32291. *
  32292. * @param {string} type - The type.
  32293. * @return {string} The component type.
  32294. */
  32295. getComponentType( type ) {
  32296. type = this.getVectorType( type );
  32297. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  32298. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  32299. if ( componentType === null ) return null;
  32300. if ( componentType[ 1 ] === 'b' ) return 'bool';
  32301. if ( componentType[ 1 ] === 'i' ) return 'int';
  32302. if ( componentType[ 1 ] === 'u' ) return 'uint';
  32303. return 'float';
  32304. }
  32305. /**
  32306. * Returns the vector type for a given type.
  32307. *
  32308. * @param {string} type - The type.
  32309. * @return {string} The vector type.
  32310. */
  32311. getVectorType( type ) {
  32312. if ( type === 'color' ) return 'vec3';
  32313. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  32314. return type;
  32315. }
  32316. /**
  32317. * Returns the data type for the given the length and component type.
  32318. *
  32319. * @param {number} length - The length.
  32320. * @param {string} [componentType='float'] - The component type.
  32321. * @return {string} The type.
  32322. */
  32323. getTypeFromLength( length, componentType = 'float' ) {
  32324. if ( length === 1 ) return componentType;
  32325. let baseType = getTypeFromLength( length );
  32326. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  32327. // fix edge case for mat2x2 being same size as vec4
  32328. if ( /mat2/.test( componentType ) === true ) {
  32329. baseType = baseType.replace( 'vec', 'mat' );
  32330. }
  32331. return prefix + baseType;
  32332. }
  32333. /**
  32334. * Returns the type for a given typed array.
  32335. *
  32336. * @param {TypedArray} array - The typed array.
  32337. * @return {string} The type.
  32338. */
  32339. getTypeFromArray( array ) {
  32340. return typeFromArray.get( array.constructor );
  32341. }
  32342. /**
  32343. * Returns the type is an integer type.
  32344. *
  32345. * @param {string} type - The type.
  32346. * @return {boolean} Whether the type is an integer type or not.
  32347. */
  32348. isInteger( type ) {
  32349. return /int|uint|(i|u)vec/.test( type );
  32350. }
  32351. /**
  32352. * Returns the type for a given buffer attribute.
  32353. *
  32354. * @param {BufferAttribute} attribute - The buffer attribute.
  32355. * @return {string} The type.
  32356. */
  32357. getTypeFromAttribute( attribute ) {
  32358. let dataAttribute = attribute;
  32359. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  32360. const array = dataAttribute.array;
  32361. const itemSize = attribute.itemSize;
  32362. const normalized = attribute.normalized;
  32363. let arrayType;
  32364. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  32365. arrayType = this.getTypeFromArray( array );
  32366. }
  32367. return this.getTypeFromLength( itemSize, arrayType );
  32368. }
  32369. /**
  32370. * Returns the length for the given data type.
  32371. *
  32372. * @param {string} type - The data type.
  32373. * @return {number} The length.
  32374. */
  32375. getTypeLength( type ) {
  32376. const vecType = this.getVectorType( type );
  32377. const vecNum = /vec([2-4])/.exec( vecType );
  32378. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  32379. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  32380. if ( /mat2/.test( type ) === true ) return 4;
  32381. if ( /mat3/.test( type ) === true ) return 9;
  32382. if ( /mat4/.test( type ) === true ) return 16;
  32383. return 0;
  32384. }
  32385. /**
  32386. * Returns the vector type for a given matrix type.
  32387. *
  32388. * @param {string} type - The matrix type.
  32389. * @return {string} The vector type.
  32390. */
  32391. getVectorFromMatrix( type ) {
  32392. return type.replace( 'mat', 'vec' );
  32393. }
  32394. /**
  32395. * For a given type this method changes the component type to the
  32396. * given value. E.g. `vec4` should be changed to the new component type
  32397. * `uint` which results in `uvec4`.
  32398. *
  32399. * @param {string} type - The type.
  32400. * @param {string} newComponentType - The new component type.
  32401. * @return {string} The new type.
  32402. */
  32403. changeComponentType( type, newComponentType ) {
  32404. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  32405. }
  32406. /**
  32407. * Returns the integer type pendant for the given type.
  32408. *
  32409. * @param {string} type - The type.
  32410. * @return {string} The integer type.
  32411. */
  32412. getIntegerType( type ) {
  32413. const componentType = this.getComponentType( type );
  32414. if ( componentType === 'int' || componentType === 'uint' ) return type;
  32415. return this.changeComponentType( type, 'int' );
  32416. }
  32417. /**
  32418. * Adds a stack node to the internal stack.
  32419. *
  32420. * @return {StackNode} The added stack node.
  32421. */
  32422. addStack() {
  32423. this.stack = stack( this.stack );
  32424. this.stacks.push( getCurrentStack() || this.stack );
  32425. setCurrentStack( this.stack );
  32426. return this.stack;
  32427. }
  32428. /**
  32429. * Removes the last stack node from the internal stack.
  32430. *
  32431. * @return {StackNode} The removed stack node.
  32432. */
  32433. removeStack() {
  32434. const lastStack = this.stack;
  32435. this.stack = lastStack.parent;
  32436. setCurrentStack( this.stacks.pop() );
  32437. return lastStack;
  32438. }
  32439. /**
  32440. * The builder maintains (cached) data for each node during the building process. This method
  32441. * can be used to get these data for a specific shader stage and cache.
  32442. *
  32443. * @param {Node} node - The node to get the data for.
  32444. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32445. * @param {?NodeCache} cache - An optional cache.
  32446. * @return {Object} The node data.
  32447. */
  32448. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  32449. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  32450. let nodeData = cache.getData( node );
  32451. if ( nodeData === undefined ) {
  32452. nodeData = {};
  32453. cache.setData( node, nodeData );
  32454. }
  32455. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  32456. return nodeData[ shaderStage ];
  32457. }
  32458. /**
  32459. * Returns the properties for the given node and shader stage.
  32460. *
  32461. * @param {Node} node - The node to get the properties for.
  32462. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  32463. * @return {Object} The node properties.
  32464. */
  32465. getNodeProperties( node, shaderStage = 'any' ) {
  32466. const nodeData = this.getDataFromNode( node, shaderStage );
  32467. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  32468. }
  32469. /**
  32470. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  32471. *
  32472. * @param {BufferAttributeNode} node - The buffer attribute node.
  32473. * @param {string} type - The node type.
  32474. * @return {NodeAttribute} The node attribute.
  32475. */
  32476. getBufferAttributeFromNode( node, type ) {
  32477. const nodeData = this.getDataFromNode( node );
  32478. let bufferAttribute = nodeData.bufferAttribute;
  32479. if ( bufferAttribute === undefined ) {
  32480. const index = this.uniforms.index ++;
  32481. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  32482. this.bufferAttributes.push( bufferAttribute );
  32483. nodeData.bufferAttribute = bufferAttribute;
  32484. }
  32485. return bufferAttribute;
  32486. }
  32487. /**
  32488. * Returns an instance of {@link StructType} for the given output struct node.
  32489. *
  32490. * @param {OutputStructNode} node - The output struct node.
  32491. * @param {Array<Object>} membersLayout - The output struct types.
  32492. * @param {?string} [name=null] - The name of the struct.
  32493. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32494. * @return {StructType} The struct type attribute.
  32495. */
  32496. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  32497. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32498. let structType = nodeData.structType;
  32499. if ( structType === undefined ) {
  32500. const index = this.structs.index ++;
  32501. if ( name === null ) name = 'StructType' + index;
  32502. structType = new StructType( name, membersLayout );
  32503. this.structs[ shaderStage ].push( structType );
  32504. nodeData.structType = structType;
  32505. }
  32506. return structType;
  32507. }
  32508. /**
  32509. * Returns an instance of {@link StructType} for the given output struct node.
  32510. *
  32511. * @param {OutputStructNode} node - The output struct node.
  32512. * @param {Array<Object>} membersLayout - The output struct types.
  32513. * @return {StructType} The struct type attribute.
  32514. */
  32515. getOutputStructTypeFromNode( node, membersLayout ) {
  32516. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  32517. structType.output = true;
  32518. return structType;
  32519. }
  32520. /**
  32521. * Returns an instance of {@link NodeUniform} for the given uniform node.
  32522. *
  32523. * @param {UniformNode} node - The uniform node.
  32524. * @param {string} type - The uniform type.
  32525. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32526. * @param {?string} name - The name of the uniform.
  32527. * @return {NodeUniform} The node uniform.
  32528. */
  32529. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  32530. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32531. let nodeUniform = nodeData.uniform;
  32532. if ( nodeUniform === undefined ) {
  32533. const index = this.uniforms.index ++;
  32534. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  32535. this.uniforms[ shaderStage ].push( nodeUniform );
  32536. this.registerDeclaration( nodeUniform );
  32537. nodeData.uniform = nodeUniform;
  32538. }
  32539. return nodeUniform;
  32540. }
  32541. /**
  32542. * Returns the array length.
  32543. *
  32544. * @param {Node} node - The node.
  32545. * @return {?number} The array length.
  32546. */
  32547. getArrayCount( node ) {
  32548. let count = null;
  32549. if ( node.isArrayNode ) count = node.count;
  32550. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  32551. return count;
  32552. }
  32553. /**
  32554. * Returns an instance of {@link NodeVar} for the given variable node.
  32555. *
  32556. * @param {VarNode} node - The variable node.
  32557. * @param {?string} name - The variable's name.
  32558. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  32559. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32560. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  32561. *
  32562. * @return {NodeVar} The node variable.
  32563. */
  32564. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  32565. const nodeData = this.getDataFromNode( node, shaderStage );
  32566. let nodeVar = nodeData.variable;
  32567. if ( nodeVar === undefined ) {
  32568. const idNS = readOnly ? '_const' : '_var';
  32569. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  32570. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  32571. if ( name === null ) {
  32572. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  32573. this.vars[ idNS ] ++;
  32574. }
  32575. //
  32576. const count = this.getArrayCount( node );
  32577. nodeVar = new NodeVar( name, type, readOnly, count );
  32578. if ( ! readOnly ) {
  32579. vars.push( nodeVar );
  32580. }
  32581. this.registerDeclaration( nodeVar );
  32582. nodeData.variable = nodeVar;
  32583. }
  32584. return nodeVar;
  32585. }
  32586. /**
  32587. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  32588. *
  32589. * @param {Node} node - The varying node.
  32590. * @return {boolean} Returns true if deterministic.
  32591. */
  32592. isDeterministic( node ) {
  32593. if ( node.isMathNode ) {
  32594. return this.isDeterministic( node.aNode ) &&
  32595. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  32596. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  32597. } else if ( node.isOperatorNode ) {
  32598. return this.isDeterministic( node.aNode ) &&
  32599. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  32600. } else if ( node.isArrayNode ) {
  32601. if ( node.values !== null ) {
  32602. for ( const n of node.values ) {
  32603. if ( ! this.isDeterministic( n ) ) {
  32604. return false;
  32605. }
  32606. }
  32607. }
  32608. return true;
  32609. } else if ( node.isConstNode ) {
  32610. return true;
  32611. }
  32612. return false;
  32613. }
  32614. /**
  32615. * Returns an instance of {@link NodeVarying} for the given varying node.
  32616. *
  32617. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  32618. * @param {?string} name - The varying's name.
  32619. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  32620. * @param {?string} interpolationType - The interpolation type of the varying.
  32621. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32622. * @return {NodeVar} The node varying.
  32623. */
  32624. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  32625. const nodeData = this.getDataFromNode( node, 'any' );
  32626. let nodeVarying = nodeData.varying;
  32627. if ( nodeVarying === undefined ) {
  32628. const varyings = this.varyings;
  32629. const index = varyings.length;
  32630. if ( name === null ) name = 'nodeVarying' + index;
  32631. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  32632. varyings.push( nodeVarying );
  32633. this.registerDeclaration( nodeVarying );
  32634. nodeData.varying = nodeVarying;
  32635. }
  32636. return nodeVarying;
  32637. }
  32638. /**
  32639. * Registers a node declaration in the current shader stage.
  32640. *
  32641. * @param {Object} node - The node to be registered.
  32642. */
  32643. registerDeclaration( node ) {
  32644. const shaderStage = this.shaderStage;
  32645. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  32646. const property = this.getPropertyName( node );
  32647. let index = 1;
  32648. let name = property;
  32649. // Automatically renames the property if the name is already in use.
  32650. while ( declarations[ name ] !== undefined ) {
  32651. name = property + '_' + index ++;
  32652. }
  32653. if ( index > 1 ) {
  32654. node.name = name;
  32655. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  32656. }
  32657. declarations[ name ] = node;
  32658. }
  32659. /**
  32660. * Returns an instance of {@link NodeCode} for the given code node.
  32661. *
  32662. * @param {CodeNode} node - The code node.
  32663. * @param {string} type - The node type.
  32664. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32665. * @return {NodeCode} The node code.
  32666. */
  32667. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  32668. const nodeData = this.getDataFromNode( node );
  32669. let nodeCode = nodeData.code;
  32670. if ( nodeCode === undefined ) {
  32671. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  32672. const index = codes.length;
  32673. nodeCode = new NodeCode( 'nodeCode' + index, type );
  32674. codes.push( nodeCode );
  32675. nodeData.code = nodeCode;
  32676. }
  32677. return nodeCode;
  32678. }
  32679. /**
  32680. * Adds a code flow based on the code-block hierarchy.
  32681. * This is used so that code-blocks like If,Else create their variables locally if the Node
  32682. * is only used inside one of these conditionals in the current shader stage.
  32683. *
  32684. * @param {Node} node - The node to add.
  32685. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  32686. */
  32687. addFlowCodeHierarchy( node, nodeBlock ) {
  32688. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  32689. let needsFlowCode = true;
  32690. let nodeBlockHierarchy = nodeBlock;
  32691. while ( nodeBlockHierarchy ) {
  32692. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  32693. needsFlowCode = false;
  32694. break;
  32695. }
  32696. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  32697. }
  32698. if ( needsFlowCode ) {
  32699. for ( const flowCode of flowCodes ) {
  32700. this.addLineFlowCode( flowCode );
  32701. }
  32702. }
  32703. }
  32704. /**
  32705. * Add a inline-code to the current flow code-block.
  32706. *
  32707. * @param {Node} node - The node to add.
  32708. * @param {string} code - The code to add.
  32709. * @param {Node} nodeBlock - Current ConditionalNode
  32710. */
  32711. addLineFlowCodeBlock( node, code, nodeBlock ) {
  32712. const nodeData = this.getDataFromNode( node );
  32713. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  32714. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  32715. flowCodes.push( code );
  32716. codeBlock.set( nodeBlock, true );
  32717. }
  32718. /**
  32719. * Add a inline-code to the current flow.
  32720. *
  32721. * @param {string} code - The code to add.
  32722. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  32723. * @return {NodeBuilder} A reference to this node builder.
  32724. */
  32725. addLineFlowCode( code, node = null ) {
  32726. if ( code === '' ) return this;
  32727. if ( node !== null && this.context.nodeBlock ) {
  32728. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  32729. }
  32730. code = this.tab + code;
  32731. if ( ! /;\s*$/.test( code ) ) {
  32732. code = code + ';\n';
  32733. }
  32734. this.flow.code += code;
  32735. return this;
  32736. }
  32737. /**
  32738. * Adds a code to the current code flow.
  32739. *
  32740. * @param {string} code - Shader code.
  32741. * @return {NodeBuilder} A reference to this node builder.
  32742. */
  32743. addFlowCode( code ) {
  32744. this.flow.code += code;
  32745. return this;
  32746. }
  32747. /**
  32748. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  32749. * Typically used in codes with If,Else.
  32750. *
  32751. * @return {NodeBuilder} A reference to this node builder.
  32752. */
  32753. addFlowTab() {
  32754. this.tab += '\t';
  32755. return this;
  32756. }
  32757. /**
  32758. * Removes a tab.
  32759. *
  32760. * @return {NodeBuilder} A reference to this node builder.
  32761. */
  32762. removeFlowTab() {
  32763. this.tab = this.tab.slice( 0, -1 );
  32764. return this;
  32765. }
  32766. /**
  32767. * Gets the current flow data based on a Node.
  32768. *
  32769. * @param {Node} node - Node that the flow was started.
  32770. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32771. * @return {Object} The flow data.
  32772. */
  32773. getFlowData( node/*, shaderStage*/ ) {
  32774. return this.flowsData.get( node );
  32775. }
  32776. /**
  32777. * Executes the node flow based on a root node to generate the final shader code.
  32778. *
  32779. * @param {Node} node - The node to execute.
  32780. * @return {Object} The code flow.
  32781. */
  32782. flowNode( node ) {
  32783. const output = node.getNodeType( this );
  32784. const flowData = this.flowChildNode( node, output );
  32785. this.flowsData.set( node, flowData );
  32786. return flowData;
  32787. }
  32788. /**
  32789. * Includes a node in the current function node.
  32790. *
  32791. * @param {Node} node - The node to include.
  32792. * @returns {void}
  32793. */
  32794. addInclude( node ) {
  32795. if ( this.currentFunctionNode !== null ) {
  32796. this.currentFunctionNode.includes.push( node );
  32797. }
  32798. }
  32799. /**
  32800. * Returns the native shader operator name for a given generic name.
  32801. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  32802. *
  32803. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  32804. * @return {FunctionNode} The build function node.
  32805. */
  32806. buildFunctionNode( shaderNode ) {
  32807. const fn = new FunctionNode();
  32808. const previous = this.currentFunctionNode;
  32809. this.currentFunctionNode = fn;
  32810. fn.code = this.buildFunctionCode( shaderNode );
  32811. this.currentFunctionNode = previous;
  32812. return fn;
  32813. }
  32814. /**
  32815. * Generates a code flow based on a TSL function: Fn().
  32816. *
  32817. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  32818. * @return {Object}
  32819. */
  32820. flowShaderNode( shaderNode ) {
  32821. const layout = shaderNode.layout;
  32822. const inputs = {
  32823. [ Symbol.iterator ]() {
  32824. let index = 0;
  32825. const values = Object.values( this );
  32826. return {
  32827. next: () => ( {
  32828. value: values[ index ],
  32829. done: index ++ >= values.length
  32830. } )
  32831. };
  32832. }
  32833. };
  32834. for ( const input of layout.inputs ) {
  32835. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  32836. }
  32837. //
  32838. shaderNode.layout = null;
  32839. const callNode = shaderNode.call( inputs );
  32840. const flowData = this.flowStagesNode( callNode, layout.type );
  32841. shaderNode.layout = layout;
  32842. return flowData;
  32843. }
  32844. /**
  32845. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  32846. *
  32847. * @param {Node} node - The node to execute.
  32848. * @param {?string} output - Expected output type. For example 'vec3'.
  32849. * @return {Object}
  32850. */
  32851. flowStagesNode( node, output = null ) {
  32852. const previousFlow = this.flow;
  32853. const previousVars = this.vars;
  32854. const previousDeclarations = this.declarations;
  32855. const previousCache = this.cache;
  32856. const previousBuildStage = this.buildStage;
  32857. const previousStack = this.stack;
  32858. const flow = {
  32859. code: ''
  32860. };
  32861. this.flow = flow;
  32862. this.vars = {};
  32863. this.declarations = {};
  32864. this.cache = new NodeCache();
  32865. this.stack = stack();
  32866. for ( const buildStage of defaultBuildStages ) {
  32867. this.setBuildStage( buildStage );
  32868. flow.result = node.build( this, output );
  32869. }
  32870. flow.vars = this.getVars( this.shaderStage );
  32871. this.flow = previousFlow;
  32872. this.vars = previousVars;
  32873. this.declarations = previousDeclarations;
  32874. this.cache = previousCache;
  32875. this.stack = previousStack;
  32876. this.setBuildStage( previousBuildStage );
  32877. return flow;
  32878. }
  32879. /**
  32880. * Returns the native shader operator name for a given generic name.
  32881. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  32882. *
  32883. * @abstract
  32884. * @param {string} op - The operator name to resolve.
  32885. * @return {?string} The resolved operator name.
  32886. */
  32887. getFunctionOperator( /* op */ ) {
  32888. return null;
  32889. }
  32890. /**
  32891. * Builds the given shader node.
  32892. *
  32893. * @abstract
  32894. * @param {ShaderNodeInternal} shaderNode - The shader node.
  32895. * @return {string} The function code.
  32896. */
  32897. buildFunctionCode( /* shaderNode */ ) {
  32898. console.warn( 'Abstract function.' );
  32899. }
  32900. /**
  32901. * Generates a code flow based on a child Node.
  32902. *
  32903. * @param {Node} node - The node to execute.
  32904. * @param {?string} output - Expected output type. For example 'vec3'.
  32905. * @return {Object} The code flow.
  32906. */
  32907. flowChildNode( node, output = null ) {
  32908. const previousFlow = this.flow;
  32909. const flow = {
  32910. code: ''
  32911. };
  32912. this.flow = flow;
  32913. flow.result = node.build( this, output );
  32914. this.flow = previousFlow;
  32915. return flow;
  32916. }
  32917. /**
  32918. * Executes a flow of code in a different stage.
  32919. *
  32920. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  32921. * return the value in fragment-stage even if it is being executed in an input fragment.
  32922. *
  32923. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32924. * @param {Node} node - The node to execute.
  32925. * @param {?string} output - Expected output type. For example 'vec3'.
  32926. * @param {?string} propertyName - The property name to assign the result.
  32927. * @return {Object}
  32928. */
  32929. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  32930. const previousShaderStage = this.shaderStage;
  32931. this.setShaderStage( shaderStage );
  32932. const flowData = this.flowChildNode( node, output );
  32933. if ( propertyName !== null ) {
  32934. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  32935. }
  32936. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  32937. this.setShaderStage( previousShaderStage );
  32938. return flowData;
  32939. }
  32940. /**
  32941. * Returns an array holding all node attributes of this node builder.
  32942. *
  32943. * @return {Array<NodeAttribute>} The node attributes of this builder.
  32944. */
  32945. getAttributesArray() {
  32946. return this.attributes.concat( this.bufferAttributes );
  32947. }
  32948. /**
  32949. * Returns the attribute definitions as a shader string for the given shader stage.
  32950. *
  32951. * @abstract
  32952. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32953. * @return {string} The attribute code section.
  32954. */
  32955. getAttributes( /*shaderStage*/ ) {
  32956. console.warn( 'Abstract function.' );
  32957. }
  32958. /**
  32959. * Returns the varying definitions as a shader string for the given shader stage.
  32960. *
  32961. * @abstract
  32962. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32963. * @return {string} The varying code section.
  32964. */
  32965. getVaryings( /*shaderStage*/ ) {
  32966. console.warn( 'Abstract function.' );
  32967. }
  32968. /**
  32969. * Returns a single variable definition as a shader string for the given variable type and name.
  32970. *
  32971. * @param {string} type - The variable's type.
  32972. * @param {string} name - The variable's name.
  32973. * @param {?number} [count=null] - The array length.
  32974. * @return {string} The shader string.
  32975. */
  32976. getVar( type, name, count = null ) {
  32977. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  32978. }
  32979. /**
  32980. * Returns the variable definitions as a shader string for the given shader stage.
  32981. *
  32982. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32983. * @return {string} The variable code section.
  32984. */
  32985. getVars( shaderStage ) {
  32986. let snippet = '';
  32987. const vars = this.vars[ shaderStage ];
  32988. if ( vars !== undefined ) {
  32989. for ( const variable of vars ) {
  32990. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  32991. }
  32992. }
  32993. return snippet;
  32994. }
  32995. /**
  32996. * Returns the uniform definitions as a shader string for the given shader stage.
  32997. *
  32998. * @abstract
  32999. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33000. * @return {string} The uniform code section.
  33001. */
  33002. getUniforms( /*shaderStage*/ ) {
  33003. console.warn( 'Abstract function.' );
  33004. }
  33005. /**
  33006. * Returns the native code definitions as a shader string for the given shader stage.
  33007. *
  33008. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33009. * @return {string} The native code section.
  33010. */
  33011. getCodes( shaderStage ) {
  33012. const codes = this.codes[ shaderStage ];
  33013. let code = '';
  33014. if ( codes !== undefined ) {
  33015. for ( const nodeCode of codes ) {
  33016. code += nodeCode.code + '\n';
  33017. }
  33018. }
  33019. return code;
  33020. }
  33021. /**
  33022. * Returns the hash of this node builder.
  33023. *
  33024. * @return {string} The hash.
  33025. */
  33026. getHash() {
  33027. return this.vertexShader + this.fragmentShader + this.computeShader;
  33028. }
  33029. /**
  33030. * Sets the current shader stage.
  33031. *
  33032. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  33033. */
  33034. setShaderStage( shaderStage ) {
  33035. this.shaderStage = shaderStage;
  33036. }
  33037. /**
  33038. * Returns the current shader stage.
  33039. *
  33040. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  33041. */
  33042. getShaderStage() {
  33043. return this.shaderStage;
  33044. }
  33045. /**
  33046. * Sets the current build stage.
  33047. *
  33048. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  33049. */
  33050. setBuildStage( buildStage ) {
  33051. this.buildStage = buildStage;
  33052. }
  33053. /**
  33054. * Returns the current build stage.
  33055. *
  33056. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  33057. */
  33058. getBuildStage() {
  33059. return this.buildStage;
  33060. }
  33061. /**
  33062. * Controls the code build of the shader stages.
  33063. *
  33064. * @abstract
  33065. */
  33066. buildCode() {
  33067. console.warn( 'Abstract function.' );
  33068. }
  33069. /**
  33070. * Central build method which controls the build for the given object.
  33071. *
  33072. * @return {NodeBuilder} A reference to this node builder.
  33073. */
  33074. build() {
  33075. const { object, material, renderer } = this;
  33076. if ( material !== null ) {
  33077. let nodeMaterial = renderer.library.fromMaterial( material );
  33078. if ( nodeMaterial === null ) {
  33079. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  33080. nodeMaterial = new NodeMaterial();
  33081. }
  33082. nodeMaterial.build( this );
  33083. } else {
  33084. this.addFlow( 'compute', object );
  33085. }
  33086. // setup() -> stage 1: create possible new nodes and returns an output reference node
  33087. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  33088. // generate() -> stage 3: generate shader
  33089. for ( const buildStage of defaultBuildStages ) {
  33090. this.setBuildStage( buildStage );
  33091. if ( this.context.vertex && this.context.vertex.isNode ) {
  33092. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  33093. }
  33094. for ( const shaderStage of shaderStages ) {
  33095. this.setShaderStage( shaderStage );
  33096. const flowNodes = this.flowNodes[ shaderStage ];
  33097. for ( const node of flowNodes ) {
  33098. if ( buildStage === 'generate' ) {
  33099. this.flowNode( node );
  33100. } else {
  33101. node.build( this );
  33102. }
  33103. }
  33104. }
  33105. }
  33106. this.setBuildStage( null );
  33107. this.setShaderStage( null );
  33108. // stage 4: build code for a specific output
  33109. this.buildCode();
  33110. this.buildUpdateNodes();
  33111. return this;
  33112. }
  33113. /**
  33114. * Returns a uniform representation which is later used for UBO generation and rendering.
  33115. *
  33116. * @param {NodeUniform} uniformNode - The uniform node.
  33117. * @param {string} type - The requested type.
  33118. * @return {Uniform} The uniform.
  33119. */
  33120. getNodeUniform( uniformNode, type ) {
  33121. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  33122. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  33123. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  33124. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  33125. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  33126. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  33127. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  33128. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  33129. throw new Error( `Uniform "${type}" not declared.` );
  33130. }
  33131. /**
  33132. * Formats the given shader snippet from a given type into another one. E.g.
  33133. * this method might be used to convert a simple float string `"1.0"` into a
  33134. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  33135. *
  33136. * @param {string} snippet - The shader snippet.
  33137. * @param {string} fromType - The source type.
  33138. * @param {string} toType - The target type.
  33139. * @return {string} The updated shader string.
  33140. */
  33141. format( snippet, fromType, toType ) {
  33142. fromType = this.getVectorType( fromType );
  33143. toType = this.getVectorType( toType );
  33144. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  33145. return snippet;
  33146. }
  33147. const fromTypeLength = this.getTypeLength( fromType );
  33148. const toTypeLength = this.getTypeLength( toType );
  33149. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  33150. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  33151. }
  33152. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  33153. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  33154. }
  33155. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  33156. // @TODO: ignore for now
  33157. return snippet;
  33158. }
  33159. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  33160. // @TODO: ignore for now
  33161. return snippet;
  33162. }
  33163. if ( fromTypeLength === toTypeLength ) {
  33164. return `${ this.getType( toType ) }( ${ snippet } )`;
  33165. }
  33166. if ( fromTypeLength > toTypeLength ) {
  33167. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  33168. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  33169. }
  33170. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  33171. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  33172. }
  33173. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  33174. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  33175. }
  33176. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  33177. // convert a number value to vector type, e.g:
  33178. // vec3( 1u ) -> vec3( float( 1u ) )
  33179. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  33180. }
  33181. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  33182. }
  33183. /**
  33184. * Returns a signature with the engine's current revision.
  33185. *
  33186. * @return {string} The signature.
  33187. */
  33188. getSignature() {
  33189. return `// Three.js r${ REVISION } - Node System\n`;
  33190. }
  33191. /**
  33192. * Prevents the node builder from being used as an iterable in TSL.Fn(), avoiding potential runtime errors.
  33193. */
  33194. *[ Symbol.iterator ]() { }
  33195. // Deprecated
  33196. /**
  33197. * @function
  33198. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  33199. *
  33200. * @param {string} [type='NodeMaterial'] - The node material type.
  33201. * @throws {Error}
  33202. */
  33203. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  33204. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  33205. }
  33206. }
  33207. /**
  33208. * Management class for updating nodes. The module tracks metrics like
  33209. * the elapsed time, delta time, the render and frame ID to correctly
  33210. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  33211. * and {@link Node#updateAfter} depending on the node's configuration.
  33212. */
  33213. class NodeFrame {
  33214. /**
  33215. * Constructs a new node fame.
  33216. */
  33217. constructor() {
  33218. /**
  33219. * The elapsed time in seconds.
  33220. *
  33221. * @type {number}
  33222. * @default 0
  33223. */
  33224. this.time = 0;
  33225. /**
  33226. * The delta time in seconds.
  33227. *
  33228. * @type {number}
  33229. * @default 0
  33230. */
  33231. this.deltaTime = 0;
  33232. /**
  33233. * The frame ID.
  33234. *
  33235. * @type {number}
  33236. * @default 0
  33237. */
  33238. this.frameId = 0;
  33239. /**
  33240. * The render ID.
  33241. *
  33242. * @type {number}
  33243. * @default 0
  33244. */
  33245. this.renderId = 0;
  33246. /**
  33247. * Used to control the {@link Node#update} call.
  33248. *
  33249. * @type {WeakMap<Node, Object>}
  33250. */
  33251. this.updateMap = new WeakMap();
  33252. /**
  33253. * Used to control the {@link Node#updateBefore} call.
  33254. *
  33255. * @type {WeakMap<Node, Object>}
  33256. */
  33257. this.updateBeforeMap = new WeakMap();
  33258. /**
  33259. * Used to control the {@link Node#updateAfter} call.
  33260. *
  33261. * @type {WeakMap<Node, Object>}
  33262. */
  33263. this.updateAfterMap = new WeakMap();
  33264. /**
  33265. * A reference to the current renderer.
  33266. *
  33267. * @type {?Renderer}
  33268. * @default null
  33269. */
  33270. this.renderer = null;
  33271. /**
  33272. * A reference to the current material.
  33273. *
  33274. * @type {?Material}
  33275. * @default null
  33276. */
  33277. this.material = null;
  33278. /**
  33279. * A reference to the current camera.
  33280. *
  33281. * @type {?Camera}
  33282. * @default null
  33283. */
  33284. this.camera = null;
  33285. /**
  33286. * A reference to the current 3D object.
  33287. *
  33288. * @type {?Object3D}
  33289. * @default null
  33290. */
  33291. this.object = null;
  33292. /**
  33293. * A reference to the current scene.
  33294. *
  33295. * @type {?Scene}
  33296. * @default null
  33297. */
  33298. this.scene = null;
  33299. }
  33300. /**
  33301. * Returns a dictionary for a given node and update map which
  33302. * is used to correctly call node update methods per frame or render.
  33303. *
  33304. * @private
  33305. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  33306. * @param {Node} nodeRef - The reference to the current node.
  33307. * @return {Object<string,WeakMap>} The dictionary.
  33308. */
  33309. _getMaps( referenceMap, nodeRef ) {
  33310. let maps = referenceMap.get( nodeRef );
  33311. if ( maps === undefined ) {
  33312. maps = {
  33313. renderMap: new WeakMap(),
  33314. frameMap: new WeakMap()
  33315. };
  33316. referenceMap.set( nodeRef, maps );
  33317. }
  33318. return maps;
  33319. }
  33320. /**
  33321. * This method executes the {@link Node#updateBefore} for the given node.
  33322. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  33323. * is only executed once per frame, render or object depending on the update
  33324. * type.
  33325. *
  33326. * @param {Node} node - The node that should be updated.
  33327. */
  33328. updateBeforeNode( node ) {
  33329. const updateType = node.getUpdateBeforeType();
  33330. const reference = node.updateReference( this );
  33331. if ( updateType === NodeUpdateType.FRAME ) {
  33332. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  33333. if ( frameMap.get( reference ) !== this.frameId ) {
  33334. if ( node.updateBefore( this ) !== false ) {
  33335. frameMap.set( reference, this.frameId );
  33336. }
  33337. }
  33338. } else if ( updateType === NodeUpdateType.RENDER ) {
  33339. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  33340. if ( renderMap.get( reference ) !== this.renderId ) {
  33341. if ( node.updateBefore( this ) !== false ) {
  33342. renderMap.set( reference, this.renderId );
  33343. }
  33344. }
  33345. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33346. node.updateBefore( this );
  33347. }
  33348. }
  33349. /**
  33350. * This method executes the {@link Node#updateAfter} for the given node.
  33351. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  33352. * is only executed once per frame, render or object depending on the update
  33353. * type.
  33354. *
  33355. * @param {Node} node - The node that should be updated.
  33356. */
  33357. updateAfterNode( node ) {
  33358. const updateType = node.getUpdateAfterType();
  33359. const reference = node.updateReference( this );
  33360. if ( updateType === NodeUpdateType.FRAME ) {
  33361. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  33362. if ( frameMap.get( reference ) !== this.frameId ) {
  33363. if ( node.updateAfter( this ) !== false ) {
  33364. frameMap.set( reference, this.frameId );
  33365. }
  33366. }
  33367. } else if ( updateType === NodeUpdateType.RENDER ) {
  33368. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  33369. if ( renderMap.get( reference ) !== this.renderId ) {
  33370. if ( node.updateAfter( this ) !== false ) {
  33371. renderMap.set( reference, this.renderId );
  33372. }
  33373. }
  33374. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33375. node.updateAfter( this );
  33376. }
  33377. }
  33378. /**
  33379. * This method executes the {@link Node#update} for the given node.
  33380. * It makes sure {@link Node#updateType} is honored meaning the update
  33381. * is only executed once per frame, render or object depending on the update
  33382. * type.
  33383. *
  33384. * @param {Node} node - The node that should be updated.
  33385. */
  33386. updateNode( node ) {
  33387. const updateType = node.getUpdateType();
  33388. const reference = node.updateReference( this );
  33389. if ( updateType === NodeUpdateType.FRAME ) {
  33390. const { frameMap } = this._getMaps( this.updateMap, reference );
  33391. if ( frameMap.get( reference ) !== this.frameId ) {
  33392. if ( node.update( this ) !== false ) {
  33393. frameMap.set( reference, this.frameId );
  33394. }
  33395. }
  33396. } else if ( updateType === NodeUpdateType.RENDER ) {
  33397. const { renderMap } = this._getMaps( this.updateMap, reference );
  33398. if ( renderMap.get( reference ) !== this.renderId ) {
  33399. if ( node.update( this ) !== false ) {
  33400. renderMap.set( reference, this.renderId );
  33401. }
  33402. }
  33403. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33404. node.update( this );
  33405. }
  33406. }
  33407. /**
  33408. * Updates the internal state of the node frame. This method is
  33409. * called by the renderer in its internal animation loop.
  33410. */
  33411. update() {
  33412. this.frameId ++;
  33413. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  33414. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  33415. this.lastTime = performance.now();
  33416. this.time += this.deltaTime;
  33417. }
  33418. }
  33419. /**
  33420. * Describes the input of a {@link NodeFunction}.
  33421. */
  33422. class NodeFunctionInput {
  33423. /**
  33424. * Constructs a new node function input.
  33425. *
  33426. * @param {string} type - The input type.
  33427. * @param {string} name - The input name.
  33428. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  33429. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  33430. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  33431. */
  33432. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  33433. /**
  33434. * The input type.
  33435. *
  33436. * @type {string}
  33437. */
  33438. this.type = type;
  33439. /**
  33440. * The input name.
  33441. *
  33442. * @type {string}
  33443. */
  33444. this.name = name;
  33445. /**
  33446. * If the input is an Array, count will be the length.
  33447. *
  33448. * @type {?number}
  33449. * @default null
  33450. */
  33451. this.count = count;
  33452. /**
  33453. *The parameter qualifier (only relevant for GLSL).
  33454. *
  33455. * @type {('in'|'out'|'inout')}
  33456. * @default ''
  33457. */
  33458. this.qualifier = qualifier;
  33459. /**
  33460. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  33461. *
  33462. * @type {boolean}
  33463. * @default false
  33464. */
  33465. this.isConst = isConst;
  33466. }
  33467. }
  33468. NodeFunctionInput.isNodeFunctionInput = true;
  33469. /**
  33470. * Module for representing directional lights as nodes.
  33471. *
  33472. * @augments AnalyticLightNode
  33473. */
  33474. class DirectionalLightNode extends AnalyticLightNode {
  33475. static get type() {
  33476. return 'DirectionalLightNode';
  33477. }
  33478. /**
  33479. * Constructs a new directional light node.
  33480. *
  33481. * @param {?DirectionalLight} [light=null] - The directional light source.
  33482. */
  33483. constructor( light = null ) {
  33484. super( light );
  33485. }
  33486. setupDirect() {
  33487. const lightColor = this.colorNode;
  33488. const lightDirection = lightTargetDirection( this.light );
  33489. return { lightDirection, lightColor };
  33490. }
  33491. }
  33492. const _matrix41 = /*@__PURE__*/ new Matrix4();
  33493. const _matrix42 = /*@__PURE__*/ new Matrix4();
  33494. let _ltcLib = null;
  33495. /**
  33496. * Module for representing rect area lights as nodes.
  33497. *
  33498. * @augments AnalyticLightNode
  33499. */
  33500. class RectAreaLightNode extends AnalyticLightNode {
  33501. static get type() {
  33502. return 'RectAreaLightNode';
  33503. }
  33504. /**
  33505. * Constructs a new rect area light node.
  33506. *
  33507. * @param {?RectAreaLight} [light=null] - The rect area light source.
  33508. */
  33509. constructor( light = null ) {
  33510. super( light );
  33511. /**
  33512. * Uniform node representing the half height of the are light.
  33513. *
  33514. * @type {UniformNode<vec3>}
  33515. */
  33516. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  33517. /**
  33518. * Uniform node representing the half width of the are light.
  33519. *
  33520. * @type {UniformNode<vec3>}
  33521. */
  33522. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  33523. /**
  33524. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  33525. * relies on `viewMatrix` which might vary per render call.
  33526. *
  33527. * @type {string}
  33528. * @default 'render'
  33529. */
  33530. this.updateType = NodeUpdateType.RENDER;
  33531. }
  33532. /**
  33533. * Overwritten to updated rect area light specific uniforms.
  33534. *
  33535. * @param {NodeFrame} frame - A reference to the current node frame.
  33536. */
  33537. update( frame ) {
  33538. super.update( frame );
  33539. const { light } = this;
  33540. const viewMatrix = frame.camera.matrixWorldInverse;
  33541. _matrix42.identity();
  33542. _matrix41.copy( light.matrixWorld );
  33543. _matrix41.premultiply( viewMatrix );
  33544. _matrix42.extractRotation( _matrix41 );
  33545. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  33546. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  33547. this.halfWidth.value.applyMatrix4( _matrix42 );
  33548. this.halfHeight.value.applyMatrix4( _matrix42 );
  33549. }
  33550. setupDirectRectArea( builder ) {
  33551. let ltc_1, ltc_2;
  33552. if ( builder.isAvailable( 'float32Filterable' ) ) {
  33553. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  33554. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  33555. } else {
  33556. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  33557. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  33558. }
  33559. const { colorNode, light } = this;
  33560. const lightPosition = lightViewPosition( light );
  33561. return {
  33562. lightColor: colorNode,
  33563. lightPosition,
  33564. halfWidth: this.halfWidth,
  33565. halfHeight: this.halfHeight,
  33566. ltc_1,
  33567. ltc_2
  33568. };
  33569. }
  33570. /**
  33571. * Used to configure the internal BRDF approximation texture data.
  33572. *
  33573. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  33574. */
  33575. static setLTC( ltc ) {
  33576. _ltcLib = ltc;
  33577. }
  33578. }
  33579. /**
  33580. * Module for representing spot lights as nodes.
  33581. *
  33582. * @augments AnalyticLightNode
  33583. */
  33584. class SpotLightNode extends AnalyticLightNode {
  33585. static get type() {
  33586. return 'SpotLightNode';
  33587. }
  33588. /**
  33589. * Constructs a new spot light node.
  33590. *
  33591. * @param {?SpotLight} [light=null] - The spot light source.
  33592. */
  33593. constructor( light = null ) {
  33594. super( light );
  33595. /**
  33596. * Uniform node representing the cone cosine.
  33597. *
  33598. * @type {UniformNode<float>}
  33599. */
  33600. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  33601. /**
  33602. * Uniform node representing the penumbra cosine.
  33603. *
  33604. * @type {UniformNode<float>}
  33605. */
  33606. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  33607. /**
  33608. * Uniform node representing the cutoff distance.
  33609. *
  33610. * @type {UniformNode<float>}
  33611. */
  33612. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  33613. /**
  33614. * Uniform node representing the decay exponent.
  33615. *
  33616. * @type {UniformNode<float>}
  33617. */
  33618. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  33619. /**
  33620. * Uniform node representing the light color.
  33621. *
  33622. * @type {UniformNode<Color>}
  33623. */
  33624. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  33625. }
  33626. /**
  33627. * Overwritten to updated spot light specific uniforms.
  33628. *
  33629. * @param {NodeFrame} frame - A reference to the current node frame.
  33630. */
  33631. update( frame ) {
  33632. super.update( frame );
  33633. const { light } = this;
  33634. this.coneCosNode.value = Math.cos( light.angle );
  33635. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  33636. this.cutoffDistanceNode.value = light.distance;
  33637. this.decayExponentNode.value = light.decay;
  33638. }
  33639. /**
  33640. * Computes the spot attenuation for the given angle.
  33641. *
  33642. * @param {NodeBuilder} builder - The node builder.
  33643. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  33644. * @return {Node<float>} The spot attenuation.
  33645. */
  33646. getSpotAttenuation( builder, angleCosine ) {
  33647. const { coneCosNode, penumbraCosNode } = this;
  33648. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  33649. }
  33650. getLightCoord( builder ) {
  33651. const properties = builder.getNodeProperties( this );
  33652. let projectionUV = properties.projectionUV;
  33653. if ( projectionUV === undefined ) {
  33654. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  33655. properties.projectionUV = projectionUV;
  33656. }
  33657. return projectionUV;
  33658. }
  33659. setupDirect( builder ) {
  33660. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  33661. const lightVector = this.getLightVector( builder );
  33662. const lightDirection = lightVector.normalize();
  33663. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  33664. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  33665. const lightDistance = lightVector.length();
  33666. const lightAttenuation = getDistanceAttenuation( {
  33667. lightDistance,
  33668. cutoffDistance: cutoffDistanceNode,
  33669. decayExponent: decayExponentNode
  33670. } );
  33671. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  33672. let projected, lightCoord;
  33673. if ( light.colorNode ) {
  33674. lightCoord = this.getLightCoord( builder );
  33675. projected = light.colorNode( lightCoord );
  33676. } else if ( light.map ) {
  33677. lightCoord = this.getLightCoord( builder );
  33678. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  33679. }
  33680. if ( projected ) {
  33681. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  33682. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  33683. }
  33684. return { lightColor, lightDirection };
  33685. }
  33686. }
  33687. /**
  33688. * An IES version of the default spot light node.
  33689. *
  33690. * @augments SpotLightNode
  33691. */
  33692. class IESSpotLightNode extends SpotLightNode {
  33693. static get type() {
  33694. return 'IESSpotLightNode';
  33695. }
  33696. /**
  33697. * Overwrites the default implementation to compute an IES conform spot attenuation.
  33698. *
  33699. * @param {NodeBuilder} builder - The node builder.
  33700. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  33701. * @return {Node<float>} The spot attenuation.
  33702. */
  33703. getSpotAttenuation( builder, angleCosine ) {
  33704. const iesMap = this.light.iesMap;
  33705. let spotAttenuation = null;
  33706. if ( iesMap && iesMap.isTexture === true ) {
  33707. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  33708. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  33709. } else {
  33710. spotAttenuation = super.getSpotAttenuation( angleCosine );
  33711. }
  33712. return spotAttenuation;
  33713. }
  33714. }
  33715. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  33716. const d = p.abs().sub( b );
  33717. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  33718. } );
  33719. /**
  33720. * An implementation of a projector light node.
  33721. *
  33722. * @augments SpotLightNode
  33723. */
  33724. class ProjectorLightNode extends SpotLightNode {
  33725. static get type() {
  33726. return 'ProjectorLightNode';
  33727. }
  33728. update( frame ) {
  33729. super.update( frame );
  33730. const light = this.light;
  33731. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  33732. if ( light.aspect === null ) {
  33733. let aspect = 1;
  33734. if ( light.map !== null ) {
  33735. aspect = light.map.width / light.map.height;
  33736. }
  33737. light.shadow.aspect = aspect;
  33738. } else {
  33739. light.shadow.aspect = light.aspect;
  33740. }
  33741. }
  33742. /**
  33743. * Overwrites the default implementation to compute projection attenuation.
  33744. *
  33745. * @param {NodeBuilder} builder - The node builder.
  33746. * @return {Node<float>} The spot attenuation.
  33747. */
  33748. getSpotAttenuation( builder ) {
  33749. const penumbraCos = this.penumbraCosNode;
  33750. const spotLightCoord = this.getLightCoord( builder );
  33751. const coord = spotLightCoord.xyz.div( spotLightCoord.w );
  33752. const boxDist = sdBox( coord.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  33753. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  33754. const attenuation = saturate( boxDist.mul( -2 ).mul( angleFactor ) );
  33755. return attenuation;
  33756. }
  33757. }
  33758. /**
  33759. * Module for representing ambient lights as nodes.
  33760. *
  33761. * @augments AnalyticLightNode
  33762. */
  33763. class AmbientLightNode extends AnalyticLightNode {
  33764. static get type() {
  33765. return 'AmbientLightNode';
  33766. }
  33767. /**
  33768. * Constructs a new ambient light node.
  33769. *
  33770. * @param {?AmbientLight} [light=null] - The ambient light source.
  33771. */
  33772. constructor( light = null ) {
  33773. super( light );
  33774. }
  33775. setup( { context } ) {
  33776. context.irradiance.addAssign( this.colorNode );
  33777. }
  33778. }
  33779. /**
  33780. * Module for representing hemisphere lights as nodes.
  33781. *
  33782. * @augments AnalyticLightNode
  33783. */
  33784. class HemisphereLightNode extends AnalyticLightNode {
  33785. static get type() {
  33786. return 'HemisphereLightNode';
  33787. }
  33788. /**
  33789. * Constructs a new hemisphere light node.
  33790. *
  33791. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  33792. */
  33793. constructor( light = null ) {
  33794. super( light );
  33795. /**
  33796. * Uniform node representing the light's position.
  33797. *
  33798. * @type {UniformNode<vec3>}
  33799. */
  33800. this.lightPositionNode = lightPosition( light );
  33801. /**
  33802. * A node representing the light's direction.
  33803. *
  33804. * @type {Node<vec3>}
  33805. */
  33806. this.lightDirectionNode = this.lightPositionNode.normalize();
  33807. /**
  33808. * Uniform node representing the light's ground color.
  33809. *
  33810. * @type {UniformNode<vec3>}
  33811. */
  33812. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  33813. }
  33814. /**
  33815. * Overwritten to updated hemisphere light specific uniforms.
  33816. *
  33817. * @param {NodeFrame} frame - A reference to the current node frame.
  33818. */
  33819. update( frame ) {
  33820. const { light } = this;
  33821. super.update( frame );
  33822. this.lightPositionNode.object3d = light;
  33823. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  33824. }
  33825. setup( builder ) {
  33826. const { colorNode, groundColorNode, lightDirectionNode } = this;
  33827. const dotNL = normalView.dot( lightDirectionNode );
  33828. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  33829. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  33830. builder.context.irradiance.addAssign( irradiance );
  33831. }
  33832. }
  33833. /**
  33834. * Module for representing light probes as nodes.
  33835. *
  33836. * @augments AnalyticLightNode
  33837. */
  33838. class LightProbeNode extends AnalyticLightNode {
  33839. static get type() {
  33840. return 'LightProbeNode';
  33841. }
  33842. /**
  33843. * Constructs a new light probe node.
  33844. *
  33845. * @param {?LightProbe} [light=null] - The light probe.
  33846. */
  33847. constructor( light = null ) {
  33848. super( light );
  33849. const array = [];
  33850. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  33851. /**
  33852. * Light probe represented as a uniform of spherical harmonics.
  33853. *
  33854. * @type {UniformArrayNode}
  33855. */
  33856. this.lightProbe = uniformArray( array );
  33857. }
  33858. /**
  33859. * Overwritten to updated light probe specific uniforms.
  33860. *
  33861. * @param {NodeFrame} frame - A reference to the current node frame.
  33862. */
  33863. update( frame ) {
  33864. const { light } = this;
  33865. super.update( frame );
  33866. //
  33867. for ( let i = 0; i < 9; i ++ ) {
  33868. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  33869. }
  33870. }
  33871. setup( builder ) {
  33872. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  33873. builder.context.irradiance.addAssign( irradiance );
  33874. }
  33875. }
  33876. /**
  33877. * Base class for node parsers. A derived parser must be implemented
  33878. * for each supported native shader language.
  33879. */
  33880. class NodeParser {
  33881. /**
  33882. * The method parses the given native code an returns a node function.
  33883. *
  33884. * @abstract
  33885. * @param {string} source - The native shader code.
  33886. * @return {NodeFunction} A node function.
  33887. */
  33888. parseFunction( /*source*/ ) {
  33889. console.warn( 'Abstract function.' );
  33890. }
  33891. }
  33892. /**
  33893. * Base class for node functions. A derived module must be implemented
  33894. * for each supported native shader language. Similar to other `Node*` modules,
  33895. * this class is only relevant during the building process and not used
  33896. * in user-level code.
  33897. */
  33898. class NodeFunction {
  33899. /**
  33900. * Constructs a new node function.
  33901. *
  33902. * @param {string} type - The node type. This type is the return type of the node function.
  33903. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  33904. * @param {string} [name=''] - The function's name.
  33905. * @param {string} [precision=''] - The precision qualifier.
  33906. */
  33907. constructor( type, inputs, name = '', precision = '' ) {
  33908. /**
  33909. * The node type. This type is the return type of the node function.
  33910. *
  33911. * @type {string}
  33912. */
  33913. this.type = type;
  33914. /**
  33915. * The function's inputs.
  33916. *
  33917. * @type {Array<NodeFunctionInput>}
  33918. */
  33919. this.inputs = inputs;
  33920. /**
  33921. * The name of the uniform.
  33922. *
  33923. * @type {string}
  33924. * @default ''
  33925. */
  33926. this.name = name;
  33927. /**
  33928. * The precision qualifier.
  33929. *
  33930. * @type {string}
  33931. * @default ''
  33932. */
  33933. this.precision = precision;
  33934. }
  33935. /**
  33936. * This method returns the native code of the node function.
  33937. *
  33938. * @abstract
  33939. * @param {string} name - The function's name.
  33940. * @return {string} A shader code.
  33941. */
  33942. getCode( /*name = this.name*/ ) {
  33943. console.warn( 'Abstract function.' );
  33944. }
  33945. }
  33946. NodeFunction.isNodeFunction = true;
  33947. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  33948. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  33949. const pragmaMain = '#pragma main';
  33950. const parse$1 = ( source ) => {
  33951. source = source.trim();
  33952. const pragmaMainIndex = source.indexOf( pragmaMain );
  33953. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  33954. const declaration = mainCode.match( declarationRegexp$1 );
  33955. if ( declaration !== null && declaration.length === 5 ) {
  33956. // tokenizer
  33957. const inputsCode = declaration[ 4 ];
  33958. const propsMatches = [];
  33959. let nameMatch = null;
  33960. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  33961. propsMatches.push( nameMatch );
  33962. }
  33963. // parser
  33964. const inputs = [];
  33965. let i = 0;
  33966. while ( i < propsMatches.length ) {
  33967. const isConst = propsMatches[ i ][ 0 ] === 'const';
  33968. if ( isConst === true ) {
  33969. i ++;
  33970. }
  33971. let qualifier = propsMatches[ i ][ 0 ];
  33972. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  33973. i ++;
  33974. } else {
  33975. qualifier = '';
  33976. }
  33977. const type = propsMatches[ i ++ ][ 0 ];
  33978. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  33979. if ( Number.isNaN( count ) === false ) i ++;
  33980. else count = null;
  33981. const name = propsMatches[ i ++ ][ 0 ];
  33982. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  33983. }
  33984. //
  33985. const blockCode = mainCode.substring( declaration[ 0 ].length );
  33986. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  33987. const type = declaration[ 2 ];
  33988. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  33989. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  33990. return {
  33991. type,
  33992. inputs,
  33993. name,
  33994. precision,
  33995. inputsCode,
  33996. blockCode,
  33997. headerCode
  33998. };
  33999. } else {
  34000. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  34001. }
  34002. };
  34003. /**
  34004. * This class represents a GLSL node function.
  34005. *
  34006. * @augments NodeFunction
  34007. */
  34008. class GLSLNodeFunction extends NodeFunction {
  34009. /**
  34010. * Constructs a new GLSL node function.
  34011. *
  34012. * @param {string} source - The GLSL source.
  34013. */
  34014. constructor( source ) {
  34015. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  34016. super( type, inputs, name, precision );
  34017. this.inputsCode = inputsCode;
  34018. this.blockCode = blockCode;
  34019. this.headerCode = headerCode;
  34020. }
  34021. /**
  34022. * This method returns the GLSL code of the node function.
  34023. *
  34024. * @param {string} [name=this.name] - The function's name.
  34025. * @return {string} The shader code.
  34026. */
  34027. getCode( name = this.name ) {
  34028. let code;
  34029. const blockCode = this.blockCode;
  34030. if ( blockCode !== '' ) {
  34031. const { type, inputsCode, headerCode, precision } = this;
  34032. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  34033. if ( precision !== '' ) {
  34034. declarationCode = `${ precision } ${ declarationCode }`;
  34035. }
  34036. code = headerCode + declarationCode + blockCode;
  34037. } else {
  34038. // interface function
  34039. code = '';
  34040. }
  34041. return code;
  34042. }
  34043. }
  34044. /**
  34045. * A GLSL node parser.
  34046. *
  34047. * @augments NodeParser
  34048. */
  34049. class GLSLNodeParser extends NodeParser {
  34050. /**
  34051. * The method parses the given GLSL code an returns a node function.
  34052. *
  34053. * @param {string} source - The GLSL code.
  34054. * @return {GLSLNodeFunction} A node function.
  34055. */
  34056. parseFunction( source ) {
  34057. return new GLSLNodeFunction( source );
  34058. }
  34059. }
  34060. const _outputNodeMap = new WeakMap();
  34061. const _chainKeys$2 = [];
  34062. const _cacheKeyValues = [];
  34063. /**
  34064. * This renderer module manages node-related objects and is the
  34065. * primary interface between the renderer and the node system.
  34066. *
  34067. * @private
  34068. * @augments DataMap
  34069. */
  34070. class Nodes extends DataMap {
  34071. /**
  34072. * Constructs a new nodes management component.
  34073. *
  34074. * @param {Renderer} renderer - The renderer.
  34075. * @param {Backend} backend - The renderer's backend.
  34076. */
  34077. constructor( renderer, backend ) {
  34078. super();
  34079. /**
  34080. * The renderer.
  34081. *
  34082. * @type {Renderer}
  34083. */
  34084. this.renderer = renderer;
  34085. /**
  34086. * The renderer's backend.
  34087. *
  34088. * @type {Backend}
  34089. */
  34090. this.backend = backend;
  34091. /**
  34092. * The node frame.
  34093. *
  34094. * @type {Renderer}
  34095. */
  34096. this.nodeFrame = new NodeFrame();
  34097. /**
  34098. * A cache for managing node builder states.
  34099. *
  34100. * @type {Map<number,NodeBuilderState>}
  34101. */
  34102. this.nodeBuilderCache = new Map();
  34103. /**
  34104. * A cache for managing data cache key data.
  34105. *
  34106. * @type {ChainMap}
  34107. */
  34108. this.callHashCache = new ChainMap();
  34109. /**
  34110. * A cache for managing node uniforms group data.
  34111. *
  34112. * @type {ChainMap}
  34113. */
  34114. this.groupsData = new ChainMap();
  34115. /**
  34116. * A cache for managing node objects of
  34117. * scene properties like fog or environments.
  34118. *
  34119. * @type {Object<string,WeakMap>}
  34120. */
  34121. this.cacheLib = {};
  34122. }
  34123. /**
  34124. * Returns `true` if the given node uniforms group must be updated or not.
  34125. *
  34126. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  34127. * @return {boolean} Whether the node uniforms group requires an update or not.
  34128. */
  34129. updateGroup( nodeUniformsGroup ) {
  34130. const groupNode = nodeUniformsGroup.groupNode;
  34131. const name = groupNode.name;
  34132. // objectGroup is always updated
  34133. if ( name === objectGroup.name ) return true;
  34134. // renderGroup is updated once per render/compute call
  34135. if ( name === renderGroup.name ) {
  34136. const uniformsGroupData = this.get( nodeUniformsGroup );
  34137. const renderId = this.nodeFrame.renderId;
  34138. if ( uniformsGroupData.renderId !== renderId ) {
  34139. uniformsGroupData.renderId = renderId;
  34140. return true;
  34141. }
  34142. return false;
  34143. }
  34144. // frameGroup is updated once per frame
  34145. if ( name === frameGroup.name ) {
  34146. const uniformsGroupData = this.get( nodeUniformsGroup );
  34147. const frameId = this.nodeFrame.frameId;
  34148. if ( uniformsGroupData.frameId !== frameId ) {
  34149. uniformsGroupData.frameId = frameId;
  34150. return true;
  34151. }
  34152. return false;
  34153. }
  34154. // other groups are updated just when groupNode.needsUpdate is true
  34155. _chainKeys$2[ 0 ] = groupNode;
  34156. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  34157. let groupData = this.groupsData.get( _chainKeys$2 );
  34158. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  34159. _chainKeys$2.length = 0;
  34160. if ( groupData.version !== groupNode.version ) {
  34161. groupData.version = groupNode.version;
  34162. return true;
  34163. }
  34164. return false;
  34165. }
  34166. /**
  34167. * Returns the cache key for the given render object.
  34168. *
  34169. * @param {RenderObject} renderObject - The render object.
  34170. * @return {number} The cache key.
  34171. */
  34172. getForRenderCacheKey( renderObject ) {
  34173. return renderObject.initialCacheKey;
  34174. }
  34175. /**
  34176. * Returns a node builder state for the given render object.
  34177. *
  34178. * @param {RenderObject} renderObject - The render object.
  34179. * @return {NodeBuilderState} The node builder state.
  34180. */
  34181. getForRender( renderObject ) {
  34182. const renderObjectData = this.get( renderObject );
  34183. let nodeBuilderState = renderObjectData.nodeBuilderState;
  34184. if ( nodeBuilderState === undefined ) {
  34185. const { nodeBuilderCache } = this;
  34186. const cacheKey = this.getForRenderCacheKey( renderObject );
  34187. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  34188. if ( nodeBuilderState === undefined ) {
  34189. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  34190. nodeBuilder.scene = renderObject.scene;
  34191. nodeBuilder.material = renderObject.material;
  34192. nodeBuilder.camera = renderObject.camera;
  34193. nodeBuilder.context.material = renderObject.material;
  34194. nodeBuilder.lightsNode = renderObject.lightsNode;
  34195. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  34196. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  34197. nodeBuilder.clippingContext = renderObject.clippingContext;
  34198. if ( this.renderer.getRenderTarget() ? this.renderer.getRenderTarget().multiview : false ) {
  34199. nodeBuilder.enableMultiview();
  34200. }
  34201. nodeBuilder.build();
  34202. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34203. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  34204. }
  34205. nodeBuilderState.usedTimes ++;
  34206. renderObjectData.nodeBuilderState = nodeBuilderState;
  34207. }
  34208. return nodeBuilderState;
  34209. }
  34210. /**
  34211. * Deletes the given object from the internal data map
  34212. *
  34213. * @param {any} object - The object to delete.
  34214. * @return {?Object} The deleted dictionary.
  34215. */
  34216. delete( object ) {
  34217. if ( object.isRenderObject ) {
  34218. const nodeBuilderState = this.get( object ).nodeBuilderState;
  34219. nodeBuilderState.usedTimes --;
  34220. if ( nodeBuilderState.usedTimes === 0 ) {
  34221. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  34222. }
  34223. }
  34224. return super.delete( object );
  34225. }
  34226. /**
  34227. * Returns a node builder state for the given compute node.
  34228. *
  34229. * @param {Node} computeNode - The compute node.
  34230. * @return {NodeBuilderState} The node builder state.
  34231. */
  34232. getForCompute( computeNode ) {
  34233. const computeData = this.get( computeNode );
  34234. let nodeBuilderState = computeData.nodeBuilderState;
  34235. if ( nodeBuilderState === undefined ) {
  34236. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  34237. nodeBuilder.build();
  34238. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34239. computeData.nodeBuilderState = nodeBuilderState;
  34240. }
  34241. return nodeBuilderState;
  34242. }
  34243. /**
  34244. * Creates a node builder state for the given node builder.
  34245. *
  34246. * @private
  34247. * @param {NodeBuilder} nodeBuilder - The node builder.
  34248. * @return {NodeBuilderState} The node builder state.
  34249. */
  34250. _createNodeBuilderState( nodeBuilder ) {
  34251. return new NodeBuilderState(
  34252. nodeBuilder.vertexShader,
  34253. nodeBuilder.fragmentShader,
  34254. nodeBuilder.computeShader,
  34255. nodeBuilder.getAttributesArray(),
  34256. nodeBuilder.getBindings(),
  34257. nodeBuilder.updateNodes,
  34258. nodeBuilder.updateBeforeNodes,
  34259. nodeBuilder.updateAfterNodes,
  34260. nodeBuilder.observer,
  34261. nodeBuilder.transforms
  34262. );
  34263. }
  34264. /**
  34265. * Returns an environment node for the current configured
  34266. * scene environment.
  34267. *
  34268. * @param {Scene} scene - The scene.
  34269. * @return {Node} A node representing the current scene environment.
  34270. */
  34271. getEnvironmentNode( scene ) {
  34272. this.updateEnvironment( scene );
  34273. let environmentNode = null;
  34274. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  34275. environmentNode = scene.environmentNode;
  34276. } else {
  34277. const sceneData = this.get( scene );
  34278. if ( sceneData.environmentNode ) {
  34279. environmentNode = sceneData.environmentNode;
  34280. }
  34281. }
  34282. return environmentNode;
  34283. }
  34284. /**
  34285. * Returns a background node for the current configured
  34286. * scene background.
  34287. *
  34288. * @param {Scene} scene - The scene.
  34289. * @return {Node} A node representing the current scene background.
  34290. */
  34291. getBackgroundNode( scene ) {
  34292. this.updateBackground( scene );
  34293. let backgroundNode = null;
  34294. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  34295. backgroundNode = scene.backgroundNode;
  34296. } else {
  34297. const sceneData = this.get( scene );
  34298. if ( sceneData.backgroundNode ) {
  34299. backgroundNode = sceneData.backgroundNode;
  34300. }
  34301. }
  34302. return backgroundNode;
  34303. }
  34304. /**
  34305. * Returns a fog node for the current configured scene fog.
  34306. *
  34307. * @param {Scene} scene - The scene.
  34308. * @return {Node} A node representing the current scene fog.
  34309. */
  34310. getFogNode( scene ) {
  34311. this.updateFog( scene );
  34312. return scene.fogNode || this.get( scene ).fogNode || null;
  34313. }
  34314. /**
  34315. * Returns a cache key for the given scene and lights node.
  34316. * This key is used by `RenderObject` as a part of the dynamic
  34317. * cache key (a key that must be checked every time the render
  34318. * objects is drawn).
  34319. *
  34320. * @param {Scene} scene - The scene.
  34321. * @param {LightsNode} lightsNode - The lights node.
  34322. * @return {number} The cache key.
  34323. */
  34324. getCacheKey( scene, lightsNode ) {
  34325. _chainKeys$2[ 0 ] = scene;
  34326. _chainKeys$2[ 1 ] = lightsNode;
  34327. const callId = this.renderer.info.calls;
  34328. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  34329. if ( cacheKeyData.callId !== callId ) {
  34330. const environmentNode = this.getEnvironmentNode( scene );
  34331. const fogNode = this.getFogNode( scene );
  34332. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  34333. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  34334. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  34335. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  34336. cacheKeyData.callId = callId;
  34337. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  34338. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  34339. _cacheKeyValues.length = 0;
  34340. }
  34341. _chainKeys$2.length = 0;
  34342. return cacheKeyData.cacheKey;
  34343. }
  34344. /**
  34345. * A boolean that indicates whether tone mapping should be enabled
  34346. * or not.
  34347. *
  34348. * @type {boolean}
  34349. */
  34350. get isToneMappingState() {
  34351. return this.renderer.getRenderTarget() ? false : true;
  34352. }
  34353. /**
  34354. * If a scene background is configured, this method makes sure to
  34355. * represent the background with a corresponding node-based implementation.
  34356. *
  34357. * @param {Scene} scene - The scene.
  34358. */
  34359. updateBackground( scene ) {
  34360. const sceneData = this.get( scene );
  34361. const background = scene.background;
  34362. if ( background ) {
  34363. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  34364. if ( sceneData.background !== background || forceUpdate ) {
  34365. const backgroundNode = this.getCacheNode( 'background', background, () => {
  34366. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  34367. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  34368. return pmremTexture( background );
  34369. } else {
  34370. let envMap;
  34371. if ( background.isCubeTexture === true ) {
  34372. envMap = cubeTexture( background );
  34373. } else {
  34374. envMap = texture( background );
  34375. }
  34376. return cubeMapNode( envMap );
  34377. }
  34378. } else if ( background.isTexture === true ) {
  34379. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  34380. } else if ( background.isColor !== true ) {
  34381. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  34382. }
  34383. }, forceUpdate );
  34384. sceneData.backgroundNode = backgroundNode;
  34385. sceneData.background = background;
  34386. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  34387. }
  34388. } else if ( sceneData.backgroundNode ) {
  34389. delete sceneData.backgroundNode;
  34390. delete sceneData.background;
  34391. }
  34392. }
  34393. /**
  34394. * This method is part of the caching of nodes which are used to represents the
  34395. * scene's background, fog or environment.
  34396. *
  34397. * @param {string} type - The type of object to cache.
  34398. * @param {Object} object - The object.
  34399. * @param {Function} callback - A callback that produces a node representation for the given object.
  34400. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  34401. * @return {Node} The node representation.
  34402. */
  34403. getCacheNode( type, object, callback, forceUpdate = false ) {
  34404. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  34405. let node = nodeCache.get( object );
  34406. if ( node === undefined || forceUpdate ) {
  34407. node = callback();
  34408. nodeCache.set( object, node );
  34409. }
  34410. return node;
  34411. }
  34412. /**
  34413. * If a scene fog is configured, this method makes sure to
  34414. * represent the fog with a corresponding node-based implementation.
  34415. *
  34416. * @param {Scene} scene - The scene.
  34417. */
  34418. updateFog( scene ) {
  34419. const sceneData = this.get( scene );
  34420. const sceneFog = scene.fog;
  34421. if ( sceneFog ) {
  34422. if ( sceneData.fog !== sceneFog ) {
  34423. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  34424. if ( sceneFog.isFogExp2 ) {
  34425. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34426. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  34427. return fog( color, densityFogFactor( density ) );
  34428. } else if ( sceneFog.isFog ) {
  34429. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34430. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  34431. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  34432. return fog( color, rangeFogFactor( near, far ) );
  34433. } else {
  34434. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  34435. }
  34436. } );
  34437. sceneData.fogNode = fogNode;
  34438. sceneData.fog = sceneFog;
  34439. }
  34440. } else {
  34441. delete sceneData.fogNode;
  34442. delete sceneData.fog;
  34443. }
  34444. }
  34445. /**
  34446. * If a scene environment is configured, this method makes sure to
  34447. * represent the environment with a corresponding node-based implementation.
  34448. *
  34449. * @param {Scene} scene - The scene.
  34450. */
  34451. updateEnvironment( scene ) {
  34452. const sceneData = this.get( scene );
  34453. const environment = scene.environment;
  34454. if ( environment ) {
  34455. if ( sceneData.environment !== environment ) {
  34456. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  34457. if ( environment.isCubeTexture === true ) {
  34458. return cubeTexture( environment );
  34459. } else if ( environment.isTexture === true ) {
  34460. return texture( environment );
  34461. } else {
  34462. console.error( 'Nodes: Unsupported environment configuration.', environment );
  34463. }
  34464. } );
  34465. sceneData.environmentNode = environmentNode;
  34466. sceneData.environment = environment;
  34467. }
  34468. } else if ( sceneData.environmentNode ) {
  34469. delete sceneData.environmentNode;
  34470. delete sceneData.environment;
  34471. }
  34472. }
  34473. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  34474. const nodeFrame = this.nodeFrame;
  34475. nodeFrame.renderer = renderer;
  34476. nodeFrame.scene = scene;
  34477. nodeFrame.object = object;
  34478. nodeFrame.camera = camera;
  34479. nodeFrame.material = material;
  34480. return nodeFrame;
  34481. }
  34482. getNodeFrameForRender( renderObject ) {
  34483. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  34484. }
  34485. /**
  34486. * Returns the current output cache key.
  34487. *
  34488. * @return {string} The output cache key.
  34489. */
  34490. getOutputCacheKey() {
  34491. const renderer = this.renderer;
  34492. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  34493. }
  34494. /**
  34495. * Checks if the output configuration (tone mapping and color space) for
  34496. * the given target has changed.
  34497. *
  34498. * @param {Texture} outputTarget - The output target.
  34499. * @return {boolean} Whether the output configuration has changed or not.
  34500. */
  34501. hasOutputChange( outputTarget ) {
  34502. const cacheKey = _outputNodeMap.get( outputTarget );
  34503. return cacheKey !== this.getOutputCacheKey();
  34504. }
  34505. /**
  34506. * Returns a node that represents the output configuration (tone mapping and
  34507. * color space) for the current target.
  34508. *
  34509. * @param {Texture} outputTarget - The output target.
  34510. * @return {Node} The output node.
  34511. */
  34512. getOutputNode( outputTarget ) {
  34513. const renderer = this.renderer;
  34514. const cacheKey = this.getOutputCacheKey();
  34515. const output = outputTarget.isArrayTexture ?
  34516. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  34517. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  34518. _outputNodeMap.set( outputTarget, cacheKey );
  34519. return output;
  34520. }
  34521. /**
  34522. * Triggers the call of `updateBefore()` methods
  34523. * for all nodes of the given render object.
  34524. *
  34525. * @param {RenderObject} renderObject - The render object.
  34526. */
  34527. updateBefore( renderObject ) {
  34528. const nodeBuilder = renderObject.getNodeBuilderState();
  34529. for ( const node of nodeBuilder.updateBeforeNodes ) {
  34530. // update frame state for each node
  34531. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  34532. }
  34533. }
  34534. /**
  34535. * Triggers the call of `updateAfter()` methods
  34536. * for all nodes of the given render object.
  34537. *
  34538. * @param {RenderObject} renderObject - The render object.
  34539. */
  34540. updateAfter( renderObject ) {
  34541. const nodeBuilder = renderObject.getNodeBuilderState();
  34542. for ( const node of nodeBuilder.updateAfterNodes ) {
  34543. // update frame state for each node
  34544. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  34545. }
  34546. }
  34547. /**
  34548. * Triggers the call of `update()` methods
  34549. * for all nodes of the given compute node.
  34550. *
  34551. * @param {Node} computeNode - The compute node.
  34552. */
  34553. updateForCompute( computeNode ) {
  34554. const nodeFrame = this.getNodeFrame();
  34555. const nodeBuilder = this.getForCompute( computeNode );
  34556. for ( const node of nodeBuilder.updateNodes ) {
  34557. nodeFrame.updateNode( node );
  34558. }
  34559. }
  34560. /**
  34561. * Triggers the call of `update()` methods
  34562. * for all nodes of the given compute node.
  34563. *
  34564. * @param {RenderObject} renderObject - The render object.
  34565. */
  34566. updateForRender( renderObject ) {
  34567. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34568. const nodeBuilder = renderObject.getNodeBuilderState();
  34569. for ( const node of nodeBuilder.updateNodes ) {
  34570. nodeFrame.updateNode( node );
  34571. }
  34572. }
  34573. /**
  34574. * Returns `true` if the given render object requires a refresh.
  34575. *
  34576. * @param {RenderObject} renderObject - The render object.
  34577. * @return {boolean} Whether the given render object requires a refresh or not.
  34578. */
  34579. needsRefresh( renderObject ) {
  34580. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34581. const monitor = renderObject.getMonitor();
  34582. return monitor.needsRefresh( renderObject, nodeFrame );
  34583. }
  34584. /**
  34585. * Frees the internal resources.
  34586. */
  34587. dispose() {
  34588. super.dispose();
  34589. this.nodeFrame = new NodeFrame();
  34590. this.nodeBuilderCache = new Map();
  34591. this.cacheLib = {};
  34592. }
  34593. }
  34594. const _plane = /*@__PURE__*/ new Plane();
  34595. /**
  34596. * Represents the state that is used to perform clipping via clipping planes.
  34597. * There is a default clipping context for each render context. When the
  34598. * scene holds instances of `ClippingGroup`, there will be a context for each
  34599. * group.
  34600. *
  34601. * @private
  34602. */
  34603. class ClippingContext {
  34604. /**
  34605. * Constructs a new clipping context.
  34606. *
  34607. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  34608. */
  34609. constructor( parentContext = null ) {
  34610. /**
  34611. * The clipping context's version.
  34612. *
  34613. * @type {number}
  34614. * @readonly
  34615. */
  34616. this.version = 0;
  34617. /**
  34618. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  34619. *
  34620. * @type {?boolean}
  34621. * @default null
  34622. */
  34623. this.clipIntersection = null;
  34624. /**
  34625. * The clipping context's cache key.
  34626. *
  34627. * @type {string}
  34628. */
  34629. this.cacheKey = '';
  34630. /**
  34631. * Whether the shadow pass is active or not.
  34632. *
  34633. * @type {boolean}
  34634. * @default false
  34635. */
  34636. this.shadowPass = false;
  34637. /**
  34638. * The view normal matrix.
  34639. *
  34640. * @type {Matrix3}
  34641. */
  34642. this.viewNormalMatrix = new Matrix3();
  34643. /**
  34644. * Internal cache for maintaining clipping contexts.
  34645. *
  34646. * @type {WeakMap<ClippingGroup,ClippingContext>}
  34647. */
  34648. this.clippingGroupContexts = new WeakMap();
  34649. /**
  34650. * The intersection planes.
  34651. *
  34652. * @type {Array<Vector4>}
  34653. */
  34654. this.intersectionPlanes = [];
  34655. /**
  34656. * The intersection planes.
  34657. *
  34658. * @type {Array<Vector4>}
  34659. */
  34660. this.unionPlanes = [];
  34661. /**
  34662. * The version of the clipping context's parent context.
  34663. *
  34664. * @type {?number}
  34665. * @readonly
  34666. */
  34667. this.parentVersion = null;
  34668. if ( parentContext !== null ) {
  34669. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  34670. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  34671. this.shadowPass = parentContext.shadowPass;
  34672. this.viewMatrix = parentContext.viewMatrix;
  34673. }
  34674. }
  34675. /**
  34676. * Projects the given source clipping planes and writes the result into the
  34677. * destination array.
  34678. *
  34679. * @param {Array<Plane>} source - The source clipping planes.
  34680. * @param {Array<Vector4>} destination - The destination.
  34681. * @param {number} offset - The offset.
  34682. */
  34683. projectPlanes( source, destination, offset ) {
  34684. const l = source.length;
  34685. for ( let i = 0; i < l; i ++ ) {
  34686. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  34687. const v = destination[ offset + i ];
  34688. const normal = _plane.normal;
  34689. v.x = - normal.x;
  34690. v.y = - normal.y;
  34691. v.z = - normal.z;
  34692. v.w = _plane.constant;
  34693. }
  34694. }
  34695. /**
  34696. * Updates the root clipping context of a scene.
  34697. *
  34698. * @param {Scene} scene - The scene.
  34699. * @param {Camera} camera - The camera that is used to render the scene.
  34700. */
  34701. updateGlobal( scene, camera ) {
  34702. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  34703. this.viewMatrix = camera.matrixWorldInverse;
  34704. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  34705. }
  34706. /**
  34707. * Updates the clipping context.
  34708. *
  34709. * @param {ClippingContext} parentContext - The parent context.
  34710. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  34711. */
  34712. update( parentContext, clippingGroup ) {
  34713. let update = false;
  34714. if ( parentContext.version !== this.parentVersion ) {
  34715. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  34716. this.unionPlanes = Array.from( parentContext.unionPlanes );
  34717. this.parentVersion = parentContext.version;
  34718. }
  34719. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  34720. this.clipIntersection = clippingGroup.clipIntersection;
  34721. if ( this.clipIntersection ) {
  34722. this.unionPlanes.length = parentContext.unionPlanes.length;
  34723. } else {
  34724. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  34725. }
  34726. }
  34727. const srcClippingPlanes = clippingGroup.clippingPlanes;
  34728. const l = srcClippingPlanes.length;
  34729. let dstClippingPlanes;
  34730. let offset;
  34731. if ( this.clipIntersection ) {
  34732. dstClippingPlanes = this.intersectionPlanes;
  34733. offset = parentContext.intersectionPlanes.length;
  34734. } else {
  34735. dstClippingPlanes = this.unionPlanes;
  34736. offset = parentContext.unionPlanes.length;
  34737. }
  34738. if ( dstClippingPlanes.length !== offset + l ) {
  34739. dstClippingPlanes.length = offset + l;
  34740. for ( let i = 0; i < l; i ++ ) {
  34741. dstClippingPlanes[ offset + i ] = new Vector4();
  34742. }
  34743. update = true;
  34744. }
  34745. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  34746. if ( update ) {
  34747. this.version ++;
  34748. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  34749. }
  34750. }
  34751. /**
  34752. * Returns a clipping context for the given clipping group.
  34753. *
  34754. * @param {ClippingGroup} clippingGroup - The clipping group.
  34755. * @return {ClippingContext} The clipping context.
  34756. */
  34757. getGroupContext( clippingGroup ) {
  34758. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  34759. let context = this.clippingGroupContexts.get( clippingGroup );
  34760. if ( context === undefined ) {
  34761. context = new ClippingContext( this );
  34762. this.clippingGroupContexts.set( clippingGroup, context );
  34763. }
  34764. context.update( this, clippingGroup );
  34765. return context;
  34766. }
  34767. /**
  34768. * The count of union clipping planes.
  34769. *
  34770. * @type {number}
  34771. * @readonly
  34772. */
  34773. get unionClippingCount() {
  34774. return this.unionPlanes.length;
  34775. }
  34776. }
  34777. /**
  34778. * This module is used to represent render bundles inside the renderer
  34779. * for further processing.
  34780. *
  34781. * @private
  34782. */
  34783. class RenderBundle {
  34784. /**
  34785. * Constructs a new bundle group.
  34786. *
  34787. * @param {BundleGroup} bundleGroup - The bundle group.
  34788. * @param {Camera} camera - The camera the bundle group is rendered with.
  34789. */
  34790. constructor( bundleGroup, camera ) {
  34791. this.bundleGroup = bundleGroup;
  34792. this.camera = camera;
  34793. }
  34794. }
  34795. const _chainKeys$1 = [];
  34796. /**
  34797. * This renderer module manages render bundles.
  34798. *
  34799. * @private
  34800. */
  34801. class RenderBundles {
  34802. /**
  34803. * Constructs a new render bundle management component.
  34804. */
  34805. constructor() {
  34806. /**
  34807. * A chain map for maintaining the render bundles.
  34808. *
  34809. * @type {ChainMap}
  34810. */
  34811. this.bundles = new ChainMap();
  34812. }
  34813. /**
  34814. * Returns a render bundle for the given bundle group and camera.
  34815. *
  34816. * @param {BundleGroup} bundleGroup - The bundle group.
  34817. * @param {Camera} camera - The camera the bundle group is rendered with.
  34818. * @return {RenderBundle} The render bundle.
  34819. */
  34820. get( bundleGroup, camera ) {
  34821. const bundles = this.bundles;
  34822. _chainKeys$1[ 0 ] = bundleGroup;
  34823. _chainKeys$1[ 1 ] = camera;
  34824. let bundle = bundles.get( _chainKeys$1 );
  34825. if ( bundle === undefined ) {
  34826. bundle = new RenderBundle( bundleGroup, camera );
  34827. bundles.set( _chainKeys$1, bundle );
  34828. }
  34829. _chainKeys$1.length = 0;
  34830. return bundle;
  34831. }
  34832. /**
  34833. * Frees all internal resources.
  34834. */
  34835. dispose() {
  34836. this.bundles = new ChainMap();
  34837. }
  34838. }
  34839. /**
  34840. * The purpose of a node library is to assign node implementations
  34841. * to existing library features. In `WebGPURenderer` lights, materials
  34842. * which are not based on `NodeMaterial` as well as tone mapping techniques
  34843. * are implemented with node-based modules.
  34844. *
  34845. * @private
  34846. */
  34847. class NodeLibrary {
  34848. /**
  34849. * Constructs a new node library.
  34850. */
  34851. constructor() {
  34852. /**
  34853. * A weak map that maps lights to light nodes.
  34854. *
  34855. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  34856. */
  34857. this.lightNodes = new WeakMap();
  34858. /**
  34859. * A map that maps materials to node materials.
  34860. *
  34861. * @type {Map<string,NodeMaterial.constructor>}
  34862. */
  34863. this.materialNodes = new Map();
  34864. /**
  34865. * A map that maps tone mapping techniques (constants)
  34866. * to tone mapping node functions.
  34867. *
  34868. * @type {Map<number,Function>}
  34869. */
  34870. this.toneMappingNodes = new Map();
  34871. }
  34872. /**
  34873. * Returns a matching node material instance for the given material object.
  34874. *
  34875. * This method also assigns/copies the properties of the given material object
  34876. * to the node material. This is done to make sure the current material
  34877. * configuration carries over to the node version.
  34878. *
  34879. * @param {Material} material - A material.
  34880. * @return {NodeMaterial} The corresponding node material.
  34881. */
  34882. fromMaterial( material ) {
  34883. if ( material.isNodeMaterial ) return material;
  34884. let nodeMaterial = null;
  34885. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  34886. if ( nodeMaterialClass !== null ) {
  34887. nodeMaterial = new nodeMaterialClass();
  34888. for ( const key in material ) {
  34889. nodeMaterial[ key ] = material[ key ];
  34890. }
  34891. }
  34892. return nodeMaterial;
  34893. }
  34894. /**
  34895. * Adds a tone mapping node function for a tone mapping technique (constant).
  34896. *
  34897. * @param {Function} toneMappingNode - The tone mapping node function.
  34898. * @param {number} toneMapping - The tone mapping.
  34899. */
  34900. addToneMapping( toneMappingNode, toneMapping ) {
  34901. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  34902. }
  34903. /**
  34904. * Returns a tone mapping node function for a tone mapping technique (constant).
  34905. *
  34906. * @param {number} toneMapping - The tone mapping.
  34907. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  34908. */
  34909. getToneMappingFunction( toneMapping ) {
  34910. return this.toneMappingNodes.get( toneMapping ) || null;
  34911. }
  34912. /**
  34913. * Returns a node material class definition for a material type.
  34914. *
  34915. * @param {string} materialType - The material type.
  34916. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  34917. */
  34918. getMaterialNodeClass( materialType ) {
  34919. return this.materialNodes.get( materialType ) || null;
  34920. }
  34921. /**
  34922. * Adds a node material class definition for a given material type.
  34923. *
  34924. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  34925. * @param {string} materialClassType - The material type.
  34926. */
  34927. addMaterial( materialNodeClass, materialClassType ) {
  34928. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  34929. }
  34930. /**
  34931. * Returns a light node class definition for a light class definition.
  34932. *
  34933. * @param {Light.constructor} light - The light class definition.
  34934. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  34935. */
  34936. getLightNodeClass( light ) {
  34937. return this.lightNodes.get( light ) || null;
  34938. }
  34939. /**
  34940. * Adds a light node class definition for a given light class definition.
  34941. *
  34942. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  34943. * @param {Light.constructor} lightClass - The light class definition.
  34944. */
  34945. addLight( lightNodeClass, lightClass ) {
  34946. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  34947. }
  34948. /**
  34949. * Adds a node class definition for the given type to the provided type library.
  34950. *
  34951. * @param {any} nodeClass - The node class definition.
  34952. * @param {number|string} type - The object type.
  34953. * @param {Map} library - The type library.
  34954. */
  34955. addType( nodeClass, type, library ) {
  34956. if ( library.has( type ) ) {
  34957. console.warn( `Redefinition of node ${ type }` );
  34958. return;
  34959. }
  34960. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  34961. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  34962. library.set( type, nodeClass );
  34963. }
  34964. /**
  34965. * Adds a node class definition for the given class definition to the provided type library.
  34966. *
  34967. * @param {any} nodeClass - The node class definition.
  34968. * @param {any} baseClass - The class definition.
  34969. * @param {WeakMap} library - The type library.
  34970. */
  34971. addClass( nodeClass, baseClass, library ) {
  34972. if ( library.has( baseClass ) ) {
  34973. console.warn( `Redefinition of node ${ baseClass.name }` );
  34974. return;
  34975. }
  34976. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  34977. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  34978. library.set( baseClass, nodeClass );
  34979. }
  34980. }
  34981. const _defaultLights = /*@__PURE__*/ new LightsNode();
  34982. const _chainKeys = [];
  34983. /**
  34984. * This renderer module manages the lights nodes which are unique
  34985. * per scene and camera combination.
  34986. *
  34987. * The lights node itself is later configured in the render list
  34988. * with the actual lights from the scene.
  34989. *
  34990. * @private
  34991. * @augments ChainMap
  34992. */
  34993. class Lighting extends ChainMap {
  34994. /**
  34995. * Constructs a lighting management component.
  34996. */
  34997. constructor() {
  34998. super();
  34999. }
  35000. /**
  35001. * Creates a new lights node for the given array of lights.
  35002. *
  35003. * @param {Array<Light>} lights - The render object.
  35004. * @return {LightsNode} The lights node.
  35005. */
  35006. createNode( lights = [] ) {
  35007. return new LightsNode().setLights( lights );
  35008. }
  35009. /**
  35010. * Returns a lights node for the given scene and camera.
  35011. *
  35012. * @param {Scene} scene - The scene.
  35013. * @param {Camera} camera - The camera.
  35014. * @return {LightsNode} The lights node.
  35015. */
  35016. getNode( scene, camera ) {
  35017. // ignore post-processing
  35018. if ( scene.isQuadMesh ) return _defaultLights;
  35019. _chainKeys[ 0 ] = scene;
  35020. _chainKeys[ 1 ] = camera;
  35021. let node = this.get( _chainKeys );
  35022. if ( node === undefined ) {
  35023. node = this.createNode();
  35024. this.set( _chainKeys, node );
  35025. }
  35026. _chainKeys.length = 0;
  35027. return node;
  35028. }
  35029. }
  35030. /**
  35031. * A special type of render target that is used when rendering
  35032. * with the WebXR Device API.
  35033. *
  35034. * @private
  35035. * @augments RenderTarget
  35036. */
  35037. class XRRenderTarget extends RenderTarget {
  35038. /**
  35039. * Constructs a new XR render target.
  35040. *
  35041. * @param {number} [width=1] - The width of the render target.
  35042. * @param {number} [height=1] - The height of the render target.
  35043. * @param {Object} [options={}] - The configuration options.
  35044. */
  35045. constructor( width = 1, height = 1, options = {} ) {
  35046. super( width, height, options );
  35047. /**
  35048. * This flag can be used for type testing.
  35049. *
  35050. * @type {boolean}
  35051. * @readonly
  35052. * @default true
  35053. */
  35054. this.isXRRenderTarget = true;
  35055. /**
  35056. * Whether the attachments of the render target
  35057. * are defined by external textures. This flag is
  35058. * set to `true` when using the WebXR Layers API.
  35059. *
  35060. * @type {boolean}
  35061. * @default false
  35062. */
  35063. this.hasExternalTextures = false;
  35064. /**
  35065. * Whether a depth buffer should automatically be allocated
  35066. * for this XR render target or not.
  35067. *
  35068. * Allocating a depth buffer is the default behavior of XR render
  35069. * targets. However, when using the WebXR Layers API, this flag
  35070. * must be set to `false` when the `ignoreDepthValues` property of
  35071. * the projection layers evaluates to `false`.
  35072. *
  35073. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  35074. *
  35075. * @type {boolean}
  35076. * @default true
  35077. */
  35078. this.autoAllocateDepthBuffer = true;
  35079. }
  35080. copy( source ) {
  35081. super.copy( source );
  35082. this.hasExternalTextures = source.hasExternalTextures;
  35083. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  35084. return this;
  35085. }
  35086. }
  35087. const _cameraLPos = /*@__PURE__*/ new Vector3();
  35088. const _cameraRPos = /*@__PURE__*/ new Vector3();
  35089. /**
  35090. * The XR manager is built on top of the WebXR Device API to
  35091. * manage XR sessions with `WebGPURenderer`.
  35092. *
  35093. * XR is currently only supported with a WebGL 2 backend.
  35094. *
  35095. * @augments EventDispatcher
  35096. */
  35097. class XRManager extends EventDispatcher {
  35098. /**
  35099. * Constructs a new XR manager.
  35100. *
  35101. * @param {Renderer} renderer - The renderer.
  35102. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  35103. */
  35104. constructor( renderer, multiview = false ) {
  35105. super();
  35106. /**
  35107. * This flag globally enables XR rendering.
  35108. *
  35109. * @type {boolean}
  35110. * @default false
  35111. */
  35112. this.enabled = false;
  35113. /**
  35114. * Whether the XR device is currently presenting or not.
  35115. *
  35116. * @type {boolean}
  35117. * @default false
  35118. * @readonly
  35119. */
  35120. this.isPresenting = false;
  35121. /**
  35122. * Whether the XR camera should automatically be updated or not.
  35123. *
  35124. * @type {boolean}
  35125. * @default true
  35126. */
  35127. this.cameraAutoUpdate = true;
  35128. /**
  35129. * The renderer.
  35130. *
  35131. * @private
  35132. * @type {Renderer}
  35133. */
  35134. this._renderer = renderer;
  35135. // camera
  35136. /**
  35137. * Represents the camera for the left eye.
  35138. *
  35139. * @private
  35140. * @type {PerspectiveCamera}
  35141. */
  35142. this._cameraL = new PerspectiveCamera();
  35143. this._cameraL.viewport = new Vector4();
  35144. /**
  35145. * Represents the camera for the right eye.
  35146. *
  35147. * @private
  35148. * @type {PerspectiveCamera}
  35149. */
  35150. this._cameraR = new PerspectiveCamera();
  35151. this._cameraR.viewport = new Vector4();
  35152. /**
  35153. * A list of cameras used for rendering the XR views.
  35154. *
  35155. * @private
  35156. * @type {Array<Camera>}
  35157. */
  35158. this._cameras = [ this._cameraL, this._cameraR ];
  35159. /**
  35160. * The main XR camera.
  35161. *
  35162. * @private
  35163. * @type {ArrayCamera}
  35164. */
  35165. this._cameraXR = new ArrayCamera();
  35166. /**
  35167. * The current near value of the XR camera.
  35168. *
  35169. * @private
  35170. * @type {?number}
  35171. * @default null
  35172. */
  35173. this._currentDepthNear = null;
  35174. /**
  35175. * The current far value of the XR camera.
  35176. *
  35177. * @private
  35178. * @type {?number}
  35179. * @default null
  35180. */
  35181. this._currentDepthFar = null;
  35182. /**
  35183. * A list of WebXR controllers requested by the application.
  35184. *
  35185. * @private
  35186. * @type {Array<WebXRController>}
  35187. */
  35188. this._controllers = [];
  35189. /**
  35190. * A list of XR input source. Each input source belongs to
  35191. * an instance of WebXRController.
  35192. *
  35193. * @private
  35194. * @type {Array<XRInputSource?>}
  35195. */
  35196. this._controllerInputSources = [];
  35197. /**
  35198. * The XR render target that represents the rendering destination
  35199. * during an active XR session.
  35200. *
  35201. * @private
  35202. * @type {?RenderTarget}
  35203. * @default null
  35204. */
  35205. this._xrRenderTarget = null;
  35206. /**
  35207. * An array holding all the non-projection layers
  35208. *
  35209. * @private
  35210. * @type {Array<Object>}
  35211. * @default []
  35212. */
  35213. this._layers = [];
  35214. /**
  35215. * Whether the device has support for all layer types.
  35216. *
  35217. * @type {boolean}
  35218. * @default false
  35219. */
  35220. this._supportsLayers = false;
  35221. /**
  35222. * Helper function to create native WebXR Layer.
  35223. *
  35224. * @private
  35225. * @type {Function}
  35226. */
  35227. this._createXRLayer = createXRLayer.bind( this );
  35228. /**
  35229. * The current WebGL context.
  35230. *
  35231. * @private
  35232. * @type {?WebGL2RenderingContext}
  35233. * @default null
  35234. */
  35235. this._gl = null;
  35236. /**
  35237. * The current animation context.
  35238. *
  35239. * @private
  35240. * @type {?Window}
  35241. * @default null
  35242. */
  35243. this._currentAnimationContext = null;
  35244. /**
  35245. * The current animation loop.
  35246. *
  35247. * @private
  35248. * @type {?Function}
  35249. * @default null
  35250. */
  35251. this._currentAnimationLoop = null;
  35252. /**
  35253. * The current pixel ratio.
  35254. *
  35255. * @private
  35256. * @type {?number}
  35257. * @default null
  35258. */
  35259. this._currentPixelRatio = null;
  35260. /**
  35261. * The current size of the renderer's canvas
  35262. * in logical pixel unit.
  35263. *
  35264. * @private
  35265. * @type {Vector2}
  35266. */
  35267. this._currentSize = new Vector2();
  35268. /**
  35269. * The default event listener for handling events inside a XR session.
  35270. *
  35271. * @private
  35272. * @type {Function}
  35273. */
  35274. this._onSessionEvent = onSessionEvent.bind( this );
  35275. /**
  35276. * The event listener for handling the end of a XR session.
  35277. *
  35278. * @private
  35279. * @type {Function}
  35280. */
  35281. this._onSessionEnd = onSessionEnd.bind( this );
  35282. /**
  35283. * The event listener for handling the `inputsourceschange` event.
  35284. *
  35285. * @private
  35286. * @type {Function}
  35287. */
  35288. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  35289. /**
  35290. * The animation loop which is used as a replacement for the default
  35291. * animation loop of the application. It is only used when a XR session
  35292. * is active.
  35293. *
  35294. * @private
  35295. * @type {Function}
  35296. */
  35297. this._onAnimationFrame = onAnimationFrame.bind( this );
  35298. /**
  35299. * The current XR reference space.
  35300. *
  35301. * @private
  35302. * @type {?XRReferenceSpace}
  35303. * @default null
  35304. */
  35305. this._referenceSpace = null;
  35306. /**
  35307. * The current XR reference space type.
  35308. *
  35309. * @private
  35310. * @type {XRReferenceSpaceType}
  35311. * @default 'local-floor'
  35312. */
  35313. this._referenceSpaceType = 'local-floor';
  35314. /**
  35315. * A custom reference space defined by the application.
  35316. *
  35317. * @private
  35318. * @type {?XRReferenceSpace}
  35319. * @default null
  35320. */
  35321. this._customReferenceSpace = null;
  35322. /**
  35323. * The framebuffer scale factor.
  35324. *
  35325. * @private
  35326. * @type {number}
  35327. * @default 1
  35328. */
  35329. this._framebufferScaleFactor = 1;
  35330. /**
  35331. * The foveation factor.
  35332. *
  35333. * @private
  35334. * @type {number}
  35335. * @default 1
  35336. */
  35337. this._foveation = 1.0;
  35338. /**
  35339. * A reference to the current XR session.
  35340. *
  35341. * @private
  35342. * @type {?XRSession}
  35343. * @default null
  35344. */
  35345. this._session = null;
  35346. /**
  35347. * A reference to the current XR base layer.
  35348. *
  35349. * @private
  35350. * @type {?XRWebGLLayer}
  35351. * @default null
  35352. */
  35353. this._glBaseLayer = null;
  35354. /**
  35355. * A reference to the current XR binding.
  35356. *
  35357. * @private
  35358. * @type {?XRWebGLBinding}
  35359. * @default null
  35360. */
  35361. this._glBinding = null;
  35362. /**
  35363. * A reference to the current XR projection layer.
  35364. *
  35365. * @private
  35366. * @type {?XRProjectionLayer}
  35367. * @default null
  35368. */
  35369. this._glProjLayer = null;
  35370. /**
  35371. * A reference to the current XR frame.
  35372. *
  35373. * @private
  35374. * @type {?XRFrame}
  35375. * @default null
  35376. */
  35377. this._xrFrame = null;
  35378. /**
  35379. * Whether to use the WebXR Layers API or not.
  35380. *
  35381. * @private
  35382. * @type {boolean}
  35383. * @readonly
  35384. */
  35385. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  35386. /**
  35387. * Whether the usage of multiview has been requested by the application or not.
  35388. *
  35389. * @private
  35390. * @type {boolean}
  35391. * @default false
  35392. * @readonly
  35393. */
  35394. this._useMultiviewIfPossible = multiview;
  35395. /**
  35396. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  35397. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  35398. *
  35399. * @private
  35400. * @type {boolean}
  35401. * @readonly
  35402. */
  35403. this._useMultiview = false;
  35404. }
  35405. /**
  35406. * Returns an instance of `THREE.Group` that represents the transformation
  35407. * of a XR controller in target ray space. The requested controller is defined
  35408. * by the given index.
  35409. *
  35410. * @param {number} index - The index of the XR controller.
  35411. * @return {Group} A group that represents the controller's transformation.
  35412. */
  35413. getController( index ) {
  35414. const controller = this._getController( index );
  35415. return controller.getTargetRaySpace();
  35416. }
  35417. /**
  35418. * Returns an instance of `THREE.Group` that represents the transformation
  35419. * of a XR controller in grip space. The requested controller is defined
  35420. * by the given index.
  35421. *
  35422. * @param {number} index - The index of the XR controller.
  35423. * @return {Group} A group that represents the controller's transformation.
  35424. */
  35425. getControllerGrip( index ) {
  35426. const controller = this._getController( index );
  35427. return controller.getGripSpace();
  35428. }
  35429. /**
  35430. * Returns an instance of `THREE.Group` that represents the transformation
  35431. * of a XR controller in hand space. The requested controller is defined
  35432. * by the given index.
  35433. *
  35434. * @param {number} index - The index of the XR controller.
  35435. * @return {Group} A group that represents the controller's transformation.
  35436. */
  35437. getHand( index ) {
  35438. const controller = this._getController( index );
  35439. return controller.getHandSpace();
  35440. }
  35441. /**
  35442. * Returns the foveation value.
  35443. *
  35444. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  35445. */
  35446. getFoveation() {
  35447. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  35448. return undefined;
  35449. }
  35450. return this._foveation;
  35451. }
  35452. /**
  35453. * Sets the foveation value.
  35454. *
  35455. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  35456. * and `1` means maximum foveation (the edges render at lower resolution).
  35457. */
  35458. setFoveation( foveation ) {
  35459. this._foveation = foveation;
  35460. if ( this._glProjLayer !== null ) {
  35461. this._glProjLayer.fixedFoveation = foveation;
  35462. }
  35463. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  35464. this._glBaseLayer.fixedFoveation = foveation;
  35465. }
  35466. }
  35467. /**
  35468. * Returns the framebuffer scale factor.
  35469. *
  35470. * @return {number} The framebuffer scale factor.
  35471. */
  35472. getFramebufferScaleFactor() {
  35473. return this._framebufferScaleFactor;
  35474. }
  35475. /**
  35476. * Sets the framebuffer scale factor.
  35477. *
  35478. * This method can not be used during a XR session.
  35479. *
  35480. * @param {number} factor - The framebuffer scale factor.
  35481. */
  35482. setFramebufferScaleFactor( factor ) {
  35483. this._framebufferScaleFactor = factor;
  35484. if ( this.isPresenting === true ) {
  35485. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  35486. }
  35487. }
  35488. /**
  35489. * Returns the reference space type.
  35490. *
  35491. * @return {XRReferenceSpaceType} The reference space type.
  35492. */
  35493. getReferenceSpaceType() {
  35494. return this._referenceSpaceType;
  35495. }
  35496. /**
  35497. * Sets the reference space type.
  35498. *
  35499. * This method can not be used during a XR session.
  35500. *
  35501. * @param {XRReferenceSpaceType} type - The reference space type.
  35502. */
  35503. setReferenceSpaceType( type ) {
  35504. this._referenceSpaceType = type;
  35505. if ( this.isPresenting === true ) {
  35506. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  35507. }
  35508. }
  35509. /**
  35510. * Returns the XR reference space.
  35511. *
  35512. * @return {XRReferenceSpace} The XR reference space.
  35513. */
  35514. getReferenceSpace() {
  35515. return this._customReferenceSpace || this._referenceSpace;
  35516. }
  35517. /**
  35518. * Sets a custom XR reference space.
  35519. *
  35520. * @param {XRReferenceSpace} space - The XR reference space.
  35521. */
  35522. setReferenceSpace( space ) {
  35523. this._customReferenceSpace = space;
  35524. }
  35525. /**
  35526. * Returns the XR camera.
  35527. *
  35528. * @return {ArrayCamera} The XR camera.
  35529. */
  35530. getCamera() {
  35531. return this._cameraXR;
  35532. }
  35533. /**
  35534. * Returns the environment blend mode from the current XR session.
  35535. *
  35536. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  35537. */
  35538. getEnvironmentBlendMode() {
  35539. if ( this._session !== null ) {
  35540. return this._session.environmentBlendMode;
  35541. }
  35542. }
  35543. /**
  35544. * Returns the current XR frame.
  35545. *
  35546. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  35547. */
  35548. getFrame() {
  35549. return this._xrFrame;
  35550. }
  35551. /**
  35552. * Returns `true` if the engine renders to a multiview target.
  35553. *
  35554. * @return {boolean} Whether the engine renders to a multiview render target or not.
  35555. */
  35556. useMultiview() {
  35557. return this._useMultiview;
  35558. }
  35559. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = [] ) {
  35560. const geometry = new PlaneGeometry( width, height );
  35561. const renderTarget = new XRRenderTarget(
  35562. pixelwidth,
  35563. pixelheight,
  35564. {
  35565. format: RGBAFormat,
  35566. type: UnsignedByteType,
  35567. depthTexture: new DepthTexture(
  35568. pixelwidth,
  35569. pixelheight,
  35570. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  35571. undefined,
  35572. undefined,
  35573. undefined,
  35574. undefined,
  35575. undefined,
  35576. undefined,
  35577. attributes.stencil ? DepthStencilFormat : DepthFormat
  35578. ),
  35579. stencilBuffer: attributes.stencil,
  35580. resolveDepthBuffer: false,
  35581. resolveStencilBuffer: false
  35582. } );
  35583. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  35584. material.map = renderTarget.texture;
  35585. material.map.offset.y = 1;
  35586. material.map.repeat.y = -1;
  35587. const plane = new Mesh( geometry, material );
  35588. plane.position.copy( translation );
  35589. plane.quaternion.copy( quaternion );
  35590. const layer = {
  35591. type: 'quad',
  35592. width: width,
  35593. height: height,
  35594. translation: translation,
  35595. quaternion: quaternion,
  35596. pixelwidth: pixelwidth,
  35597. pixelheight: pixelheight,
  35598. plane: plane,
  35599. material: material,
  35600. rendercall: rendercall,
  35601. renderTarget: renderTarget };
  35602. this._layers.push( layer );
  35603. if ( this._session !== null ) {
  35604. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  35605. layer.plane.material.blending = CustomBlending;
  35606. layer.plane.material.blendEquation = AddEquation;
  35607. layer.plane.material.blendSrc = ZeroFactor;
  35608. layer.plane.material.blendDst = ZeroFactor;
  35609. layer.xrlayer = this._createXRLayer( layer );
  35610. const xrlayers = this._session.renderState.layers;
  35611. xrlayers.unshift( layer.xrlayer );
  35612. this._session.updateRenderState( { layers: xrlayers } );
  35613. } else {
  35614. renderTarget.isXRRenderTarget = false;
  35615. }
  35616. return plane;
  35617. }
  35618. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = [] ) {
  35619. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  35620. const renderTarget = new XRRenderTarget(
  35621. pixelwidth,
  35622. pixelheight,
  35623. {
  35624. format: RGBAFormat,
  35625. type: UnsignedByteType,
  35626. depthTexture: new DepthTexture(
  35627. pixelwidth,
  35628. pixelheight,
  35629. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  35630. undefined,
  35631. undefined,
  35632. undefined,
  35633. undefined,
  35634. undefined,
  35635. undefined,
  35636. attributes.stencil ? DepthStencilFormat : DepthFormat
  35637. ),
  35638. stencilBuffer: attributes.stencil,
  35639. resolveDepthBuffer: false,
  35640. resolveStencilBuffer: false
  35641. } );
  35642. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  35643. material.map = renderTarget.texture;
  35644. material.map.offset.y = 1;
  35645. material.map.repeat.y = -1;
  35646. const plane = new Mesh( geometry, material );
  35647. plane.position.copy( translation );
  35648. plane.quaternion.copy( quaternion );
  35649. const layer = {
  35650. type: 'cylinder',
  35651. radius: radius,
  35652. centralAngle: centralAngle,
  35653. aspectratio: aspectratio,
  35654. translation: translation,
  35655. quaternion: quaternion,
  35656. pixelwidth: pixelwidth,
  35657. pixelheight: pixelheight,
  35658. plane: plane,
  35659. material: material,
  35660. rendercall: rendercall,
  35661. renderTarget: renderTarget };
  35662. this._layers.push( layer );
  35663. if ( this._session !== null ) {
  35664. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  35665. layer.plane.material.blending = CustomBlending;
  35666. layer.plane.material.blendEquation = AddEquation;
  35667. layer.plane.material.blendSrc = ZeroFactor;
  35668. layer.plane.material.blendDst = ZeroFactor;
  35669. layer.xrlayer = this._createXRLayer( layer );
  35670. const xrlayers = this._session.renderState.layers;
  35671. xrlayers.unshift( layer.xrlayer );
  35672. this._session.updateRenderState( { layers: xrlayers } );
  35673. } else {
  35674. renderTarget.isXRRenderTarget = false;
  35675. }
  35676. return plane;
  35677. }
  35678. renderLayers( ) {
  35679. const translationObject = new Vector3();
  35680. const quaternionObject = new Quaternion();
  35681. const wasPresenting = this.isPresenting;
  35682. this.isPresenting = false;
  35683. for ( const layer of this._layers ) {
  35684. layer.renderTarget.isXRRenderTarget = this._session !== null;
  35685. layer.renderTarget.hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  35686. layer.renderTarget.autoAllocateDepthBuffer = ! layer.renderTarget.isXRRenderTarget;
  35687. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  35688. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  35689. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  35690. this._renderer.backend.setXRRenderTargetTextures(
  35691. layer.renderTarget,
  35692. glSubImage.colorTexture,
  35693. glSubImage.depthStencilTexture );
  35694. }
  35695. this._renderer.setRenderTarget( layer.renderTarget );
  35696. layer.rendercall();
  35697. }
  35698. this.isPresenting = wasPresenting;
  35699. this._renderer.setRenderTarget( null );
  35700. }
  35701. /**
  35702. * Returns the current XR session.
  35703. *
  35704. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  35705. */
  35706. getSession() {
  35707. return this._session;
  35708. }
  35709. /**
  35710. * After a XR session has been requested usually with one of the `*Button` modules, it
  35711. * is injected into the renderer with this method. This method triggers the start of
  35712. * the actual XR rendering.
  35713. *
  35714. * @async
  35715. * @param {XRSession} session - The XR session to set.
  35716. * @return {Promise} A Promise that resolves when the session has been set.
  35717. */
  35718. async setSession( session ) {
  35719. const renderer = this._renderer;
  35720. const backend = renderer.backend;
  35721. this._gl = renderer.getContext();
  35722. const gl = this._gl;
  35723. const attributes = gl.getContextAttributes();
  35724. this._session = session;
  35725. if ( session !== null ) {
  35726. 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.' );
  35727. session.addEventListener( 'select', this._onSessionEvent );
  35728. session.addEventListener( 'selectstart', this._onSessionEvent );
  35729. session.addEventListener( 'selectend', this._onSessionEvent );
  35730. session.addEventListener( 'squeeze', this._onSessionEvent );
  35731. session.addEventListener( 'squeezestart', this._onSessionEvent );
  35732. session.addEventListener( 'squeezeend', this._onSessionEvent );
  35733. session.addEventListener( 'end', this._onSessionEnd );
  35734. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  35735. await backend.makeXRCompatible();
  35736. this._currentPixelRatio = renderer.getPixelRatio();
  35737. renderer.getSize( this._currentSize );
  35738. this._currentAnimationContext = renderer._animation.getContext();
  35739. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  35740. renderer._animation.stop();
  35741. //
  35742. if ( this._useLayers === true ) {
  35743. // default path using XRWebGLBinding/XRProjectionLayer
  35744. let depthFormat = null;
  35745. let depthType = null;
  35746. let glDepthFormat = null;
  35747. if ( renderer.depth ) {
  35748. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  35749. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  35750. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  35751. }
  35752. const projectionlayerInit = {
  35753. colorFormat: gl.RGBA8,
  35754. depthFormat: glDepthFormat,
  35755. scaleFactor: this._framebufferScaleFactor
  35756. };
  35757. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  35758. projectionlayerInit.textureType = 'texture-array';
  35759. this._useMultiview = true;
  35760. }
  35761. const glBinding = new XRWebGLBinding( session, gl );
  35762. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  35763. const layersArray = [ glProjLayer ];
  35764. this._glBinding = glBinding;
  35765. this._glProjLayer = glProjLayer;
  35766. renderer.setPixelRatio( 1 );
  35767. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  35768. const depth = this._useMultiview ? 2 : 1;
  35769. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  35770. this._xrRenderTarget = new XRRenderTarget(
  35771. glProjLayer.textureWidth,
  35772. glProjLayer.textureHeight,
  35773. {
  35774. format: RGBAFormat,
  35775. type: UnsignedByteType,
  35776. colorSpace: renderer.outputColorSpace,
  35777. depthTexture: depthTexture,
  35778. stencilBuffer: renderer.stencil,
  35779. samples: attributes.antialias ? 4 : 0,
  35780. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  35781. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  35782. depth: this._useMultiview ? 2 : 1,
  35783. multiview: this._useMultiview
  35784. } );
  35785. this._xrRenderTarget.hasExternalTextures = true;
  35786. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  35787. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  35788. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  35789. if ( this._supportsLayers ) {
  35790. // switch layers to native
  35791. for ( const layer of this._layers ) {
  35792. // change material so it "punches" out a hole to show the XR Layer.
  35793. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  35794. layer.plane.material.blending = CustomBlending;
  35795. layer.plane.material.blendEquation = AddEquation;
  35796. layer.plane.material.blendSrc = ZeroFactor;
  35797. layer.plane.material.blendDst = ZeroFactor;
  35798. layer.xrlayer = this._createXRLayer( layer );
  35799. layersArray.unshift( layer.xrlayer );
  35800. }
  35801. }
  35802. session.updateRenderState( { layers: layersArray } );
  35803. } else {
  35804. // fallback to XRWebGLLayer
  35805. const layerInit = {
  35806. antialias: renderer.samples > 0,
  35807. alpha: true,
  35808. depth: renderer.depth,
  35809. stencil: renderer.stencil,
  35810. framebufferScaleFactor: this.getFramebufferScaleFactor()
  35811. };
  35812. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  35813. this._glBaseLayer = glBaseLayer;
  35814. session.updateRenderState( { baseLayer: glBaseLayer } );
  35815. renderer.setPixelRatio( 1 );
  35816. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  35817. this._xrRenderTarget = new XRRenderTarget(
  35818. glBaseLayer.framebufferWidth,
  35819. glBaseLayer.framebufferHeight,
  35820. {
  35821. format: RGBAFormat,
  35822. type: UnsignedByteType,
  35823. colorSpace: renderer.outputColorSpace,
  35824. stencilBuffer: renderer.stencil,
  35825. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  35826. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  35827. }
  35828. );
  35829. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  35830. }
  35831. //
  35832. this.setFoveation( this.getFoveation() );
  35833. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  35834. renderer._animation.setContext( session );
  35835. renderer._animation.start();
  35836. this.isPresenting = true;
  35837. this.dispatchEvent( { type: 'sessionstart' } );
  35838. }
  35839. }
  35840. /**
  35841. * This method is called by the renderer per frame and updates the XR camera
  35842. * and it sub cameras based on the given camera. The given camera is the "user"
  35843. * camera created on application level and used for non-XR rendering.
  35844. *
  35845. * @param {PerspectiveCamera} camera - The camera.
  35846. */
  35847. updateCamera( camera ) {
  35848. const session = this._session;
  35849. if ( session === null ) return;
  35850. const depthNear = camera.near;
  35851. const depthFar = camera.far;
  35852. const cameraXR = this._cameraXR;
  35853. const cameraL = this._cameraL;
  35854. const cameraR = this._cameraR;
  35855. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  35856. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  35857. cameraXR.isMultiViewCamera = this._useMultiview;
  35858. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  35859. // Note that the new renderState won't apply until the next frame. See #18320
  35860. session.updateRenderState( {
  35861. depthNear: cameraXR.near,
  35862. depthFar: cameraXR.far
  35863. } );
  35864. this._currentDepthNear = cameraXR.near;
  35865. this._currentDepthFar = cameraXR.far;
  35866. }
  35867. cameraL.layers.mask = camera.layers.mask | 0b010;
  35868. cameraR.layers.mask = camera.layers.mask | 0b100;
  35869. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  35870. const parent = camera.parent;
  35871. const cameras = cameraXR.cameras;
  35872. updateCamera( cameraXR, parent );
  35873. for ( let i = 0; i < cameras.length; i ++ ) {
  35874. updateCamera( cameras[ i ], parent );
  35875. }
  35876. // update projection matrix for proper view frustum culling
  35877. if ( cameras.length === 2 ) {
  35878. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  35879. } else {
  35880. // assume single camera setup (AR)
  35881. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  35882. }
  35883. // update user camera and its children
  35884. updateUserCamera( camera, cameraXR, parent );
  35885. }
  35886. /**
  35887. * Returns a WebXR controller for the given controller index.
  35888. *
  35889. * @private
  35890. * @param {number} index - The controller index.
  35891. * @return {WebXRController} The XR controller.
  35892. */
  35893. _getController( index ) {
  35894. let controller = this._controllers[ index ];
  35895. if ( controller === undefined ) {
  35896. controller = new WebXRController();
  35897. this._controllers[ index ] = controller;
  35898. }
  35899. return controller;
  35900. }
  35901. }
  35902. /**
  35903. * Assumes 2 cameras that are parallel and share an X-axis, and that
  35904. * the cameras' projection and world matrices have already been set.
  35905. * And that near and far planes are identical for both cameras.
  35906. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  35907. *
  35908. * @param {ArrayCamera} camera - The camera to update.
  35909. * @param {PerspectiveCamera} cameraL - The left camera.
  35910. * @param {PerspectiveCamera} cameraR - The right camera.
  35911. */
  35912. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  35913. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  35914. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  35915. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  35916. const projL = cameraL.projectionMatrix.elements;
  35917. const projR = cameraR.projectionMatrix.elements;
  35918. // VR systems will have identical far and near planes, and
  35919. // most likely identical top and bottom frustum extents.
  35920. // Use the left camera for these values.
  35921. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  35922. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  35923. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  35924. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  35925. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  35926. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  35927. const left = near * leftFov;
  35928. const right = near * rightFov;
  35929. // Calculate the new camera's position offset from the
  35930. // left camera. xOffset should be roughly half `ipd`.
  35931. const zOffset = ipd / ( - leftFov + rightFov );
  35932. const xOffset = zOffset * - leftFov;
  35933. // TODO: Better way to apply this offset?
  35934. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  35935. camera.translateX( xOffset );
  35936. camera.translateZ( zOffset );
  35937. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  35938. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  35939. // Check if the projection uses an infinite far plane.
  35940. if ( projL[ 10 ] === -1 ) {
  35941. // Use the projection matrix from the left eye.
  35942. // The camera offset is sufficient to include the view volumes
  35943. // of both eyes (assuming symmetric projections).
  35944. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  35945. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  35946. } else {
  35947. // Find the union of the frustum values of the cameras and scale
  35948. // the values so that the near plane's position does not change in world space,
  35949. // although must now be relative to the new union camera.
  35950. const near2 = near + zOffset;
  35951. const far2 = far + zOffset;
  35952. const left2 = left - xOffset;
  35953. const right2 = right + ( ipd - xOffset );
  35954. const top2 = topFov * far / far2 * near2;
  35955. const bottom2 = bottomFov * far / far2 * near2;
  35956. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  35957. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  35958. }
  35959. }
  35960. /**
  35961. * Updates the world matrices for the given camera based on the parent 3D object.
  35962. *
  35963. * @inner
  35964. * @param {Camera} camera - The camera to update.
  35965. * @param {Object3D} parent - The parent 3D object.
  35966. */
  35967. function updateCamera( camera, parent ) {
  35968. if ( parent === null ) {
  35969. camera.matrixWorld.copy( camera.matrix );
  35970. } else {
  35971. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  35972. }
  35973. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  35974. }
  35975. /**
  35976. * Updates the given camera with the transformation of the XR camera and parent object.
  35977. *
  35978. * @inner
  35979. * @param {Camera} camera - The camera to update.
  35980. * @param {ArrayCamera} cameraXR - The XR camera.
  35981. * @param {Object3D} parent - The parent 3D object.
  35982. */
  35983. function updateUserCamera( camera, cameraXR, parent ) {
  35984. if ( parent === null ) {
  35985. camera.matrix.copy( cameraXR.matrixWorld );
  35986. } else {
  35987. camera.matrix.copy( parent.matrixWorld );
  35988. camera.matrix.invert();
  35989. camera.matrix.multiply( cameraXR.matrixWorld );
  35990. }
  35991. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  35992. camera.updateMatrixWorld( true );
  35993. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  35994. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  35995. if ( camera.isPerspectiveCamera ) {
  35996. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  35997. camera.zoom = 1;
  35998. }
  35999. }
  36000. function onSessionEvent( event ) {
  36001. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  36002. if ( controllerIndex === -1 ) {
  36003. return;
  36004. }
  36005. const controller = this._controllers[ controllerIndex ];
  36006. if ( controller !== undefined ) {
  36007. const referenceSpace = this.getReferenceSpace();
  36008. controller.update( event.inputSource, event.frame, referenceSpace );
  36009. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  36010. }
  36011. }
  36012. function onSessionEnd() {
  36013. const session = this._session;
  36014. const renderer = this._renderer;
  36015. session.removeEventListener( 'select', this._onSessionEvent );
  36016. session.removeEventListener( 'selectstart', this._onSessionEvent );
  36017. session.removeEventListener( 'selectend', this._onSessionEvent );
  36018. session.removeEventListener( 'squeeze', this._onSessionEvent );
  36019. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  36020. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  36021. session.removeEventListener( 'end', this._onSessionEnd );
  36022. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  36023. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36024. const inputSource = this._controllerInputSources[ i ];
  36025. if ( inputSource === null ) continue;
  36026. this._controllerInputSources[ i ] = null;
  36027. this._controllers[ i ].disconnect( inputSource );
  36028. }
  36029. this._currentDepthNear = null;
  36030. this._currentDepthFar = null;
  36031. // restore framebuffer/rendering state
  36032. renderer.backend.setXRTarget( null );
  36033. renderer.setOutputRenderTarget( null );
  36034. renderer.setRenderTarget( null );
  36035. this._session = null;
  36036. this._xrRenderTarget = null;
  36037. // switch layers back to emulated
  36038. if ( this._supportsLayers === true ) {
  36039. for ( const layer of this._layers ) {
  36040. // Recreate layer render target to reset state
  36041. layer.renderTarget = new XRRenderTarget(
  36042. layer.pixelwidth,
  36043. layer.pixelheight,
  36044. {
  36045. format: RGBAFormat,
  36046. type: UnsignedByteType,
  36047. depthTexture: new DepthTexture(
  36048. layer.pixelwidth,
  36049. layer.pixelheight,
  36050. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  36051. undefined,
  36052. undefined,
  36053. undefined,
  36054. undefined,
  36055. undefined,
  36056. undefined,
  36057. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  36058. ),
  36059. stencilBuffer: layer.stencilBuffer,
  36060. resolveDepthBuffer: false,
  36061. resolveStencilBuffer: false
  36062. } );
  36063. layer.renderTarget.isXRRenderTarget = false;
  36064. layer.plane.material = layer.material;
  36065. layer.material.map = layer.renderTarget.texture;
  36066. delete layer.xrlayer;
  36067. }
  36068. }
  36069. //
  36070. this.isPresenting = false;
  36071. this._useMultiview = false;
  36072. renderer._animation.stop();
  36073. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  36074. renderer._animation.setContext( this._currentAnimationContext );
  36075. renderer._animation.start();
  36076. renderer.setPixelRatio( this._currentPixelRatio );
  36077. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  36078. this.dispatchEvent( { type: 'sessionend' } );
  36079. }
  36080. function onInputSourcesChange( event ) {
  36081. const controllers = this._controllers;
  36082. const controllerInputSources = this._controllerInputSources;
  36083. // Notify disconnected
  36084. for ( let i = 0; i < event.removed.length; i ++ ) {
  36085. const inputSource = event.removed[ i ];
  36086. const index = controllerInputSources.indexOf( inputSource );
  36087. if ( index >= 0 ) {
  36088. controllerInputSources[ index ] = null;
  36089. controllers[ index ].disconnect( inputSource );
  36090. }
  36091. }
  36092. // Notify connected
  36093. for ( let i = 0; i < event.added.length; i ++ ) {
  36094. const inputSource = event.added[ i ];
  36095. let controllerIndex = controllerInputSources.indexOf( inputSource );
  36096. if ( controllerIndex === -1 ) {
  36097. // Assign input source a controller that currently has no input source
  36098. for ( let i = 0; i < controllers.length; i ++ ) {
  36099. if ( i >= controllerInputSources.length ) {
  36100. controllerInputSources.push( inputSource );
  36101. controllerIndex = i;
  36102. break;
  36103. } else if ( controllerInputSources[ i ] === null ) {
  36104. controllerInputSources[ i ] = inputSource;
  36105. controllerIndex = i;
  36106. break;
  36107. }
  36108. }
  36109. // If all controllers do currently receive input we ignore new ones
  36110. if ( controllerIndex === -1 ) break;
  36111. }
  36112. const controller = controllers[ controllerIndex ];
  36113. if ( controller ) {
  36114. controller.connect( inputSource );
  36115. }
  36116. }
  36117. }
  36118. // Creation method for native WebXR layers
  36119. function createXRLayer( layer ) {
  36120. if ( layer.type === 'quad' ) {
  36121. return this._glBinding.createQuadLayer( {
  36122. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36123. depthFormat: this._gl.DEPTH_COMPONENT,
  36124. width: layer.width / 2,
  36125. height: layer.height / 2,
  36126. space: this._referenceSpace,
  36127. viewPixelWidth: layer.pixelwidth,
  36128. viewPixelHeight: layer.pixelheight
  36129. } );
  36130. } else {
  36131. return this._glBinding.createCylinderLayer( {
  36132. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36133. depthFormat: this._gl.DEPTH_COMPONENT,
  36134. radius: layer.radius,
  36135. centralAngle: layer.centralAngle,
  36136. aspectRatio: layer.aspectRatio,
  36137. space: this._referenceSpace,
  36138. viewPixelWidth: layer.pixelwidth,
  36139. viewPixelHeight: layer.pixelheight
  36140. } );
  36141. }
  36142. }
  36143. // Animation Loop
  36144. function onAnimationFrame( time, frame ) {
  36145. if ( frame === undefined ) return;
  36146. const cameraXR = this._cameraXR;
  36147. const renderer = this._renderer;
  36148. const backend = renderer.backend;
  36149. const glBaseLayer = this._glBaseLayer;
  36150. const referenceSpace = this.getReferenceSpace();
  36151. const pose = frame.getViewerPose( referenceSpace );
  36152. this._xrFrame = frame;
  36153. if ( pose !== null ) {
  36154. const views = pose.views;
  36155. if ( this._glBaseLayer !== null ) {
  36156. backend.setXRTarget( glBaseLayer.framebuffer );
  36157. }
  36158. let cameraXRNeedsUpdate = false;
  36159. // check if it's necessary to rebuild cameraXR's camera list
  36160. if ( views.length !== cameraXR.cameras.length ) {
  36161. cameraXR.cameras.length = 0;
  36162. cameraXRNeedsUpdate = true;
  36163. }
  36164. for ( let i = 0; i < views.length; i ++ ) {
  36165. const view = views[ i ];
  36166. let viewport;
  36167. if ( this._useLayers === true ) {
  36168. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  36169. viewport = glSubImage.viewport;
  36170. // For side-by-side projection, we only produce a single texture for both eyes.
  36171. if ( i === 0 ) {
  36172. backend.setXRRenderTargetTextures(
  36173. this._xrRenderTarget,
  36174. glSubImage.colorTexture,
  36175. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  36176. );
  36177. }
  36178. } else {
  36179. viewport = glBaseLayer.getViewport( view );
  36180. }
  36181. let camera = this._cameras[ i ];
  36182. if ( camera === undefined ) {
  36183. camera = new PerspectiveCamera();
  36184. camera.layers.enable( i );
  36185. camera.viewport = new Vector4();
  36186. this._cameras[ i ] = camera;
  36187. }
  36188. camera.matrix.fromArray( view.transform.matrix );
  36189. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36190. camera.projectionMatrix.fromArray( view.projectionMatrix );
  36191. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36192. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  36193. if ( i === 0 ) {
  36194. cameraXR.matrix.copy( camera.matrix );
  36195. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  36196. }
  36197. if ( cameraXRNeedsUpdate === true ) {
  36198. cameraXR.cameras.push( camera );
  36199. }
  36200. }
  36201. renderer.setOutputRenderTarget( this._xrRenderTarget );
  36202. }
  36203. //
  36204. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36205. const inputSource = this._controllerInputSources[ i ];
  36206. const controller = this._controllers[ i ];
  36207. if ( inputSource !== null && controller !== undefined ) {
  36208. controller.update( inputSource, frame, referenceSpace );
  36209. }
  36210. }
  36211. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  36212. if ( frame.detectedPlanes ) {
  36213. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  36214. }
  36215. this._xrFrame = null;
  36216. }
  36217. const _scene = /*@__PURE__*/ new Scene();
  36218. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  36219. const _screen = /*@__PURE__*/ new Vector4();
  36220. const _frustum = /*@__PURE__*/ new Frustum();
  36221. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  36222. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  36223. const _vector4 = /*@__PURE__*/ new Vector4();
  36224. /**
  36225. * Base class for renderers.
  36226. */
  36227. class Renderer {
  36228. /**
  36229. * Renderer options.
  36230. *
  36231. * @typedef {Object} Renderer~Options
  36232. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  36233. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  36234. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  36235. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  36236. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  36237. * @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
  36238. * to overwrite the default.
  36239. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36240. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  36241. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  36242. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  36243. */
  36244. /**
  36245. * Constructs a new renderer.
  36246. *
  36247. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  36248. * @param {Renderer~Options} [parameters] - The configuration parameter.
  36249. */
  36250. constructor( backend, parameters = {} ) {
  36251. /**
  36252. * This flag can be used for type testing.
  36253. *
  36254. * @type {boolean}
  36255. * @readonly
  36256. * @default true
  36257. */
  36258. this.isRenderer = true;
  36259. //
  36260. const {
  36261. logarithmicDepthBuffer = false,
  36262. alpha = true,
  36263. depth = true,
  36264. stencil = false,
  36265. antialias = false,
  36266. samples = 0,
  36267. getFallback = null,
  36268. colorBufferType = HalfFloatType,
  36269. multiview = false
  36270. } = parameters;
  36271. /**
  36272. * A reference to the canvas element the renderer is drawing to.
  36273. * This value of this property will automatically be created by
  36274. * the renderer.
  36275. *
  36276. * @type {HTMLCanvasElement|OffscreenCanvas}
  36277. */
  36278. this.domElement = backend.getDomElement();
  36279. /**
  36280. * A reference to the current backend.
  36281. *
  36282. * @type {Backend}
  36283. */
  36284. this.backend = backend;
  36285. /**
  36286. * The number of MSAA samples.
  36287. *
  36288. * @type {number}
  36289. * @default 0
  36290. */
  36291. this.samples = samples || ( antialias === true ) ? 4 : 0;
  36292. /**
  36293. * Whether the renderer should automatically clear the current rendering target
  36294. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  36295. * or the current bound render target (custom framebuffer).
  36296. *
  36297. * @type {boolean}
  36298. * @default true
  36299. */
  36300. this.autoClear = true;
  36301. /**
  36302. * When `autoClear` is set to `true`, this property defines whether the renderer
  36303. * should clear the color buffer.
  36304. *
  36305. * @type {boolean}
  36306. * @default true
  36307. */
  36308. this.autoClearColor = true;
  36309. /**
  36310. * When `autoClear` is set to `true`, this property defines whether the renderer
  36311. * should clear the depth buffer.
  36312. *
  36313. * @type {boolean}
  36314. * @default true
  36315. */
  36316. this.autoClearDepth = true;
  36317. /**
  36318. * When `autoClear` is set to `true`, this property defines whether the renderer
  36319. * should clear the stencil buffer.
  36320. *
  36321. * @type {boolean}
  36322. * @default true
  36323. */
  36324. this.autoClearStencil = true;
  36325. /**
  36326. * Whether the default framebuffer should be transparent or opaque.
  36327. *
  36328. * @type {boolean}
  36329. * @default true
  36330. */
  36331. this.alpha = alpha;
  36332. /**
  36333. * Whether logarithmic depth buffer is enabled or not.
  36334. *
  36335. * @type {boolean}
  36336. * @default false
  36337. */
  36338. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  36339. /**
  36340. * Defines the output color space of the renderer.
  36341. *
  36342. * @type {string}
  36343. * @default SRGBColorSpace
  36344. */
  36345. this.outputColorSpace = SRGBColorSpace;
  36346. /**
  36347. * Defines the tone mapping of the renderer.
  36348. *
  36349. * @type {number}
  36350. * @default NoToneMapping
  36351. */
  36352. this.toneMapping = NoToneMapping;
  36353. /**
  36354. * Defines the tone mapping exposure.
  36355. *
  36356. * @type {number}
  36357. * @default 1
  36358. */
  36359. this.toneMappingExposure = 1.0;
  36360. /**
  36361. * Whether the renderer should sort its render lists or not.
  36362. *
  36363. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  36364. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  36365. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  36366. * e.g. manually determining each object's rendering order.
  36367. *
  36368. * @type {boolean}
  36369. * @default true
  36370. */
  36371. this.sortObjects = true;
  36372. /**
  36373. * Whether the default framebuffer should have a depth buffer or not.
  36374. *
  36375. * @type {boolean}
  36376. * @default true
  36377. */
  36378. this.depth = depth;
  36379. /**
  36380. * Whether the default framebuffer should have a stencil buffer or not.
  36381. *
  36382. * @type {boolean}
  36383. * @default false
  36384. */
  36385. this.stencil = stencil;
  36386. /**
  36387. * Holds a series of statistical information about the GPU memory
  36388. * and the rendering process. Useful for debugging and monitoring.
  36389. *
  36390. * @type {Info}
  36391. */
  36392. this.info = new Info();
  36393. /**
  36394. * Stores override nodes for specific transformations or calculations.
  36395. * These nodes can be used to replace default behavior in the rendering pipeline.
  36396. *
  36397. * @type {Object}
  36398. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  36399. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  36400. */
  36401. this.overrideNodes = {
  36402. modelViewMatrix: null,
  36403. modelNormalViewMatrix: null
  36404. };
  36405. /**
  36406. * The node library defines how certain library objects like materials, lights
  36407. * or tone mapping functions are mapped to node types. This is required since
  36408. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  36409. * be part of the scene graph, they are internally represented as nodes for
  36410. * further processing.
  36411. *
  36412. * @type {NodeLibrary}
  36413. */
  36414. this.library = new NodeLibrary();
  36415. /**
  36416. * A map-like data structure for managing lights.
  36417. *
  36418. * @type {Lighting}
  36419. */
  36420. this.lighting = new Lighting();
  36421. // internals
  36422. /**
  36423. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36424. *
  36425. * @private
  36426. * @type {?Function}
  36427. */
  36428. this._getFallback = getFallback;
  36429. /**
  36430. * The renderer's pixel ratio.
  36431. *
  36432. * @private
  36433. * @type {number}
  36434. * @default 1
  36435. */
  36436. this._pixelRatio = 1;
  36437. /**
  36438. * The width of the renderer's default framebuffer in logical pixel unit.
  36439. *
  36440. * @private
  36441. * @type {number}
  36442. */
  36443. this._width = this.domElement.width;
  36444. /**
  36445. * The height of the renderer's default framebuffer in logical pixel unit.
  36446. *
  36447. * @private
  36448. * @type {number}
  36449. */
  36450. this._height = this.domElement.height;
  36451. /**
  36452. * The viewport of the renderer in logical pixel unit.
  36453. *
  36454. * @private
  36455. * @type {Vector4}
  36456. */
  36457. this._viewport = new Vector4( 0, 0, this._width, this._height );
  36458. /**
  36459. * The scissor rectangle of the renderer in logical pixel unit.
  36460. *
  36461. * @private
  36462. * @type {Vector4}
  36463. */
  36464. this._scissor = new Vector4( 0, 0, this._width, this._height );
  36465. /**
  36466. * Whether the scissor test should be enabled or not.
  36467. *
  36468. * @private
  36469. * @type {boolean}
  36470. */
  36471. this._scissorTest = false;
  36472. /**
  36473. * A reference to a renderer module for managing shader attributes.
  36474. *
  36475. * @private
  36476. * @type {?Attributes}
  36477. * @default null
  36478. */
  36479. this._attributes = null;
  36480. /**
  36481. * A reference to a renderer module for managing geometries.
  36482. *
  36483. * @private
  36484. * @type {?Geometries}
  36485. * @default null
  36486. */
  36487. this._geometries = null;
  36488. /**
  36489. * A reference to a renderer module for managing node related logic.
  36490. *
  36491. * @private
  36492. * @type {?Nodes}
  36493. * @default null
  36494. */
  36495. this._nodes = null;
  36496. /**
  36497. * A reference to a renderer module for managing the internal animation loop.
  36498. *
  36499. * @private
  36500. * @type {?Animation}
  36501. * @default null
  36502. */
  36503. this._animation = null;
  36504. /**
  36505. * A reference to a renderer module for managing shader program bindings.
  36506. *
  36507. * @private
  36508. * @type {?Bindings}
  36509. * @default null
  36510. */
  36511. this._bindings = null;
  36512. /**
  36513. * A reference to a renderer module for managing render objects.
  36514. *
  36515. * @private
  36516. * @type {?RenderObjects}
  36517. * @default null
  36518. */
  36519. this._objects = null;
  36520. /**
  36521. * A reference to a renderer module for managing render and compute pipelines.
  36522. *
  36523. * @private
  36524. * @type {?Pipelines}
  36525. * @default null
  36526. */
  36527. this._pipelines = null;
  36528. /**
  36529. * A reference to a renderer module for managing render bundles.
  36530. *
  36531. * @private
  36532. * @type {?RenderBundles}
  36533. * @default null
  36534. */
  36535. this._bundles = null;
  36536. /**
  36537. * A reference to a renderer module for managing render lists.
  36538. *
  36539. * @private
  36540. * @type {?RenderLists}
  36541. * @default null
  36542. */
  36543. this._renderLists = null;
  36544. /**
  36545. * A reference to a renderer module for managing render contexts.
  36546. *
  36547. * @private
  36548. * @type {?RenderContexts}
  36549. * @default null
  36550. */
  36551. this._renderContexts = null;
  36552. /**
  36553. * A reference to a renderer module for managing textures.
  36554. *
  36555. * @private
  36556. * @type {?Textures}
  36557. * @default null
  36558. */
  36559. this._textures = null;
  36560. /**
  36561. * A reference to a renderer module for backgrounds.
  36562. *
  36563. * @private
  36564. * @type {?Background}
  36565. * @default null
  36566. */
  36567. this._background = null;
  36568. /**
  36569. * This fullscreen quad is used for internal render passes
  36570. * like the tone mapping and color space output pass.
  36571. *
  36572. * @private
  36573. * @type {QuadMesh}
  36574. */
  36575. this._quad = new QuadMesh( new NodeMaterial() );
  36576. this._quad.material.name = 'Renderer_output';
  36577. /**
  36578. * A reference to the current render context.
  36579. *
  36580. * @private
  36581. * @type {?RenderContext}
  36582. * @default null
  36583. */
  36584. this._currentRenderContext = null;
  36585. /**
  36586. * A custom sort function for the opaque render list.
  36587. *
  36588. * @private
  36589. * @type {?Function}
  36590. * @default null
  36591. */
  36592. this._opaqueSort = null;
  36593. /**
  36594. * A custom sort function for the transparent render list.
  36595. *
  36596. * @private
  36597. * @type {?Function}
  36598. * @default null
  36599. */
  36600. this._transparentSort = null;
  36601. /**
  36602. * The framebuffer target.
  36603. *
  36604. * @private
  36605. * @type {?RenderTarget}
  36606. * @default null
  36607. */
  36608. this._frameBufferTarget = null;
  36609. const alphaClear = this.alpha === true ? 0 : 1;
  36610. /**
  36611. * The clear color value.
  36612. *
  36613. * @private
  36614. * @type {Color4}
  36615. */
  36616. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  36617. /**
  36618. * The clear depth value.
  36619. *
  36620. * @private
  36621. * @type {number}
  36622. * @default 1
  36623. */
  36624. this._clearDepth = 1;
  36625. /**
  36626. * The clear stencil value.
  36627. *
  36628. * @private
  36629. * @type {number}
  36630. * @default 0
  36631. */
  36632. this._clearStencil = 0;
  36633. /**
  36634. * The current render target.
  36635. *
  36636. * @private
  36637. * @type {?RenderTarget}
  36638. * @default null
  36639. */
  36640. this._renderTarget = null;
  36641. /**
  36642. * The active cube face.
  36643. *
  36644. * @private
  36645. * @type {number}
  36646. * @default 0
  36647. */
  36648. this._activeCubeFace = 0;
  36649. /**
  36650. * The active mipmap level.
  36651. *
  36652. * @private
  36653. * @type {number}
  36654. * @default 0
  36655. */
  36656. this._activeMipmapLevel = 0;
  36657. /**
  36658. * The current output render target.
  36659. *
  36660. * @private
  36661. * @type {?RenderTarget}
  36662. * @default null
  36663. */
  36664. this._outputRenderTarget = null;
  36665. /**
  36666. * The MRT setting.
  36667. *
  36668. * @private
  36669. * @type {?MRTNode}
  36670. * @default null
  36671. */
  36672. this._mrt = null;
  36673. /**
  36674. * This function defines how a render object is going
  36675. * to be rendered.
  36676. *
  36677. * @private
  36678. * @type {?Function}
  36679. * @default null
  36680. */
  36681. this._renderObjectFunction = null;
  36682. /**
  36683. * Used to keep track of the current render object function.
  36684. *
  36685. * @private
  36686. * @type {?Function}
  36687. * @default null
  36688. */
  36689. this._currentRenderObjectFunction = null;
  36690. /**
  36691. * Used to keep track of the current render bundle.
  36692. *
  36693. * @private
  36694. * @type {?RenderBundle}
  36695. * @default null
  36696. */
  36697. this._currentRenderBundle = null;
  36698. /**
  36699. * Next to `_renderObjectFunction()`, this function provides another hook
  36700. * for influencing the render process of a render object. It is meant for internal
  36701. * use and only relevant for `compileAsync()` right now. Instead of using
  36702. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  36703. * a different function might be used which performs no draw but just the node
  36704. * and pipeline updates.
  36705. *
  36706. * @private
  36707. * @type {?Function}
  36708. * @default null
  36709. */
  36710. this._handleObjectFunction = this._renderObjectDirect;
  36711. /**
  36712. * Indicates whether the device has been lost or not. In WebGL terms, the device
  36713. * lost is considered as a context lost. When this is set to `true`, rendering
  36714. * isn't possible anymore.
  36715. *
  36716. * @private
  36717. * @type {boolean}
  36718. * @default false
  36719. */
  36720. this._isDeviceLost = false;
  36721. /**
  36722. * A callback function that defines what should happen when a device/context lost occurs.
  36723. *
  36724. * @type {Function}
  36725. */
  36726. this.onDeviceLost = this._onDeviceLost;
  36727. /**
  36728. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  36729. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  36730. * This will reduce rendering quality though.
  36731. *
  36732. * @private
  36733. * @type {number}
  36734. * @default HalfFloatType
  36735. */
  36736. this._colorBufferType = colorBufferType;
  36737. /**
  36738. * Whether the renderer has been initialized or not.
  36739. *
  36740. * @private
  36741. * @type {boolean}
  36742. * @default false
  36743. */
  36744. this._initialized = false;
  36745. /**
  36746. * A reference to the promise which initializes the renderer.
  36747. *
  36748. * @private
  36749. * @type {?Promise<this>}
  36750. * @default null
  36751. */
  36752. this._initPromise = null;
  36753. /**
  36754. * An array of compilation promises which are used in `compileAsync()`.
  36755. *
  36756. * @private
  36757. * @type {?Array<Promise>}
  36758. * @default null
  36759. */
  36760. this._compilationPromises = null;
  36761. /**
  36762. * Whether the renderer should render transparent render objects or not.
  36763. *
  36764. * @type {boolean}
  36765. * @default true
  36766. */
  36767. this.transparent = true;
  36768. /**
  36769. * Whether the renderer should render opaque render objects or not.
  36770. *
  36771. * @type {boolean}
  36772. * @default true
  36773. */
  36774. this.opaque = true;
  36775. /**
  36776. * Shadow map configuration
  36777. * @typedef {Object} ShadowMapConfig
  36778. * @property {boolean} enabled - Whether to globally enable shadows or not.
  36779. * @property {number} type - The shadow map type.
  36780. */
  36781. /**
  36782. * The renderer's shadow configuration.
  36783. *
  36784. * @type {ShadowMapConfig}
  36785. */
  36786. this.shadowMap = {
  36787. enabled: false,
  36788. type: PCFShadowMap
  36789. };
  36790. /**
  36791. * XR configuration.
  36792. * @typedef {Object} XRConfig
  36793. * @property {boolean} enabled - Whether to globally enable XR or not.
  36794. */
  36795. /**
  36796. * The renderer's XR manager.
  36797. *
  36798. * @type {XRManager}
  36799. */
  36800. this.xr = new XRManager( this, multiview );
  36801. /**
  36802. * Debug configuration.
  36803. * @typedef {Object} DebugConfig
  36804. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  36805. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  36806. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  36807. */
  36808. /**
  36809. * The renderer's debug configuration.
  36810. *
  36811. * @type {DebugConfig}
  36812. */
  36813. this.debug = {
  36814. checkShaderErrors: true,
  36815. onShaderError: null,
  36816. getShaderAsync: async ( scene, camera, object ) => {
  36817. await this.compileAsync( scene, camera );
  36818. const renderList = this._renderLists.get( scene, camera );
  36819. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  36820. const material = scene.overrideMaterial || object.material;
  36821. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  36822. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  36823. return { fragmentShader, vertexShader };
  36824. }
  36825. };
  36826. }
  36827. /**
  36828. * Initializes the renderer so it is ready for usage.
  36829. *
  36830. * @async
  36831. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  36832. */
  36833. async init() {
  36834. if ( this._initialized ) {
  36835. throw new Error( 'Renderer: Backend has already been initialized.' );
  36836. }
  36837. if ( this._initPromise !== null ) {
  36838. return this._initPromise;
  36839. }
  36840. this._initPromise = new Promise( async ( resolve, reject ) => {
  36841. let backend = this.backend;
  36842. try {
  36843. await backend.init( this );
  36844. } catch ( error ) {
  36845. if ( this._getFallback !== null ) {
  36846. // try the fallback
  36847. try {
  36848. this.backend = backend = this._getFallback( error );
  36849. await backend.init( this );
  36850. } catch ( error ) {
  36851. reject( error );
  36852. return;
  36853. }
  36854. } else {
  36855. reject( error );
  36856. return;
  36857. }
  36858. }
  36859. this._nodes = new Nodes( this, backend );
  36860. this._animation = new Animation( this._nodes, this.info );
  36861. this._attributes = new Attributes( backend );
  36862. this._background = new Background( this, this._nodes );
  36863. this._geometries = new Geometries( this._attributes, this.info );
  36864. this._textures = new Textures( this, backend, this.info );
  36865. this._pipelines = new Pipelines( backend, this._nodes );
  36866. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  36867. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  36868. this._renderLists = new RenderLists( this.lighting );
  36869. this._bundles = new RenderBundles();
  36870. this._renderContexts = new RenderContexts();
  36871. //
  36872. this._animation.start();
  36873. this._initialized = true;
  36874. resolve( this );
  36875. } );
  36876. return this._initPromise;
  36877. }
  36878. /**
  36879. * The coordinate system of the renderer. The value of this property
  36880. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  36881. * `THREE.WebGPUCoordinateSystem`.
  36882. *
  36883. * @readonly
  36884. * @type {number}
  36885. */
  36886. get coordinateSystem() {
  36887. return this.backend.coordinateSystem;
  36888. }
  36889. /**
  36890. * Compiles all materials in the given scene. This can be useful to avoid a
  36891. * phenomenon which is called "shader compilation stutter", which occurs when
  36892. * rendering an object with a new shader for the first time.
  36893. *
  36894. * If you want to add a 3D object to an existing scene, use the third optional
  36895. * parameter for applying the target scene. Note that the (target) scene's lighting
  36896. * and environment must be configured before calling this method.
  36897. *
  36898. * @async
  36899. * @param {Object3D} scene - The scene or 3D object to precompile.
  36900. * @param {Camera} camera - The camera that is used to render the scene.
  36901. * @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.
  36902. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  36903. */
  36904. async compileAsync( scene, camera, targetScene = null ) {
  36905. if ( this._isDeviceLost === true ) return;
  36906. if ( this._initialized === false ) await this.init();
  36907. // preserve render tree
  36908. const nodeFrame = this._nodes.nodeFrame;
  36909. const previousRenderId = nodeFrame.renderId;
  36910. const previousRenderContext = this._currentRenderContext;
  36911. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  36912. const previousCompilationPromises = this._compilationPromises;
  36913. //
  36914. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  36915. if ( targetScene === null ) targetScene = scene;
  36916. const renderTarget = this._renderTarget;
  36917. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  36918. const activeMipmapLevel = this._activeMipmapLevel;
  36919. const compilationPromises = [];
  36920. this._currentRenderContext = renderContext;
  36921. this._currentRenderObjectFunction = this.renderObject;
  36922. this._handleObjectFunction = this._createObjectPipeline;
  36923. this._compilationPromises = compilationPromises;
  36924. nodeFrame.renderId ++;
  36925. //
  36926. nodeFrame.update();
  36927. //
  36928. renderContext.depth = this.depth;
  36929. renderContext.stencil = this.stencil;
  36930. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36931. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  36932. //
  36933. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36934. //
  36935. const renderList = this._renderLists.get( scene, camera );
  36936. renderList.begin();
  36937. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  36938. // include lights from target scene
  36939. if ( targetScene !== scene ) {
  36940. targetScene.traverseVisible( function ( object ) {
  36941. if ( object.isLight && object.layers.test( camera.layers ) ) {
  36942. renderList.pushLight( object );
  36943. }
  36944. } );
  36945. }
  36946. renderList.finish();
  36947. //
  36948. if ( renderTarget !== null ) {
  36949. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36950. const renderTargetData = this._textures.get( renderTarget );
  36951. renderContext.textures = renderTargetData.textures;
  36952. renderContext.depthTexture = renderTargetData.depthTexture;
  36953. } else {
  36954. renderContext.textures = null;
  36955. renderContext.depthTexture = null;
  36956. }
  36957. //
  36958. this._background.update( sceneRef, renderList, renderContext );
  36959. // process render lists
  36960. const opaqueObjects = renderList.opaque;
  36961. const transparentObjects = renderList.transparent;
  36962. const transparentDoublePassObjects = renderList.transparentDoublePass;
  36963. const lightsNode = renderList.lightsNode;
  36964. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36965. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  36966. // restore render tree
  36967. nodeFrame.renderId = previousRenderId;
  36968. this._currentRenderContext = previousRenderContext;
  36969. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36970. this._compilationPromises = previousCompilationPromises;
  36971. this._handleObjectFunction = this._renderObjectDirect;
  36972. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  36973. await Promise.all( compilationPromises );
  36974. }
  36975. /**
  36976. * Renders the scene in an async fashion.
  36977. *
  36978. * @async
  36979. * @param {Object3D} scene - The scene or 3D object to render.
  36980. * @param {Camera} camera - The camera.
  36981. * @return {Promise} A Promise that resolves when the render has been finished.
  36982. */
  36983. async renderAsync( scene, camera ) {
  36984. if ( this._initialized === false ) await this.init();
  36985. this._renderScene( scene, camera );
  36986. }
  36987. /**
  36988. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  36989. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  36990. *
  36991. * @async
  36992. * @return {Promise} A Promise that resolves when synchronization has been finished.
  36993. */
  36994. async waitForGPU() {
  36995. await this.backend.waitForGPU();
  36996. }
  36997. /**
  36998. * Enables or disables high precision for model-view and normal-view matrices.
  36999. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  37000. *
  37001. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  37002. *
  37003. * @param {boolean} value - Whether to enable or disable high precision.
  37004. * @type {boolean}
  37005. */
  37006. set highPrecision( value ) {
  37007. if ( value === true ) {
  37008. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  37009. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  37010. } else if ( this.highPrecision ) {
  37011. this.overrideNodes.modelViewMatrix = null;
  37012. this.overrideNodes.modelNormalViewMatrix = null;
  37013. }
  37014. }
  37015. /**
  37016. * Returns whether high precision is enabled or not.
  37017. *
  37018. * @return {boolean} Whether high precision is enabled or not.
  37019. * @type {boolean}
  37020. */
  37021. get highPrecision() {
  37022. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  37023. }
  37024. /**
  37025. * Sets the given MRT configuration.
  37026. *
  37027. * @param {MRTNode} mrt - The MRT node to set.
  37028. * @return {Renderer} A reference to this renderer.
  37029. */
  37030. setMRT( mrt ) {
  37031. this._mrt = mrt;
  37032. return this;
  37033. }
  37034. /**
  37035. * Returns the MRT configuration.
  37036. *
  37037. * @return {MRTNode} The MRT configuration.
  37038. */
  37039. getMRT() {
  37040. return this._mrt;
  37041. }
  37042. /**
  37043. * Returns the color buffer type.
  37044. *
  37045. * @return {number} The color buffer type.
  37046. */
  37047. getColorBufferType() {
  37048. return this._colorBufferType;
  37049. }
  37050. /**
  37051. * Default implementation of the device lost callback.
  37052. *
  37053. * @private
  37054. * @param {Object} info - Information about the context lost.
  37055. */
  37056. _onDeviceLost( info ) {
  37057. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  37058. if ( info.reason ) {
  37059. errorMessage += `\nReason: ${info.reason}`;
  37060. }
  37061. console.error( errorMessage );
  37062. this._isDeviceLost = true;
  37063. }
  37064. /**
  37065. * Renders the given render bundle.
  37066. *
  37067. * @private
  37068. * @param {Object} bundle - Render bundle data.
  37069. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  37070. * @param {LightsNode} lightsNode - The lights node.
  37071. */
  37072. _renderBundle( bundle, sceneRef, lightsNode ) {
  37073. const { bundleGroup, camera, renderList } = bundle;
  37074. const renderContext = this._currentRenderContext;
  37075. //
  37076. const renderBundle = this._bundles.get( bundleGroup, camera );
  37077. const renderBundleData = this.backend.get( renderBundle );
  37078. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37079. //
  37080. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37081. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37082. renderBundleData.renderContexts.add( renderContext );
  37083. if ( renderBundleNeedsUpdate ) {
  37084. this.backend.beginBundle( renderContext );
  37085. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37086. renderBundleData.renderObjects = [];
  37087. }
  37088. this._currentRenderBundle = renderBundle;
  37089. const {
  37090. transparentDoublePass: transparentDoublePassObjects,
  37091. transparent: transparentObjects,
  37092. opaque: opaqueObjects
  37093. } = renderList;
  37094. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37095. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37096. this._currentRenderBundle = null;
  37097. //
  37098. this.backend.finishBundle( renderContext, renderBundle );
  37099. renderBundleData.version = bundleGroup.version;
  37100. } else {
  37101. const { renderObjects } = renderBundleData;
  37102. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37103. const renderObject = renderObjects[ i ];
  37104. if ( this._nodes.needsRefresh( renderObject ) ) {
  37105. this._nodes.updateBefore( renderObject );
  37106. this._nodes.updateForRender( renderObject );
  37107. this._bindings.updateForRender( renderObject );
  37108. this._nodes.updateAfter( renderObject );
  37109. }
  37110. }
  37111. }
  37112. this.backend.addBundle( renderContext, renderBundle );
  37113. }
  37114. /**
  37115. * Renders the scene or 3D object with the given camera. This method can only be called
  37116. * if the renderer has been initialized.
  37117. *
  37118. * The target of the method is the default framebuffer (meaning the canvas)
  37119. * or alternatively a render target when specified via `setRenderTarget()`.
  37120. *
  37121. * @param {Object3D} scene - The scene or 3D object to render.
  37122. * @param {Camera} camera - The camera to render the scene with.
  37123. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  37124. * Only returned when the renderer has not been initialized.
  37125. */
  37126. render( scene, camera ) {
  37127. if ( this._initialized === false ) {
  37128. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37129. return this.renderAsync( scene, camera );
  37130. }
  37131. this._renderScene( scene, camera );
  37132. }
  37133. /**
  37134. * Returns an internal render target which is used when computing the output tone mapping
  37135. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  37136. * pass and not inline to achieve more correct results.
  37137. *
  37138. * @private
  37139. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  37140. */
  37141. _getFrameBufferTarget() {
  37142. const { currentToneMapping, currentColorSpace } = this;
  37143. const useToneMapping = currentToneMapping !== NoToneMapping;
  37144. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37145. if ( useToneMapping === false && useColorSpace === false ) return null;
  37146. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37147. const { depth, stencil } = this;
  37148. let frameBufferTarget = this._frameBufferTarget;
  37149. if ( frameBufferTarget === null ) {
  37150. frameBufferTarget = new RenderTarget( width, height, {
  37151. depthBuffer: depth,
  37152. stencilBuffer: stencil,
  37153. type: this._colorBufferType,
  37154. format: RGBAFormat,
  37155. colorSpace: LinearSRGBColorSpace,
  37156. generateMipmaps: false,
  37157. minFilter: LinearFilter,
  37158. magFilter: LinearFilter,
  37159. samples: this.samples
  37160. } );
  37161. frameBufferTarget.isPostProcessingRenderTarget = true;
  37162. this._frameBufferTarget = frameBufferTarget;
  37163. }
  37164. const outputRenderTarget = this.getOutputRenderTarget();
  37165. frameBufferTarget.depthBuffer = depth;
  37166. frameBufferTarget.stencilBuffer = stencil;
  37167. frameBufferTarget.setSize( width, height, outputRenderTarget !== null ? outputRenderTarget.depth : 1 );
  37168. frameBufferTarget.viewport.copy( this._viewport );
  37169. frameBufferTarget.scissor.copy( this._scissor );
  37170. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37171. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37172. frameBufferTarget.scissorTest = this._scissorTest;
  37173. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  37174. return frameBufferTarget;
  37175. }
  37176. /**
  37177. * Renders the scene or 3D object with the given camera.
  37178. *
  37179. * @private
  37180. * @param {Object3D} scene - The scene or 3D object to render.
  37181. * @param {Camera} camera - The camera to render the scene with.
  37182. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  37183. * @return {RenderContext} The current render context.
  37184. */
  37185. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37186. if ( this._isDeviceLost === true ) return;
  37187. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37188. // preserve render tree
  37189. const nodeFrame = this._nodes.nodeFrame;
  37190. const previousRenderId = nodeFrame.renderId;
  37191. const previousRenderContext = this._currentRenderContext;
  37192. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37193. //
  37194. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37195. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  37196. const activeCubeFace = this._activeCubeFace;
  37197. const activeMipmapLevel = this._activeMipmapLevel;
  37198. //
  37199. let renderTarget;
  37200. if ( frameBufferTarget !== null ) {
  37201. renderTarget = frameBufferTarget;
  37202. this.setRenderTarget( renderTarget );
  37203. } else {
  37204. renderTarget = outputRenderTarget;
  37205. }
  37206. //
  37207. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37208. this._currentRenderContext = renderContext;
  37209. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37210. //
  37211. this.info.calls ++;
  37212. this.info.render.calls ++;
  37213. this.info.render.frameCalls ++;
  37214. nodeFrame.renderId = this.info.calls;
  37215. //
  37216. const coordinateSystem = this.coordinateSystem;
  37217. const xr = this.xr;
  37218. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  37219. camera.coordinateSystem = coordinateSystem;
  37220. camera.updateProjectionMatrix();
  37221. if ( camera.isArrayCamera ) {
  37222. for ( const subCamera of camera.cameras ) {
  37223. subCamera.coordinateSystem = coordinateSystem;
  37224. subCamera.updateProjectionMatrix();
  37225. }
  37226. }
  37227. }
  37228. //
  37229. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37230. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37231. if ( xr.enabled === true && xr.isPresenting === true ) {
  37232. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  37233. camera = xr.getCamera(); // use XR camera for rendering
  37234. }
  37235. //
  37236. let viewport = this._viewport;
  37237. let scissor = this._scissor;
  37238. let pixelRatio = this._pixelRatio;
  37239. if ( renderTarget !== null ) {
  37240. viewport = renderTarget.viewport;
  37241. scissor = renderTarget.scissor;
  37242. pixelRatio = 1;
  37243. }
  37244. this.getDrawingBufferSize( _drawingBufferSize );
  37245. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37246. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37247. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37248. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37249. renderContext.viewportValue.width >>= activeMipmapLevel;
  37250. renderContext.viewportValue.height >>= activeMipmapLevel;
  37251. renderContext.viewportValue.minDepth = minDepth;
  37252. renderContext.viewportValue.maxDepth = maxDepth;
  37253. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37254. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37255. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37256. renderContext.scissorValue.width >>= activeMipmapLevel;
  37257. renderContext.scissorValue.height >>= activeMipmapLevel;
  37258. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37259. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37260. //
  37261. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37262. //
  37263. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  37264. if ( ! camera.isArrayCamera ) {
  37265. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37266. frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37267. }
  37268. const renderList = this._renderLists.get( scene, camera );
  37269. renderList.begin();
  37270. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37271. renderList.finish();
  37272. if ( this.sortObjects === true ) {
  37273. renderList.sort( this._opaqueSort, this._transparentSort );
  37274. }
  37275. //
  37276. if ( renderTarget !== null ) {
  37277. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37278. const renderTargetData = this._textures.get( renderTarget );
  37279. renderContext.textures = renderTargetData.textures;
  37280. renderContext.depthTexture = renderTargetData.depthTexture;
  37281. renderContext.width = renderTargetData.width;
  37282. renderContext.height = renderTargetData.height;
  37283. renderContext.renderTarget = renderTarget;
  37284. renderContext.depth = renderTarget.depthBuffer;
  37285. renderContext.stencil = renderTarget.stencilBuffer;
  37286. } else {
  37287. renderContext.textures = null;
  37288. renderContext.depthTexture = null;
  37289. renderContext.width = this.domElement.width;
  37290. renderContext.height = this.domElement.height;
  37291. renderContext.depth = this.depth;
  37292. renderContext.stencil = this.stencil;
  37293. }
  37294. renderContext.width >>= activeMipmapLevel;
  37295. renderContext.height >>= activeMipmapLevel;
  37296. renderContext.activeCubeFace = activeCubeFace;
  37297. renderContext.activeMipmapLevel = activeMipmapLevel;
  37298. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37299. //
  37300. this._background.update( sceneRef, renderList, renderContext );
  37301. //
  37302. renderContext.camera = camera;
  37303. this.backend.beginRender( renderContext );
  37304. // process render lists
  37305. const {
  37306. bundles,
  37307. lightsNode,
  37308. transparentDoublePass: transparentDoublePassObjects,
  37309. transparent: transparentObjects,
  37310. opaque: opaqueObjects
  37311. } = renderList;
  37312. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37313. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37314. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37315. // finish render pass
  37316. this.backend.finishRender( renderContext );
  37317. // restore render tree
  37318. nodeFrame.renderId = previousRenderId;
  37319. this._currentRenderContext = previousRenderContext;
  37320. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37321. //
  37322. if ( frameBufferTarget !== null ) {
  37323. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37324. this._renderOutput( renderTarget );
  37325. }
  37326. //
  37327. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37328. //
  37329. return renderContext;
  37330. }
  37331. /**
  37332. * The output pass performs tone mapping and color space conversion.
  37333. *
  37334. * @private
  37335. * @param {RenderTarget} renderTarget - The current render target.
  37336. */
  37337. _renderOutput( renderTarget ) {
  37338. const quad = this._quad;
  37339. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37340. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37341. quad.material.needsUpdate = true;
  37342. }
  37343. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  37344. const currentAutoClear = this.autoClear;
  37345. const currentXR = this.xr.enabled;
  37346. this.autoClear = false;
  37347. this.xr.enabled = false;
  37348. this._renderScene( quad, quad.camera, false );
  37349. this.autoClear = currentAutoClear;
  37350. this.xr.enabled = currentXR;
  37351. }
  37352. /**
  37353. * Returns the maximum available anisotropy for texture filtering.
  37354. *
  37355. * @return {number} The maximum available anisotropy.
  37356. */
  37357. getMaxAnisotropy() {
  37358. return this.backend.getMaxAnisotropy();
  37359. }
  37360. /**
  37361. * Returns the active cube face.
  37362. *
  37363. * @return {number} The active cube face.
  37364. */
  37365. getActiveCubeFace() {
  37366. return this._activeCubeFace;
  37367. }
  37368. /**
  37369. * Returns the active mipmap level.
  37370. *
  37371. * @return {number} The active mipmap level.
  37372. */
  37373. getActiveMipmapLevel() {
  37374. return this._activeMipmapLevel;
  37375. }
  37376. /**
  37377. * Applications are advised to always define the animation loop
  37378. * with this method and not manually with `requestAnimationFrame()`
  37379. * for best compatibility.
  37380. *
  37381. * @async
  37382. * @param {?Function} callback - The application's animation loop.
  37383. * @return {Promise} A Promise that resolves when the set has been executed.
  37384. */
  37385. async setAnimationLoop( callback ) {
  37386. if ( this._initialized === false ) await this.init();
  37387. this._animation.setAnimationLoop( callback );
  37388. }
  37389. /**
  37390. * Can be used to transfer buffer data from a storage buffer attribute
  37391. * from the GPU to the CPU in context of compute shaders.
  37392. *
  37393. * @async
  37394. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  37395. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  37396. */
  37397. async getArrayBufferAsync( attribute ) {
  37398. return await this.backend.getArrayBufferAsync( attribute );
  37399. }
  37400. /**
  37401. * Returns the rendering context.
  37402. *
  37403. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  37404. */
  37405. getContext() {
  37406. return this.backend.getContext();
  37407. }
  37408. /**
  37409. * Returns the pixel ratio.
  37410. *
  37411. * @return {number} The pixel ratio.
  37412. */
  37413. getPixelRatio() {
  37414. return this._pixelRatio;
  37415. }
  37416. /**
  37417. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  37418. *
  37419. * @param {Vector2} target - The method writes the result in this target object.
  37420. * @return {Vector2} The drawing buffer size.
  37421. */
  37422. getDrawingBufferSize( target ) {
  37423. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37424. }
  37425. /**
  37426. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  37427. *
  37428. * @param {Vector2} target - The method writes the result in this target object.
  37429. * @return {Vector2} The renderer's size in logical pixels.
  37430. */
  37431. getSize( target ) {
  37432. return target.set( this._width, this._height );
  37433. }
  37434. /**
  37435. * Sets the given pixel ratio and resizes the canvas if necessary.
  37436. *
  37437. * @param {number} [value=1] - The pixel ratio.
  37438. */
  37439. setPixelRatio( value = 1 ) {
  37440. if ( this._pixelRatio === value ) return;
  37441. this._pixelRatio = value;
  37442. this.setSize( this._width, this._height, false );
  37443. }
  37444. /**
  37445. * This method allows to define the drawing buffer size by specifying
  37446. * width, height and pixel ratio all at once. The size of the drawing
  37447. * buffer is computed with this formula:
  37448. * ```js
  37449. * size.x = width * pixelRatio;
  37450. * size.y = height * pixelRatio;
  37451. * ```
  37452. *
  37453. * @param {number} width - The width in logical pixels.
  37454. * @param {number} height - The height in logical pixels.
  37455. * @param {number} pixelRatio - The pixel ratio.
  37456. */
  37457. setDrawingBufferSize( width, height, pixelRatio ) {
  37458. // Renderer can't be resized while presenting in XR.
  37459. if ( this.xr && this.xr.isPresenting ) return;
  37460. this._width = width;
  37461. this._height = height;
  37462. this._pixelRatio = pixelRatio;
  37463. this.domElement.width = Math.floor( width * pixelRatio );
  37464. this.domElement.height = Math.floor( height * pixelRatio );
  37465. this.setViewport( 0, 0, width, height );
  37466. if ( this._initialized ) this.backend.updateSize();
  37467. }
  37468. /**
  37469. * Sets the size of the renderer.
  37470. *
  37471. * @param {number} width - The width in logical pixels.
  37472. * @param {number} height - The height in logical pixels.
  37473. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  37474. */
  37475. setSize( width, height, updateStyle = true ) {
  37476. // Renderer can't be resized while presenting in XR.
  37477. if ( this.xr && this.xr.isPresenting ) return;
  37478. this._width = width;
  37479. this._height = height;
  37480. this.domElement.width = Math.floor( width * this._pixelRatio );
  37481. this.domElement.height = Math.floor( height * this._pixelRatio );
  37482. if ( updateStyle === true ) {
  37483. this.domElement.style.width = width + 'px';
  37484. this.domElement.style.height = height + 'px';
  37485. }
  37486. this.setViewport( 0, 0, width, height );
  37487. if ( this._initialized ) this.backend.updateSize();
  37488. }
  37489. /**
  37490. * Defines a manual sort function for the opaque render list.
  37491. * Pass `null` to use the default sort.
  37492. *
  37493. * @param {Function} method - The sort function.
  37494. */
  37495. setOpaqueSort( method ) {
  37496. this._opaqueSort = method;
  37497. }
  37498. /**
  37499. * Defines a manual sort function for the transparent render list.
  37500. * Pass `null` to use the default sort.
  37501. *
  37502. * @param {Function} method - The sort function.
  37503. */
  37504. setTransparentSort( method ) {
  37505. this._transparentSort = method;
  37506. }
  37507. /**
  37508. * Returns the scissor rectangle.
  37509. *
  37510. * @param {Vector4} target - The method writes the result in this target object.
  37511. * @return {Vector4} The scissor rectangle.
  37512. */
  37513. getScissor( target ) {
  37514. const scissor = this._scissor;
  37515. target.x = scissor.x;
  37516. target.y = scissor.y;
  37517. target.width = scissor.width;
  37518. target.height = scissor.height;
  37519. return target;
  37520. }
  37521. /**
  37522. * Defines the scissor rectangle.
  37523. *
  37524. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  37525. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  37526. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  37527. * @param {number} width - The width of the scissor box in logical pixel unit.
  37528. * @param {number} height - The height of the scissor box in logical pixel unit.
  37529. */
  37530. setScissor( x, y, width, height ) {
  37531. const scissor = this._scissor;
  37532. if ( x.isVector4 ) {
  37533. scissor.copy( x );
  37534. } else {
  37535. scissor.set( x, y, width, height );
  37536. }
  37537. }
  37538. /**
  37539. * Returns the scissor test value.
  37540. *
  37541. * @return {boolean} Whether the scissor test should be enabled or not.
  37542. */
  37543. getScissorTest() {
  37544. return this._scissorTest;
  37545. }
  37546. /**
  37547. * Defines the scissor test.
  37548. *
  37549. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  37550. */
  37551. setScissorTest( boolean ) {
  37552. this._scissorTest = boolean;
  37553. this.backend.setScissorTest( boolean );
  37554. }
  37555. /**
  37556. * Returns the viewport definition.
  37557. *
  37558. * @param {Vector4} target - The method writes the result in this target object.
  37559. * @return {Vector4} The viewport definition.
  37560. */
  37561. getViewport( target ) {
  37562. return target.copy( this._viewport );
  37563. }
  37564. /**
  37565. * Defines the viewport.
  37566. *
  37567. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  37568. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  37569. * @param {number} width - The width of the viewport in logical pixel unit.
  37570. * @param {number} height - The height of the viewport in logical pixel unit.
  37571. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  37572. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  37573. */
  37574. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37575. const viewport = this._viewport;
  37576. if ( x.isVector4 ) {
  37577. viewport.copy( x );
  37578. } else {
  37579. viewport.set( x, y, width, height );
  37580. }
  37581. viewport.minDepth = minDepth;
  37582. viewport.maxDepth = maxDepth;
  37583. }
  37584. /**
  37585. * Returns the clear color.
  37586. *
  37587. * @param {Color} target - The method writes the result in this target object.
  37588. * @return {Color} The clear color.
  37589. */
  37590. getClearColor( target ) {
  37591. return target.copy( this._clearColor );
  37592. }
  37593. /**
  37594. * Defines the clear color and optionally the clear alpha.
  37595. *
  37596. * @param {Color} color - The clear color.
  37597. * @param {number} [alpha=1] - The clear alpha.
  37598. */
  37599. setClearColor( color, alpha = 1 ) {
  37600. this._clearColor.set( color );
  37601. this._clearColor.a = alpha;
  37602. }
  37603. /**
  37604. * Returns the clear alpha.
  37605. *
  37606. * @return {number} The clear alpha.
  37607. */
  37608. getClearAlpha() {
  37609. return this._clearColor.a;
  37610. }
  37611. /**
  37612. * Defines the clear alpha.
  37613. *
  37614. * @param {number} alpha - The clear alpha.
  37615. */
  37616. setClearAlpha( alpha ) {
  37617. this._clearColor.a = alpha;
  37618. }
  37619. /**
  37620. * Returns the clear depth.
  37621. *
  37622. * @return {number} The clear depth.
  37623. */
  37624. getClearDepth() {
  37625. return this._clearDepth;
  37626. }
  37627. /**
  37628. * Defines the clear depth.
  37629. *
  37630. * @param {number} depth - The clear depth.
  37631. */
  37632. setClearDepth( depth ) {
  37633. this._clearDepth = depth;
  37634. }
  37635. /**
  37636. * Returns the clear stencil.
  37637. *
  37638. * @return {number} The clear stencil.
  37639. */
  37640. getClearStencil() {
  37641. return this._clearStencil;
  37642. }
  37643. /**
  37644. * Defines the clear stencil.
  37645. *
  37646. * @param {number} stencil - The clear stencil.
  37647. */
  37648. setClearStencil( stencil ) {
  37649. this._clearStencil = stencil;
  37650. }
  37651. /**
  37652. * This method performs an occlusion query for the given 3D object.
  37653. * It returns `true` if the given 3D object is fully occluded by other
  37654. * 3D objects in the scene.
  37655. *
  37656. * @param {Object3D} object - The 3D object to test.
  37657. * @return {boolean} Whether the 3D object is fully occluded or not.
  37658. */
  37659. isOccluded( object ) {
  37660. const renderContext = this._currentRenderContext;
  37661. return renderContext && this.backend.isOccluded( renderContext, object );
  37662. }
  37663. /**
  37664. * Performs a manual clear operation. This method ignores `autoClear` properties.
  37665. *
  37666. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  37667. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  37668. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  37669. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37670. * Only returned when the renderer has not been initialized.
  37671. */
  37672. clear( color = true, depth = true, stencil = true ) {
  37673. if ( this._initialized === false ) {
  37674. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  37675. return this.clearAsync( color, depth, stencil );
  37676. }
  37677. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37678. let renderContext = null;
  37679. if ( renderTarget !== null ) {
  37680. this._textures.updateRenderTarget( renderTarget );
  37681. const renderTargetData = this._textures.get( renderTarget );
  37682. renderContext = this._renderContexts.getForClear( renderTarget );
  37683. renderContext.textures = renderTargetData.textures;
  37684. renderContext.depthTexture = renderTargetData.depthTexture;
  37685. renderContext.width = renderTargetData.width;
  37686. renderContext.height = renderTargetData.height;
  37687. renderContext.renderTarget = renderTarget;
  37688. renderContext.depth = renderTarget.depthBuffer;
  37689. renderContext.stencil = renderTarget.stencilBuffer;
  37690. // #30329
  37691. renderContext.clearColorValue = this.backend.getClearColor();
  37692. renderContext.activeCubeFace = this.getActiveCubeFace();
  37693. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  37694. }
  37695. this.backend.clear( color, depth, stencil, renderContext );
  37696. if ( renderTarget !== null && this._renderTarget === null ) {
  37697. this._renderOutput( renderTarget );
  37698. }
  37699. }
  37700. /**
  37701. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  37702. *
  37703. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37704. * Only returned when the renderer has not been initialized.
  37705. */
  37706. clearColor() {
  37707. return this.clear( true, false, false );
  37708. }
  37709. /**
  37710. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  37711. *
  37712. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37713. * Only returned when the renderer has not been initialized.
  37714. */
  37715. clearDepth() {
  37716. return this.clear( false, true, false );
  37717. }
  37718. /**
  37719. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  37720. *
  37721. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37722. * Only returned when the renderer has not been initialized.
  37723. */
  37724. clearStencil() {
  37725. return this.clear( false, false, true );
  37726. }
  37727. /**
  37728. * Async version of {@link Renderer#clear}.
  37729. *
  37730. * @async
  37731. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  37732. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  37733. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  37734. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37735. */
  37736. async clearAsync( color = true, depth = true, stencil = true ) {
  37737. if ( this._initialized === false ) await this.init();
  37738. this.clear( color, depth, stencil );
  37739. }
  37740. /**
  37741. * Async version of {@link Renderer#clearColor}.
  37742. *
  37743. * @async
  37744. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37745. */
  37746. async clearColorAsync() {
  37747. this.clearAsync( true, false, false );
  37748. }
  37749. /**
  37750. * Async version of {@link Renderer#clearDepth}.
  37751. *
  37752. * @async
  37753. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37754. */
  37755. async clearDepthAsync() {
  37756. this.clearAsync( false, true, false );
  37757. }
  37758. /**
  37759. * Async version of {@link Renderer#clearStencil}.
  37760. *
  37761. * @async
  37762. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37763. */
  37764. async clearStencilAsync() {
  37765. this.clearAsync( false, false, true );
  37766. }
  37767. /**
  37768. * The current output tone mapping of the renderer. When a render target is set,
  37769. * the output tone mapping is always `NoToneMapping`.
  37770. *
  37771. * @type {number}
  37772. */
  37773. get currentToneMapping() {
  37774. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  37775. }
  37776. /**
  37777. * The current output color space of the renderer. When a render target is set,
  37778. * the output color space is always `LinearSRGBColorSpace`.
  37779. *
  37780. * @type {string}
  37781. */
  37782. get currentColorSpace() {
  37783. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  37784. }
  37785. /**
  37786. * Returns `true` if the rendering settings are set to screen output.
  37787. *
  37788. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  37789. */
  37790. get isOutputTarget() {
  37791. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  37792. }
  37793. /**
  37794. * Frees all internal resources of the renderer. Call this method if the renderer
  37795. * is no longer in use by your app.
  37796. */
  37797. dispose() {
  37798. this.info.dispose();
  37799. this.backend.dispose();
  37800. this._animation.dispose();
  37801. this._objects.dispose();
  37802. this._pipelines.dispose();
  37803. this._nodes.dispose();
  37804. this._bindings.dispose();
  37805. this._renderLists.dispose();
  37806. this._renderContexts.dispose();
  37807. this._textures.dispose();
  37808. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  37809. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  37810. if ( queryPool !== null ) queryPool.dispose();
  37811. } );
  37812. this.setRenderTarget( null );
  37813. this.setAnimationLoop( null );
  37814. }
  37815. /**
  37816. * Sets the given render target. Calling this method means the renderer does not
  37817. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  37818. * Use `null` as the first argument to reset the state.
  37819. *
  37820. * @param {?RenderTarget} renderTarget - The render target to set.
  37821. * @param {number} [activeCubeFace=0] - The active cube face.
  37822. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  37823. */
  37824. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  37825. this._renderTarget = renderTarget;
  37826. this._activeCubeFace = activeCubeFace;
  37827. this._activeMipmapLevel = activeMipmapLevel;
  37828. }
  37829. /**
  37830. * Returns the current render target.
  37831. *
  37832. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  37833. */
  37834. getRenderTarget() {
  37835. return this._renderTarget;
  37836. }
  37837. /**
  37838. * Sets the output render target for the renderer.
  37839. *
  37840. * @param {Object} renderTarget - The render target to set as the output target.
  37841. */
  37842. setOutputRenderTarget( renderTarget ) {
  37843. this._outputRenderTarget = renderTarget;
  37844. }
  37845. /**
  37846. * Returns the current output target.
  37847. *
  37848. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  37849. */
  37850. getOutputRenderTarget() {
  37851. return this._outputRenderTarget;
  37852. }
  37853. /**
  37854. * Callback for {@link Renderer#setRenderObjectFunction}.
  37855. *
  37856. * @callback renderObjectFunction
  37857. * @param {Object3D} object - The 3D object.
  37858. * @param {Scene} scene - The scene the 3D object belongs to.
  37859. * @param {Camera} camera - The camera the object should be rendered with.
  37860. * @param {BufferGeometry} geometry - The object's geometry.
  37861. * @param {Material} material - The object's material.
  37862. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  37863. * @param {LightsNode} lightsNode - The current lights node.
  37864. * @param {ClippingContext} clippingContext - The clipping context.
  37865. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37866. */
  37867. /**
  37868. * Sets the given render object function. Calling this method overwrites the default implementation
  37869. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  37870. * if you want to modify the way objects are rendered. For example you can define things like "every
  37871. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  37872. * The custom function must always call `renderObject()` in its implementation.
  37873. *
  37874. * Use `null` as the first argument to reset the state.
  37875. *
  37876. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  37877. */
  37878. setRenderObjectFunction( renderObjectFunction ) {
  37879. this._renderObjectFunction = renderObjectFunction;
  37880. }
  37881. /**
  37882. * Returns the current render object function.
  37883. *
  37884. * @return {?Function} The current render object function. Returns `null` if no function is set.
  37885. */
  37886. getRenderObjectFunction() {
  37887. return this._renderObjectFunction;
  37888. }
  37889. /**
  37890. * Execute a single or an array of compute nodes. This method can only be called
  37891. * if the renderer has been initialized.
  37892. *
  37893. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  37894. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  37895. */
  37896. compute( computeNodes ) {
  37897. if ( this._isDeviceLost === true ) return;
  37898. if ( this._initialized === false ) {
  37899. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  37900. return this.computeAsync( computeNodes );
  37901. }
  37902. //
  37903. const nodeFrame = this._nodes.nodeFrame;
  37904. const previousRenderId = nodeFrame.renderId;
  37905. //
  37906. this.info.calls ++;
  37907. this.info.compute.calls ++;
  37908. this.info.compute.frameCalls ++;
  37909. nodeFrame.renderId = this.info.calls;
  37910. //
  37911. const backend = this.backend;
  37912. const pipelines = this._pipelines;
  37913. const bindings = this._bindings;
  37914. const nodes = this._nodes;
  37915. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  37916. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  37917. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  37918. }
  37919. backend.beginCompute( computeNodes );
  37920. for ( const computeNode of computeList ) {
  37921. // onInit
  37922. if ( pipelines.has( computeNode ) === false ) {
  37923. const dispose = () => {
  37924. computeNode.removeEventListener( 'dispose', dispose );
  37925. pipelines.delete( computeNode );
  37926. bindings.delete( computeNode );
  37927. nodes.delete( computeNode );
  37928. };
  37929. computeNode.addEventListener( 'dispose', dispose );
  37930. //
  37931. const onInitFn = computeNode.onInitFunction;
  37932. if ( onInitFn !== null ) {
  37933. onInitFn.call( computeNode, { renderer: this } );
  37934. }
  37935. }
  37936. nodes.updateForCompute( computeNode );
  37937. bindings.updateForCompute( computeNode );
  37938. const computeBindings = bindings.getForCompute( computeNode );
  37939. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  37940. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  37941. }
  37942. backend.finishCompute( computeNodes );
  37943. //
  37944. nodeFrame.renderId = previousRenderId;
  37945. }
  37946. /**
  37947. * Execute a single or an array of compute nodes.
  37948. *
  37949. * @async
  37950. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  37951. * @return {Promise} A Promise that resolve when the compute has finished.
  37952. */
  37953. async computeAsync( computeNodes ) {
  37954. if ( this._initialized === false ) await this.init();
  37955. this.compute( computeNodes );
  37956. }
  37957. /**
  37958. * Checks if the given feature is supported by the selected backend.
  37959. *
  37960. * @async
  37961. * @param {string} name - The feature's name.
  37962. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  37963. */
  37964. async hasFeatureAsync( name ) {
  37965. if ( this._initialized === false ) await this.init();
  37966. return this.backend.hasFeature( name );
  37967. }
  37968. async resolveTimestampsAsync( type = 'render' ) {
  37969. if ( this._initialized === false ) await this.init();
  37970. return this.backend.resolveTimestampsAsync( type );
  37971. }
  37972. /**
  37973. * Checks if the given feature is supported by the selected backend. If the
  37974. * renderer has not been initialized, this method always returns `false`.
  37975. *
  37976. * @param {string} name - The feature's name.
  37977. * @return {boolean} Whether the feature is supported or not.
  37978. */
  37979. hasFeature( name ) {
  37980. if ( this._initialized === false ) {
  37981. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  37982. return false;
  37983. }
  37984. return this.backend.hasFeature( name );
  37985. }
  37986. /**
  37987. * Returns `true` when the renderer has been initialized.
  37988. *
  37989. * @return {boolean} Whether the renderer has been initialized or not.
  37990. */
  37991. hasInitialized() {
  37992. return this._initialized;
  37993. }
  37994. /**
  37995. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  37996. * (which can cause noticeable lags due to decode and GPU upload overhead).
  37997. *
  37998. * @async
  37999. * @param {Texture} texture - The texture.
  38000. * @return {Promise} A Promise that resolves when the texture has been initialized.
  38001. */
  38002. async initTextureAsync( texture ) {
  38003. if ( this._initialized === false ) await this.init();
  38004. this._textures.updateTexture( texture );
  38005. }
  38006. /**
  38007. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  38008. * (which can cause noticeable lags due to decode and GPU upload overhead).
  38009. *
  38010. * This method can only be used if the renderer has been initialized.
  38011. *
  38012. * @param {Texture} texture - The texture.
  38013. */
  38014. initTexture( texture ) {
  38015. if ( this._initialized === false ) {
  38016. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  38017. }
  38018. this._textures.updateTexture( texture );
  38019. }
  38020. /**
  38021. * Copies the current bound framebuffer into the given texture.
  38022. *
  38023. * @param {FramebufferTexture} framebufferTexture - The texture.
  38024. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  38025. */
  38026. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38027. if ( rectangle !== null ) {
  38028. if ( rectangle.isVector2 ) {
  38029. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  38030. } else if ( rectangle.isVector4 ) {
  38031. rectangle = _vector4.copy( rectangle ).floor();
  38032. } else {
  38033. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  38034. return;
  38035. }
  38036. } else {
  38037. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  38038. }
  38039. //
  38040. let renderContext = this._currentRenderContext;
  38041. let renderTarget;
  38042. if ( renderContext !== null ) {
  38043. renderTarget = renderContext.renderTarget;
  38044. } else {
  38045. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38046. if ( renderTarget !== null ) {
  38047. this._textures.updateRenderTarget( renderTarget );
  38048. renderContext = this._textures.get( renderTarget );
  38049. }
  38050. }
  38051. //
  38052. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  38053. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38054. }
  38055. /**
  38056. * Copies data of the given source texture into a destination texture.
  38057. *
  38058. * @param {Texture} srcTexture - The source texture.
  38059. * @param {Texture} dstTexture - The destination texture.
  38060. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  38061. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  38062. * @param {number} [srcLevel=0] - The source mip level to copy from.
  38063. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  38064. */
  38065. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  38066. this._textures.updateTexture( srcTexture );
  38067. this._textures.updateTexture( dstTexture );
  38068. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  38069. }
  38070. /**
  38071. * Reads pixel data from the given render target.
  38072. *
  38073. * @async
  38074. * @param {RenderTarget} renderTarget - The render target to read from.
  38075. * @param {number} x - The `x` coordinate of the copy region's origin.
  38076. * @param {number} y - The `y` coordinate of the copy region's origin.
  38077. * @param {number} width - The width of the copy region.
  38078. * @param {number} height - The height of the copy region.
  38079. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  38080. * @param {number} [faceIndex=0] - The active cube face index.
  38081. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  38082. */
  38083. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  38084. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  38085. }
  38086. /**
  38087. * Analyzes the given 3D object's hierarchy and builds render lists from the
  38088. * processed hierarchy.
  38089. *
  38090. * @param {Object3D} object - The 3D object to process (usually a scene).
  38091. * @param {Camera} camera - The camera the object is rendered with.
  38092. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  38093. * @param {RenderList} renderList - The current render list.
  38094. * @param {ClippingContext} clippingContext - The current clipping context.
  38095. */
  38096. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  38097. if ( object.visible === false ) return;
  38098. const visible = object.layers.test( camera.layers );
  38099. if ( visible ) {
  38100. if ( object.isGroup ) {
  38101. groupOrder = object.renderOrder;
  38102. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  38103. } else if ( object.isLOD ) {
  38104. if ( object.autoUpdate === true ) object.update( camera );
  38105. } else if ( object.isLight ) {
  38106. renderList.pushLight( object );
  38107. } else if ( object.isSprite ) {
  38108. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38109. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  38110. if ( this.sortObjects === true ) {
  38111. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38112. }
  38113. const { geometry, material } = object;
  38114. if ( material.visible ) {
  38115. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38116. }
  38117. }
  38118. } else if ( object.isLineLoop ) {
  38119. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38120. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38121. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38122. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  38123. const { geometry, material } = object;
  38124. if ( this.sortObjects === true ) {
  38125. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38126. _vector4
  38127. .copy( geometry.boundingSphere.center )
  38128. .applyMatrix4( object.matrixWorld )
  38129. .applyMatrix4( _projScreenMatrix );
  38130. }
  38131. if ( Array.isArray( material ) ) {
  38132. const groups = geometry.groups;
  38133. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38134. const group = groups[ i ];
  38135. const groupMaterial = material[ group.materialIndex ];
  38136. if ( groupMaterial && groupMaterial.visible ) {
  38137. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  38138. }
  38139. }
  38140. } else if ( material.visible ) {
  38141. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38142. }
  38143. }
  38144. }
  38145. }
  38146. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38147. const baseRenderList = renderList;
  38148. // replace render list
  38149. renderList = this._renderLists.get( object, camera );
  38150. renderList.begin();
  38151. baseRenderList.pushBundle( {
  38152. bundleGroup: object,
  38153. camera,
  38154. renderList,
  38155. } );
  38156. renderList.finish();
  38157. }
  38158. const children = object.children;
  38159. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38160. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  38161. }
  38162. }
  38163. /**
  38164. * Renders the given render bundles.
  38165. *
  38166. * @private
  38167. * @param {Array<Object>} bundles - Array with render bundle data.
  38168. * @param {Scene} sceneRef - The scene the render bundles belong to.
  38169. * @param {LightsNode} lightsNode - The current lights node.
  38170. */
  38171. _renderBundles( bundles, sceneRef, lightsNode ) {
  38172. for ( const bundle of bundles ) {
  38173. this._renderBundle( bundle, sceneRef, lightsNode );
  38174. }
  38175. }
  38176. /**
  38177. * Renders the transparent objects from the given render lists.
  38178. *
  38179. * @private
  38180. * @param {Array<Object>} renderList - The transparent render list.
  38181. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  38182. * @param {Camera} camera - The camera the render list should be rendered with.
  38183. * @param {Scene} scene - The scene the render list belongs to.
  38184. * @param {LightsNode} lightsNode - The current lights node.
  38185. */
  38186. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  38187. if ( doublePassList.length > 0 ) {
  38188. // render back side
  38189. for ( const { material } of doublePassList ) {
  38190. material.side = BackSide;
  38191. }
  38192. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  38193. // render front side
  38194. for ( const { material } of doublePassList ) {
  38195. material.side = FrontSide;
  38196. }
  38197. this._renderObjects( renderList, camera, scene, lightsNode );
  38198. // restore
  38199. for ( const { material } of doublePassList ) {
  38200. material.side = DoubleSide;
  38201. }
  38202. } else {
  38203. this._renderObjects( renderList, camera, scene, lightsNode );
  38204. }
  38205. }
  38206. /**
  38207. * Renders the objects from the given render list.
  38208. *
  38209. * @private
  38210. * @param {Array<Object>} renderList - The render list.
  38211. * @param {Camera} camera - The camera the render list should be rendered with.
  38212. * @param {Scene} scene - The scene the render list belongs to.
  38213. * @param {LightsNode} lightsNode - The current lights node.
  38214. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38215. */
  38216. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  38217. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38218. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  38219. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  38220. }
  38221. }
  38222. /**
  38223. * This method represents the default render object function that manages the render lifecycle
  38224. * of the object.
  38225. *
  38226. * @param {Object3D} object - The 3D object.
  38227. * @param {Scene} scene - The scene the 3D object belongs to.
  38228. * @param {Camera} camera - The camera the object should be rendered with.
  38229. * @param {BufferGeometry} geometry - The object's geometry.
  38230. * @param {Material} material - The object's material.
  38231. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38232. * @param {LightsNode} lightsNode - The current lights node.
  38233. * @param {?ClippingContext} clippingContext - The clipping context.
  38234. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38235. */
  38236. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  38237. let overridePositionNode;
  38238. let overrideColorNode;
  38239. let overrideDepthNode;
  38240. //
  38241. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38242. //
  38243. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  38244. const overrideMaterial = scene.overrideMaterial;
  38245. if ( material.positionNode && material.positionNode.isNode ) {
  38246. overridePositionNode = overrideMaterial.positionNode;
  38247. overrideMaterial.positionNode = material.positionNode;
  38248. }
  38249. overrideMaterial.alphaTest = material.alphaTest;
  38250. overrideMaterial.alphaMap = material.alphaMap;
  38251. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  38252. if ( overrideMaterial.isShadowPassMaterial ) {
  38253. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38254. if ( material.depthNode && material.depthNode.isNode ) {
  38255. overrideDepthNode = overrideMaterial.depthNode;
  38256. overrideMaterial.depthNode = material.depthNode;
  38257. }
  38258. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  38259. overrideColorNode = overrideMaterial.colorNode;
  38260. overrideMaterial.colorNode = material.castShadowNode;
  38261. }
  38262. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  38263. overridePositionNode = overrideMaterial.positionNode;
  38264. overrideMaterial.positionNode = material.castShadowPositionNode;
  38265. }
  38266. }
  38267. material = overrideMaterial;
  38268. }
  38269. //
  38270. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38271. material.side = BackSide;
  38272. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  38273. material.side = FrontSide;
  38274. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  38275. material.side = DoubleSide;
  38276. } else {
  38277. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  38278. }
  38279. //
  38280. if ( overridePositionNode !== undefined ) {
  38281. scene.overrideMaterial.positionNode = overridePositionNode;
  38282. }
  38283. if ( overrideDepthNode !== undefined ) {
  38284. scene.overrideMaterial.depthNode = overrideDepthNode;
  38285. }
  38286. if ( overrideColorNode !== undefined ) {
  38287. scene.overrideMaterial.colorNode = overrideColorNode;
  38288. }
  38289. //
  38290. object.onAfterRender( this, scene, camera, geometry, material, group );
  38291. }
  38292. /**
  38293. * This method represents the default `_handleObjectFunction` implementation which creates
  38294. * a render object from the given data and performs the draw command with the selected backend.
  38295. *
  38296. * @private
  38297. * @param {Object3D} object - The 3D object.
  38298. * @param {Material} material - The object's material.
  38299. * @param {Scene} scene - The scene the 3D object belongs to.
  38300. * @param {Camera} camera - The camera the object should be rendered with.
  38301. * @param {LightsNode} lightsNode - The current lights node.
  38302. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38303. * @param {ClippingContext} clippingContext - The clipping context.
  38304. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38305. */
  38306. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38307. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38308. renderObject.drawRange = object.geometry.drawRange;
  38309. renderObject.group = group;
  38310. //
  38311. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38312. if ( needsRefresh ) {
  38313. this._nodes.updateBefore( renderObject );
  38314. this._geometries.updateForRender( renderObject );
  38315. this._nodes.updateForRender( renderObject );
  38316. this._bindings.updateForRender( renderObject );
  38317. }
  38318. this._pipelines.updateForRender( renderObject );
  38319. //
  38320. if ( this._currentRenderBundle !== null ) {
  38321. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38322. renderBundleData.renderObjects.push( renderObject );
  38323. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  38324. }
  38325. this.backend.draw( renderObject, this.info );
  38326. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38327. }
  38328. /**
  38329. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  38330. * Used in `compileAsync()`.
  38331. *
  38332. * @private
  38333. * @param {Object3D} object - The 3D object.
  38334. * @param {Material} material - The object's material.
  38335. * @param {Scene} scene - The scene the 3D object belongs to.
  38336. * @param {Camera} camera - The camera the object should be rendered with.
  38337. * @param {LightsNode} lightsNode - The current lights node.
  38338. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38339. * @param {ClippingContext} clippingContext - The clipping context.
  38340. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38341. */
  38342. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38343. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38344. renderObject.drawRange = object.geometry.drawRange;
  38345. renderObject.group = group;
  38346. //
  38347. this._nodes.updateBefore( renderObject );
  38348. this._geometries.updateForRender( renderObject );
  38349. this._nodes.updateForRender( renderObject );
  38350. this._bindings.updateForRender( renderObject );
  38351. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38352. this._nodes.updateAfter( renderObject );
  38353. }
  38354. /**
  38355. * Alias for `compileAsync()`.
  38356. *
  38357. * @method
  38358. * @param {Object3D} scene - The scene or 3D object to precompile.
  38359. * @param {Camera} camera - The camera that is used to render the scene.
  38360. * @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.
  38361. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  38362. */
  38363. get compile() {
  38364. return this.compileAsync;
  38365. }
  38366. }
  38367. /**
  38368. * A binding represents the connection between a resource (like a texture, sampler
  38369. * or uniform buffer) and the resource definition in a shader stage.
  38370. *
  38371. * This module is an abstract base class for all concrete bindings types.
  38372. *
  38373. * @abstract
  38374. * @private
  38375. */
  38376. class Binding {
  38377. /**
  38378. * Constructs a new binding.
  38379. *
  38380. * @param {string} [name=''] - The binding's name.
  38381. */
  38382. constructor( name = '' ) {
  38383. /**
  38384. * The binding's name.
  38385. *
  38386. * @type {string}
  38387. */
  38388. this.name = name;
  38389. /**
  38390. * A bitmask that defines in what shader stages the
  38391. * binding's resource is accessible.
  38392. *
  38393. * @type {number}
  38394. */
  38395. this.visibility = 0;
  38396. }
  38397. /**
  38398. * Makes sure binding's resource is visible for the given shader stage.
  38399. *
  38400. * @param {number} visibility - The shader stage.
  38401. */
  38402. setVisibility( visibility ) {
  38403. this.visibility |= visibility;
  38404. }
  38405. /**
  38406. * Clones the binding.
  38407. *
  38408. * @return {Binding} The cloned binding.
  38409. */
  38410. clone() {
  38411. return Object.assign( new this.constructor(), this );
  38412. }
  38413. }
  38414. /**
  38415. * This function is usually called with the length in bytes of an array buffer.
  38416. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  38417. *
  38418. * @function
  38419. * @param {number} floatLength - The buffer length.
  38420. * @return {number} The padded length.
  38421. */
  38422. function getFloatLength( floatLength ) {
  38423. // ensure chunk size alignment (STD140 layout)
  38424. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38425. }
  38426. /**
  38427. * Represents a buffer binding type.
  38428. *
  38429. * @private
  38430. * @abstract
  38431. * @augments Binding
  38432. */
  38433. class Buffer extends Binding {
  38434. /**
  38435. * Constructs a new buffer.
  38436. *
  38437. * @param {string} name - The buffer's name.
  38438. * @param {TypedArray} [buffer=null] - The buffer.
  38439. */
  38440. constructor( name, buffer = null ) {
  38441. super( name );
  38442. /**
  38443. * This flag can be used for type testing.
  38444. *
  38445. * @type {boolean}
  38446. * @readonly
  38447. * @default true
  38448. */
  38449. this.isBuffer = true;
  38450. /**
  38451. * The bytes per element.
  38452. *
  38453. * @type {number}
  38454. */
  38455. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38456. /**
  38457. * A reference to the internal buffer.
  38458. *
  38459. * @private
  38460. * @type {TypedArray}
  38461. */
  38462. this._buffer = buffer;
  38463. }
  38464. /**
  38465. * The buffer's byte length.
  38466. *
  38467. * @type {number}
  38468. * @readonly
  38469. */
  38470. get byteLength() {
  38471. return getFloatLength( this._buffer.byteLength );
  38472. }
  38473. /**
  38474. * A reference to the internal buffer.
  38475. *
  38476. * @type {Float32Array}
  38477. * @readonly
  38478. */
  38479. get buffer() {
  38480. return this._buffer;
  38481. }
  38482. /**
  38483. * Updates the binding.
  38484. *
  38485. * @return {boolean} Whether the buffer has been updated and must be
  38486. * uploaded to the GPU.
  38487. */
  38488. update() {
  38489. return true;
  38490. }
  38491. }
  38492. /**
  38493. * Represents a uniform buffer binding type.
  38494. *
  38495. * @private
  38496. * @augments Buffer
  38497. */
  38498. class UniformBuffer extends Buffer {
  38499. /**
  38500. * Constructs a new uniform buffer.
  38501. *
  38502. * @param {string} name - The buffer's name.
  38503. * @param {TypedArray} [buffer=null] - The buffer.
  38504. */
  38505. constructor( name, buffer = null ) {
  38506. super( name, buffer );
  38507. /**
  38508. * This flag can be used for type testing.
  38509. *
  38510. * @type {boolean}
  38511. * @readonly
  38512. * @default true
  38513. */
  38514. this.isUniformBuffer = true;
  38515. }
  38516. }
  38517. let _id$4 = 0;
  38518. /**
  38519. * A special form of uniform buffer binding type.
  38520. * It's buffer value is managed by a node object.
  38521. *
  38522. * @private
  38523. * @augments UniformBuffer
  38524. */
  38525. class NodeUniformBuffer extends UniformBuffer {
  38526. /**
  38527. * Constructs a new node-based uniform buffer.
  38528. *
  38529. * @param {BufferNode} nodeUniform - The uniform buffer node.
  38530. * @param {UniformGroupNode} groupNode - The uniform group node.
  38531. */
  38532. constructor( nodeUniform, groupNode ) {
  38533. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38534. /**
  38535. * The uniform buffer node.
  38536. *
  38537. * @type {BufferNode}
  38538. */
  38539. this.nodeUniform = nodeUniform;
  38540. /**
  38541. * The uniform group node.
  38542. *
  38543. * @type {UniformGroupNode}
  38544. */
  38545. this.groupNode = groupNode;
  38546. }
  38547. /**
  38548. * The uniform buffer.
  38549. *
  38550. * @type {Float32Array}
  38551. */
  38552. get buffer() {
  38553. return this.nodeUniform.value;
  38554. }
  38555. }
  38556. /**
  38557. * This class represents a uniform buffer binding but with
  38558. * an API that allows to maintain individual uniform objects.
  38559. *
  38560. * @private
  38561. * @augments UniformBuffer
  38562. */
  38563. class UniformsGroup extends UniformBuffer {
  38564. /**
  38565. * Constructs a new uniforms group.
  38566. *
  38567. * @param {string} name - The group's name.
  38568. */
  38569. constructor( name ) {
  38570. super( name );
  38571. /**
  38572. * This flag can be used for type testing.
  38573. *
  38574. * @type {boolean}
  38575. * @readonly
  38576. * @default true
  38577. */
  38578. this.isUniformsGroup = true;
  38579. /**
  38580. * An array with the raw uniform values.
  38581. *
  38582. * @private
  38583. * @type {?Array<number>}
  38584. * @default null
  38585. */
  38586. this._values = null;
  38587. /**
  38588. * An array of uniform objects.
  38589. *
  38590. * The order of uniforms in this array must match the order of uniforms in the shader.
  38591. *
  38592. * @type {Array<Uniform>}
  38593. */
  38594. this.uniforms = [];
  38595. }
  38596. /**
  38597. * Adds a uniform to this group.
  38598. *
  38599. * @param {Uniform} uniform - The uniform to add.
  38600. * @return {UniformsGroup} A reference to this group.
  38601. */
  38602. addUniform( uniform ) {
  38603. this.uniforms.push( uniform );
  38604. return this;
  38605. }
  38606. /**
  38607. * Removes a uniform from this group.
  38608. *
  38609. * @param {Uniform} uniform - The uniform to remove.
  38610. * @return {UniformsGroup} A reference to this group.
  38611. */
  38612. removeUniform( uniform ) {
  38613. const index = this.uniforms.indexOf( uniform );
  38614. if ( index !== -1 ) {
  38615. this.uniforms.splice( index, 1 );
  38616. }
  38617. return this;
  38618. }
  38619. /**
  38620. * An array with the raw uniform values.
  38621. *
  38622. * @type {Array<number>}
  38623. */
  38624. get values() {
  38625. if ( this._values === null ) {
  38626. this._values = Array.from( this.buffer );
  38627. }
  38628. return this._values;
  38629. }
  38630. /**
  38631. * A Float32 array buffer with the uniform values.
  38632. *
  38633. * @type {Float32Array}
  38634. */
  38635. get buffer() {
  38636. let buffer = this._buffer;
  38637. if ( buffer === null ) {
  38638. const byteLength = this.byteLength;
  38639. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38640. this._buffer = buffer;
  38641. }
  38642. return buffer;
  38643. }
  38644. /**
  38645. * The byte length of the buffer with correct buffer alignment.
  38646. *
  38647. * @type {number}
  38648. */
  38649. get byteLength() {
  38650. let offset = 0; // global buffer offset in bytes
  38651. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  38652. const uniform = this.uniforms[ i ];
  38653. const { boundary, itemSize } = uniform;
  38654. // offset within a single chunk in bytes
  38655. const chunkOffset = offset % GPU_CHUNK_BYTES;
  38656. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  38657. // conformance tests
  38658. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  38659. // check for chunk overflow
  38660. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  38661. } else if ( chunkOffset % boundary !== 0 ) {
  38662. // check for correct alignment
  38663. offset += ( chunkOffset % boundary );
  38664. }
  38665. uniform.offset = ( offset / this.bytesPerElement );
  38666. offset += ( itemSize * this.bytesPerElement );
  38667. }
  38668. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  38669. }
  38670. /**
  38671. * Updates this group by updating each uniform object of
  38672. * the internal uniform list. The uniform objects check if their
  38673. * values has actually changed so this method only returns
  38674. * `true` if there is a real value change.
  38675. *
  38676. * @return {boolean} Whether the uniforms have been updated and
  38677. * must be uploaded to the GPU.
  38678. */
  38679. update() {
  38680. let updated = false;
  38681. for ( const uniform of this.uniforms ) {
  38682. if ( this.updateByType( uniform ) === true ) {
  38683. updated = true;
  38684. }
  38685. }
  38686. return updated;
  38687. }
  38688. /**
  38689. * Updates a given uniform by calling an update method matching
  38690. * the uniforms type.
  38691. *
  38692. * @param {Uniform} uniform - The uniform to update.
  38693. * @return {boolean} Whether the uniform has been updated or not.
  38694. */
  38695. updateByType( uniform ) {
  38696. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  38697. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  38698. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  38699. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  38700. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  38701. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  38702. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  38703. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  38704. }
  38705. /**
  38706. * Updates a given Number uniform.
  38707. *
  38708. * @param {NumberUniform} uniform - The Number uniform.
  38709. * @return {boolean} Whether the uniform has been updated or not.
  38710. */
  38711. updateNumber( uniform ) {
  38712. let updated = false;
  38713. const a = this.values;
  38714. const v = uniform.getValue();
  38715. const offset = uniform.offset;
  38716. const type = uniform.getType();
  38717. if ( a[ offset ] !== v ) {
  38718. const b = this._getBufferForType( type );
  38719. b[ offset ] = a[ offset ] = v;
  38720. updated = true;
  38721. }
  38722. return updated;
  38723. }
  38724. /**
  38725. * Updates a given Vector2 uniform.
  38726. *
  38727. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  38728. * @return {boolean} Whether the uniform has been updated or not.
  38729. */
  38730. updateVector2( uniform ) {
  38731. let updated = false;
  38732. const a = this.values;
  38733. const v = uniform.getValue();
  38734. const offset = uniform.offset;
  38735. const type = uniform.getType();
  38736. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  38737. const b = this._getBufferForType( type );
  38738. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38739. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38740. updated = true;
  38741. }
  38742. return updated;
  38743. }
  38744. /**
  38745. * Updates a given Vector3 uniform.
  38746. *
  38747. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  38748. * @return {boolean} Whether the uniform has been updated or not.
  38749. */
  38750. updateVector3( uniform ) {
  38751. let updated = false;
  38752. const a = this.values;
  38753. const v = uniform.getValue();
  38754. const offset = uniform.offset;
  38755. const type = uniform.getType();
  38756. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38757. const b = this._getBufferForType( type );
  38758. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38759. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38760. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38761. updated = true;
  38762. }
  38763. return updated;
  38764. }
  38765. /**
  38766. * Updates a given Vector4 uniform.
  38767. *
  38768. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  38769. * @return {boolean} Whether the uniform has been updated or not.
  38770. */
  38771. updateVector4( uniform ) {
  38772. let updated = false;
  38773. const a = this.values;
  38774. const v = uniform.getValue();
  38775. const offset = uniform.offset;
  38776. const type = uniform.getType();
  38777. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38778. const b = this._getBufferForType( type );
  38779. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38780. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38781. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38782. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38783. updated = true;
  38784. }
  38785. return updated;
  38786. }
  38787. /**
  38788. * Updates a given Color uniform.
  38789. *
  38790. * @param {ColorUniform} uniform - The Color uniform.
  38791. * @return {boolean} Whether the uniform has been updated or not.
  38792. */
  38793. updateColor( uniform ) {
  38794. let updated = false;
  38795. const a = this.values;
  38796. const c = uniform.getValue();
  38797. const offset = uniform.offset;
  38798. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38799. const b = this.buffer;
  38800. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38801. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38802. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38803. updated = true;
  38804. }
  38805. return updated;
  38806. }
  38807. /**
  38808. * Updates a given Matrix3 uniform.
  38809. *
  38810. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  38811. * @return {boolean} Whether the uniform has been updated or not.
  38812. */
  38813. updateMatrix3( uniform ) {
  38814. let updated = false;
  38815. const a = this.values;
  38816. const e = uniform.getValue().elements;
  38817. const offset = uniform.offset;
  38818. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38819. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38820. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38821. const b = this.buffer;
  38822. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38823. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38824. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38825. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38826. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38827. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38828. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38829. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38830. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38831. updated = true;
  38832. }
  38833. return updated;
  38834. }
  38835. /**
  38836. * Updates a given Matrix4 uniform.
  38837. *
  38838. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  38839. * @return {boolean} Whether the uniform has been updated or not.
  38840. */
  38841. updateMatrix4( uniform ) {
  38842. let updated = false;
  38843. const a = this.values;
  38844. const e = uniform.getValue().elements;
  38845. const offset = uniform.offset;
  38846. if ( arraysEqual( a, e, offset ) === false ) {
  38847. const b = this.buffer;
  38848. b.set( e, offset );
  38849. setArray( a, e, offset );
  38850. updated = true;
  38851. }
  38852. return updated;
  38853. }
  38854. /**
  38855. * Returns a typed array that matches the given data type.
  38856. *
  38857. * @param {string} type - The data type.
  38858. * @return {TypedArray} The typed array.
  38859. */
  38860. _getBufferForType( type ) {
  38861. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  38862. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  38863. return this.buffer;
  38864. }
  38865. }
  38866. /**
  38867. * Sets the values of the second array to the first array.
  38868. *
  38869. * @private
  38870. * @param {TypedArray} a - The first array.
  38871. * @param {TypedArray} b - The second array.
  38872. * @param {number} offset - An index offset for the first array.
  38873. */
  38874. function setArray( a, b, offset ) {
  38875. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38876. a[ offset + i ] = b[ i ];
  38877. }
  38878. }
  38879. /**
  38880. * Returns `true` if the given arrays are equal.
  38881. *
  38882. * @private
  38883. * @param {TypedArray} a - The first array.
  38884. * @param {TypedArray} b - The second array.
  38885. * @param {number} offset - An index offset for the first array.
  38886. * @return {boolean} Whether the given arrays are equal or not.
  38887. */
  38888. function arraysEqual( a, b, offset ) {
  38889. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38890. if ( a[ offset + i ] !== b[ i ] ) return false;
  38891. }
  38892. return true;
  38893. }
  38894. let _id$3 = 0;
  38895. /**
  38896. * A special form of uniforms group that represents
  38897. * the individual uniforms as node-based uniforms.
  38898. *
  38899. * @private
  38900. * @augments UniformsGroup
  38901. */
  38902. class NodeUniformsGroup extends UniformsGroup {
  38903. /**
  38904. * Constructs a new node-based uniforms group.
  38905. *
  38906. * @param {string} name - The group's name.
  38907. * @param {UniformGroupNode} groupNode - The uniform group node.
  38908. */
  38909. constructor( name, groupNode ) {
  38910. super( name );
  38911. /**
  38912. * The group's ID.
  38913. *
  38914. * @type {number}
  38915. */
  38916. this.id = _id$3 ++;
  38917. /**
  38918. * The uniform group node.
  38919. *
  38920. * @type {UniformGroupNode}
  38921. */
  38922. this.groupNode = groupNode;
  38923. /**
  38924. * This flag can be used for type testing.
  38925. *
  38926. * @type {boolean}
  38927. * @readonly
  38928. * @default true
  38929. */
  38930. this.isNodeUniformsGroup = true;
  38931. }
  38932. }
  38933. let _id$2 = 0;
  38934. /**
  38935. * Represents a sampled texture binding type.
  38936. *
  38937. * @private
  38938. * @augments Binding
  38939. */
  38940. class SampledTexture extends Binding {
  38941. /**
  38942. * Constructs a new sampled texture.
  38943. *
  38944. * @param {string} name - The sampled texture's name.
  38945. * @param {?Texture} texture - The texture this binding is referring to.
  38946. */
  38947. constructor( name, texture ) {
  38948. super( name );
  38949. /**
  38950. * This identifier.
  38951. *
  38952. * @type {number}
  38953. */
  38954. this.id = _id$2 ++;
  38955. /**
  38956. * The texture this binding is referring to.
  38957. *
  38958. * @type {?Texture}
  38959. */
  38960. this.texture = texture;
  38961. /**
  38962. * The binding's version.
  38963. *
  38964. * @type {number}
  38965. */
  38966. this.version = texture ? texture.version : 0;
  38967. /**
  38968. * Whether the texture is a storage texture or not.
  38969. *
  38970. * @type {boolean}
  38971. * @default false
  38972. */
  38973. this.store = false;
  38974. /**
  38975. * The binding's generation which is an additional version
  38976. * qualifier.
  38977. *
  38978. * @type {?number}
  38979. * @default null
  38980. */
  38981. this.generation = null;
  38982. /**
  38983. * This flag can be used for type testing.
  38984. *
  38985. * @type {boolean}
  38986. * @readonly
  38987. * @default true
  38988. */
  38989. this.isSampledTexture = true;
  38990. }
  38991. /**
  38992. * Returns `true` whether this binding requires an update for the
  38993. * given generation.
  38994. *
  38995. * @param {number} generation - The generation.
  38996. * @return {boolean} Whether an update is required or not.
  38997. */
  38998. needsBindingsUpdate( generation ) {
  38999. const { texture } = this;
  39000. if ( generation !== this.generation ) {
  39001. this.generation = generation;
  39002. return true;
  39003. }
  39004. return texture.isVideoTexture;
  39005. }
  39006. /**
  39007. * Updates the binding.
  39008. *
  39009. * @return {boolean} Whether the texture has been updated and must be
  39010. * uploaded to the GPU.
  39011. */
  39012. update() {
  39013. const { texture, version } = this;
  39014. if ( version !== texture.version ) {
  39015. this.version = texture.version;
  39016. return true;
  39017. }
  39018. return false;
  39019. }
  39020. }
  39021. /**
  39022. * A special form of sampled texture binding type.
  39023. * It's texture value is managed by a node object.
  39024. *
  39025. * @private
  39026. * @augments SampledTexture
  39027. */
  39028. class NodeSampledTexture extends SampledTexture {
  39029. /**
  39030. * Constructs a new node-based sampled texture.
  39031. *
  39032. * @param {string} name - The textures's name.
  39033. * @param {TextureNode} textureNode - The texture node.
  39034. * @param {UniformGroupNode} groupNode - The uniform group node.
  39035. * @param {?string} [access=null] - The access type.
  39036. */
  39037. constructor( name, textureNode, groupNode, access = null ) {
  39038. super( name, textureNode ? textureNode.value : null );
  39039. /**
  39040. * The texture node.
  39041. *
  39042. * @type {TextureNode}
  39043. */
  39044. this.textureNode = textureNode;
  39045. /**
  39046. * The uniform group node.
  39047. *
  39048. * @type {UniformGroupNode}
  39049. */
  39050. this.groupNode = groupNode;
  39051. /**
  39052. * The access type.
  39053. *
  39054. * @type {?string}
  39055. * @default null
  39056. */
  39057. this.access = access;
  39058. }
  39059. /**
  39060. * Overwrites the default to additionally check if the node value has changed.
  39061. *
  39062. * @param {number} generation - The generation.
  39063. * @return {boolean} Whether an update is required or not.
  39064. */
  39065. needsBindingsUpdate( generation ) {
  39066. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  39067. }
  39068. /**
  39069. * Updates the binding.
  39070. *
  39071. * @return {boolean} Whether the texture has been updated and must be
  39072. * uploaded to the GPU.
  39073. */
  39074. update() {
  39075. const { textureNode } = this;
  39076. if ( this.texture !== textureNode.value ) {
  39077. this.texture = textureNode.value;
  39078. return true;
  39079. }
  39080. return super.update();
  39081. }
  39082. }
  39083. /**
  39084. * A special form of sampled cube texture binding type.
  39085. * It's texture value is managed by a node object.
  39086. *
  39087. * @private
  39088. * @augments NodeSampledTexture
  39089. */
  39090. class NodeSampledCubeTexture extends NodeSampledTexture {
  39091. /**
  39092. * Constructs a new node-based sampled cube texture.
  39093. *
  39094. * @param {string} name - The textures's name.
  39095. * @param {TextureNode} textureNode - The texture node.
  39096. * @param {UniformGroupNode} groupNode - The uniform group node.
  39097. * @param {?string} [access=null] - The access type.
  39098. */
  39099. constructor( name, textureNode, groupNode, access = null ) {
  39100. super( name, textureNode, groupNode, access );
  39101. /**
  39102. * This flag can be used for type testing.
  39103. *
  39104. * @type {boolean}
  39105. * @readonly
  39106. * @default true
  39107. */
  39108. this.isSampledCubeTexture = true;
  39109. }
  39110. }
  39111. /**
  39112. * A special form of sampled 3D texture binding type.
  39113. * It's texture value is managed by a node object.
  39114. *
  39115. * @private
  39116. * @augments NodeSampledTexture
  39117. */
  39118. class NodeSampledTexture3D extends NodeSampledTexture {
  39119. /**
  39120. * Constructs a new node-based sampled 3D texture.
  39121. *
  39122. * @param {string} name - The textures's name.
  39123. * @param {TextureNode} textureNode - The texture node.
  39124. * @param {UniformGroupNode} groupNode - The uniform group node.
  39125. * @param {?string} [access=null] - The access type.
  39126. */
  39127. constructor( name, textureNode, groupNode, access = null ) {
  39128. super( name, textureNode, groupNode, access );
  39129. /**
  39130. * This flag can be used for type testing.
  39131. *
  39132. * @type {boolean}
  39133. * @readonly
  39134. * @default true
  39135. */
  39136. this.isSampledTexture3D = true;
  39137. }
  39138. }
  39139. const glslMethods = {
  39140. textureDimensions: 'textureSize',
  39141. equals: 'equal'
  39142. };
  39143. const precisionLib = {
  39144. low: 'lowp',
  39145. medium: 'mediump',
  39146. high: 'highp'
  39147. };
  39148. const supports$1 = {
  39149. swizzleAssign: true,
  39150. storageBuffer: false
  39151. };
  39152. const interpolationTypeMap = {
  39153. perspective: 'smooth',
  39154. linear: 'noperspective'
  39155. };
  39156. const interpolationModeMap = {
  39157. 'centroid': 'centroid',
  39158. 'flat first': 'flat',
  39159. 'flat either': 'flat'
  39160. };
  39161. const defaultPrecisions = `
  39162. precision highp float;
  39163. precision highp int;
  39164. precision highp sampler2D;
  39165. precision highp sampler3D;
  39166. precision highp samplerCube;
  39167. precision highp sampler2DArray;
  39168. precision highp usampler2D;
  39169. precision highp usampler3D;
  39170. precision highp usamplerCube;
  39171. precision highp usampler2DArray;
  39172. precision highp isampler2D;
  39173. precision highp isampler3D;
  39174. precision highp isamplerCube;
  39175. precision highp isampler2DArray;
  39176. precision lowp sampler2DShadow;
  39177. precision lowp sampler2DArrayShadow;
  39178. precision lowp samplerCubeShadow;
  39179. `;
  39180. /**
  39181. * A node builder targeting GLSL.
  39182. *
  39183. * This module generates GLSL shader code from node materials and also
  39184. * generates the respective bindings and vertex buffer definitions. These
  39185. * data are later used by the renderer to create render and compute pipelines
  39186. * for render objects.
  39187. *
  39188. * @augments NodeBuilder
  39189. */
  39190. class GLSLNodeBuilder extends NodeBuilder {
  39191. /**
  39192. * Constructs a new GLSL node builder renderer.
  39193. *
  39194. * @param {Object3D} object - The 3D object.
  39195. * @param {Renderer} renderer - The renderer.
  39196. */
  39197. constructor( object, renderer ) {
  39198. super( object, renderer, new GLSLNodeParser() );
  39199. /**
  39200. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  39201. * another dictionary which manages UBOs per group ('render','frame','object').
  39202. *
  39203. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  39204. */
  39205. this.uniformGroups = {};
  39206. /**
  39207. * An array that holds objects defining the varying and attribute data in
  39208. * context of Transform Feedback.
  39209. *
  39210. * @type {Array<Object<string,AttributeNode|string>>}
  39211. */
  39212. this.transforms = [];
  39213. /**
  39214. * A dictionary that holds for each shader stage a Map of used extensions.
  39215. *
  39216. * @type {Object<string,Map<string,Object>>}
  39217. */
  39218. this.extensions = {};
  39219. /**
  39220. * A dictionary that holds for each shader stage an Array of used builtins.
  39221. *
  39222. * @type {Object<string,Array<string>>}
  39223. */
  39224. this.builtins = { vertex: [], fragment: [], compute: [] };
  39225. }
  39226. /**
  39227. * Checks if the given texture requires a manual conversion to the working color space.
  39228. *
  39229. * @param {Texture} texture - The texture to check.
  39230. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  39231. */
  39232. needsToWorkingColorSpace( texture ) {
  39233. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  39234. }
  39235. /**
  39236. * Returns the native shader method name for a given generic name.
  39237. *
  39238. * @param {string} method - The method name to resolve.
  39239. * @return {string} The resolved GLSL method name.
  39240. */
  39241. getMethod( method ) {
  39242. return glslMethods[ method ] || method;
  39243. }
  39244. /**
  39245. * Returns the output struct name. Not relevant for GLSL.
  39246. *
  39247. * @return {string}
  39248. */
  39249. getOutputStructName() {
  39250. return '';
  39251. }
  39252. /**
  39253. * Builds the given shader node.
  39254. *
  39255. * @param {ShaderNodeInternal} shaderNode - The shader node.
  39256. * @return {string} The GLSL function code.
  39257. */
  39258. buildFunctionCode( shaderNode ) {
  39259. const layout = shaderNode.layout;
  39260. const flowData = this.flowShaderNode( shaderNode );
  39261. const parameters = [];
  39262. for ( const input of layout.inputs ) {
  39263. parameters.push( this.getType( input.type ) + ' ' + input.name );
  39264. }
  39265. //
  39266. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  39267. ${ flowData.vars }
  39268. ${ flowData.code }
  39269. return ${ flowData.result };
  39270. }`;
  39271. //
  39272. return code;
  39273. }
  39274. /**
  39275. * Setups the Pixel Buffer Object (PBO) for the given storage
  39276. * buffer node.
  39277. *
  39278. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  39279. */
  39280. setupPBO( storageBufferNode ) {
  39281. const attribute = storageBufferNode.value;
  39282. if ( attribute.pbo === undefined ) {
  39283. const originalArray = attribute.array;
  39284. const numElements = attribute.count * attribute.itemSize;
  39285. const { itemSize } = attribute;
  39286. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  39287. let format = isInteger ? RedIntegerFormat : RedFormat;
  39288. if ( itemSize === 2 ) {
  39289. format = isInteger ? RGIntegerFormat : RGFormat;
  39290. } else if ( itemSize === 3 ) {
  39291. format = isInteger ? RGBIntegerFormat : RGBFormat;
  39292. } else if ( itemSize === 4 ) {
  39293. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  39294. }
  39295. const typeMap = {
  39296. Float32Array: FloatType,
  39297. Uint8Array: UnsignedByteType,
  39298. Uint16Array: UnsignedShortType,
  39299. Uint32Array: UnsignedIntType,
  39300. Int8Array: ByteType,
  39301. Int16Array: ShortType,
  39302. Int32Array: IntType,
  39303. Uint8ClampedArray: UnsignedByteType,
  39304. };
  39305. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  39306. let height = Math.ceil( ( numElements / itemSize ) / width );
  39307. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  39308. const newSize = width * height * itemSize;
  39309. const newArray = new originalArray.constructor( newSize );
  39310. newArray.set( originalArray, 0 );
  39311. attribute.array = newArray;
  39312. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  39313. pboTexture.needsUpdate = true;
  39314. pboTexture.isPBOTexture = true;
  39315. const pbo = new TextureNode( pboTexture, null, null );
  39316. pbo.setPrecision( 'high' );
  39317. attribute.pboNode = pbo;
  39318. attribute.pbo = pbo.value;
  39319. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39320. }
  39321. }
  39322. /**
  39323. * Returns a GLSL snippet that represents the property name of the given node.
  39324. *
  39325. * @param {Node} node - The node.
  39326. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39327. * @return {string} The property name.
  39328. */
  39329. getPropertyName( node, shaderStage = this.shaderStage ) {
  39330. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  39331. return shaderStage.charAt( 0 ) + '_' + node.name;
  39332. }
  39333. return super.getPropertyName( node, shaderStage );
  39334. }
  39335. /**
  39336. * Setups the Pixel Buffer Object (PBO) for the given storage
  39337. * buffer node.
  39338. *
  39339. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  39340. * @return {string} The property name.
  39341. */
  39342. generatePBO( storageArrayElementNode ) {
  39343. const { node, indexNode } = storageArrayElementNode;
  39344. const attribute = node.value;
  39345. if ( this.renderer.backend.has( attribute ) ) {
  39346. const attributeData = this.renderer.backend.get( attribute );
  39347. attributeData.pbo = attribute.pbo;
  39348. }
  39349. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39350. const textureName = this.getPropertyName( nodeUniform );
  39351. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  39352. const indexSnippet = indexNode.build( this, 'uint' );
  39353. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  39354. let propertyName = elementNodeData.propertyName;
  39355. if ( propertyName === undefined ) {
  39356. // property element
  39357. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  39358. propertyName = this.getPropertyName( nodeVar );
  39359. // property size
  39360. const bufferNodeData = this.getDataFromNode( node );
  39361. let propertySizeName = bufferNodeData.propertySizeName;
  39362. if ( propertySizeName === undefined ) {
  39363. propertySizeName = propertyName + 'Size';
  39364. this.getVarFromNode( node, propertySizeName, 'uint' );
  39365. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  39366. bufferNodeData.propertySizeName = propertySizeName;
  39367. }
  39368. //
  39369. const { itemSize } = attribute;
  39370. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  39371. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  39372. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  39373. //
  39374. let prefix = 'vec4';
  39375. if ( attribute.pbo.type === UnsignedIntType ) {
  39376. prefix = 'uvec4';
  39377. } else if ( attribute.pbo.type === IntType ) {
  39378. prefix = 'ivec4';
  39379. }
  39380. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  39381. elementNodeData.propertyName = propertyName;
  39382. }
  39383. return propertyName;
  39384. }
  39385. /**
  39386. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  39387. *
  39388. * @param {Texture} texture - The texture.
  39389. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39390. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39391. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39392. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39393. * @return {string} The GLSL snippet.
  39394. */
  39395. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  39396. if ( depthSnippet ) {
  39397. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  39398. } else {
  39399. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  39400. }
  39401. }
  39402. /**
  39403. * Generates the GLSL snippet for sampling/loading the given texture.
  39404. *
  39405. * @param {Texture} texture - The texture.
  39406. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39407. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39408. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39409. * @return {string} The GLSL snippet.
  39410. */
  39411. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  39412. if ( texture.isDepthTexture ) {
  39413. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  39414. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  39415. } else {
  39416. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  39417. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  39418. }
  39419. }
  39420. /**
  39421. * Generates the GLSL snippet when sampling textures with explicit mip level.
  39422. *
  39423. * @param {Texture} texture - The texture.
  39424. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39425. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39426. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39427. * @return {string} The GLSL snippet.
  39428. */
  39429. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  39430. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  39431. }
  39432. /**
  39433. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  39434. *
  39435. * @param {Texture} texture - The texture.
  39436. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39437. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39438. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  39439. * @return {string} The GLSL snippet.
  39440. */
  39441. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  39442. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  39443. }
  39444. /**
  39445. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  39446. *
  39447. * @param {Texture} texture - The texture.
  39448. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39449. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39450. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  39451. * @return {string} The GLSL snippet.
  39452. */
  39453. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  39454. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  39455. }
  39456. /**
  39457. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  39458. * against a reference value.
  39459. *
  39460. * @param {Texture} texture - The texture.
  39461. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39462. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39463. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  39464. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  39465. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39466. * @return {string} The GLSL snippet.
  39467. */
  39468. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  39469. if ( shaderStage === 'fragment' ) {
  39470. if ( depthSnippet ) {
  39471. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  39472. }
  39473. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  39474. } else {
  39475. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  39476. }
  39477. }
  39478. /**
  39479. * Returns the variables of the given shader stage as a GLSL string.
  39480. *
  39481. * @param {string} shaderStage - The shader stage.
  39482. * @return {string} The GLSL snippet that defines the variables.
  39483. */
  39484. getVars( shaderStage ) {
  39485. const snippets = [];
  39486. const vars = this.vars[ shaderStage ];
  39487. if ( vars !== undefined ) {
  39488. for ( const variable of vars ) {
  39489. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  39490. }
  39491. }
  39492. return snippets.join( '\n\t' );
  39493. }
  39494. /**
  39495. * Returns the uniforms of the given shader stage as a GLSL string.
  39496. *
  39497. * @param {string} shaderStage - The shader stage.
  39498. * @return {string} The GLSL snippet that defines the uniforms.
  39499. */
  39500. getUniforms( shaderStage ) {
  39501. const uniforms = this.uniforms[ shaderStage ];
  39502. const bindingSnippets = [];
  39503. const uniformGroups = {};
  39504. for ( const uniform of uniforms ) {
  39505. let snippet = null;
  39506. let group = false;
  39507. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  39508. const texture = uniform.node.value;
  39509. let typePrefix = '';
  39510. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  39511. if ( texture.type === UnsignedIntType ) {
  39512. typePrefix = 'u';
  39513. } else if ( texture.type === IntType ) {
  39514. typePrefix = 'i';
  39515. }
  39516. }
  39517. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  39518. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  39519. } else if ( texture.compareFunction ) {
  39520. if ( texture.isArrayTexture === true ) {
  39521. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  39522. } else {
  39523. snippet = `sampler2DShadow ${ uniform.name };`;
  39524. }
  39525. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39526. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  39527. } else {
  39528. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  39529. }
  39530. } else if ( uniform.type === 'cubeTexture' ) {
  39531. snippet = `samplerCube ${ uniform.name };`;
  39532. } else if ( uniform.type === 'buffer' ) {
  39533. const bufferNode = uniform.node;
  39534. const bufferType = this.getType( bufferNode.bufferType );
  39535. const bufferCount = bufferNode.bufferCount;
  39536. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  39537. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  39538. } else {
  39539. const vectorType = this.getVectorType( uniform.type );
  39540. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  39541. group = true;
  39542. }
  39543. const precision = uniform.node.precision;
  39544. if ( precision !== null ) {
  39545. snippet = precisionLib[ precision ] + ' ' + snippet;
  39546. }
  39547. if ( group ) {
  39548. snippet = '\t' + snippet;
  39549. const groupName = uniform.groupNode.name;
  39550. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  39551. groupSnippets.push( snippet );
  39552. } else {
  39553. snippet = 'uniform ' + snippet;
  39554. bindingSnippets.push( snippet );
  39555. }
  39556. }
  39557. let output = '';
  39558. for ( const name in uniformGroups ) {
  39559. const groupSnippets = uniformGroups[ name ];
  39560. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  39561. }
  39562. output += bindingSnippets.join( '\n' );
  39563. return output;
  39564. }
  39565. /**
  39566. * Returns the type for a given buffer attribute.
  39567. *
  39568. * @param {BufferAttribute} attribute - The buffer attribute.
  39569. * @return {string} The type.
  39570. */
  39571. getTypeFromAttribute( attribute ) {
  39572. let nodeType = super.getTypeFromAttribute( attribute );
  39573. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  39574. let dataAttribute = attribute;
  39575. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  39576. const array = dataAttribute.array;
  39577. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  39578. nodeType = nodeType.slice( 1 );
  39579. }
  39580. }
  39581. return nodeType;
  39582. }
  39583. /**
  39584. * Returns the shader attributes of the given shader stage as a GLSL string.
  39585. *
  39586. * @param {string} shaderStage - The shader stage.
  39587. * @return {string} The GLSL snippet that defines the shader attributes.
  39588. */
  39589. getAttributes( shaderStage ) {
  39590. let snippet = '';
  39591. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39592. const attributes = this.getAttributesArray();
  39593. let location = 0;
  39594. for ( const attribute of attributes ) {
  39595. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  39596. }
  39597. }
  39598. return snippet;
  39599. }
  39600. /**
  39601. * Returns the members of the given struct type node as a GLSL string.
  39602. *
  39603. * @param {StructTypeNode} struct - The struct type node.
  39604. * @return {string} The GLSL snippet that defines the struct members.
  39605. */
  39606. getStructMembers( struct ) {
  39607. const snippets = [];
  39608. for ( const member of struct.members ) {
  39609. snippets.push( `\t${ member.type } ${ member.name };` );
  39610. }
  39611. return snippets.join( '\n' );
  39612. }
  39613. /**
  39614. * Returns the structs of the given shader stage as a GLSL string.
  39615. *
  39616. * @param {string} shaderStage - The shader stage.
  39617. * @return {string} The GLSL snippet that defines the structs.
  39618. */
  39619. getStructs( shaderStage ) {
  39620. const snippets = [];
  39621. const structs = this.structs[ shaderStage ];
  39622. const outputSnippet = [];
  39623. for ( const struct of structs ) {
  39624. if ( struct.output ) {
  39625. for ( const member of struct.members ) {
  39626. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  39627. }
  39628. } else {
  39629. let snippet = 'struct ' + struct.name + ' {\n';
  39630. snippet += this.getStructMembers( struct );
  39631. snippet += '\n};\n';
  39632. snippets.push( snippet );
  39633. }
  39634. }
  39635. if ( outputSnippet.length === 0 ) {
  39636. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  39637. }
  39638. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  39639. }
  39640. /**
  39641. * Returns the varyings of the given shader stage as a GLSL string.
  39642. *
  39643. * @param {string} shaderStage - The shader stage.
  39644. * @return {string} The GLSL snippet that defines the varyings.
  39645. */
  39646. getVaryings( shaderStage ) {
  39647. let snippet = '';
  39648. const varyings = this.varyings;
  39649. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39650. for ( const varying of varyings ) {
  39651. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  39652. const type = this.getType( varying.type );
  39653. if ( varying.needsInterpolation ) {
  39654. if ( varying.interpolationType ) {
  39655. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  39656. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  39657. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  39658. } else {
  39659. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39660. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  39661. }
  39662. } else {
  39663. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  39664. }
  39665. }
  39666. } else if ( shaderStage === 'fragment' ) {
  39667. for ( const varying of varyings ) {
  39668. if ( varying.needsInterpolation ) {
  39669. const type = this.getType( varying.type );
  39670. if ( varying.interpolationType ) {
  39671. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  39672. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  39673. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  39674. } else {
  39675. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39676. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  39677. }
  39678. }
  39679. }
  39680. }
  39681. for ( const builtin of this.builtins[ shaderStage ] ) {
  39682. snippet += `${builtin};\n`;
  39683. }
  39684. return snippet;
  39685. }
  39686. /**
  39687. * Returns the vertex index builtin.
  39688. *
  39689. * @return {string} The vertex index.
  39690. */
  39691. getVertexIndex() {
  39692. return 'uint( gl_VertexID )';
  39693. }
  39694. /**
  39695. * Returns the instance index builtin.
  39696. *
  39697. * @return {string} The instance index.
  39698. */
  39699. getInstanceIndex() {
  39700. return 'uint( gl_InstanceID )';
  39701. }
  39702. /**
  39703. * Returns the invocation local index builtin.
  39704. *
  39705. * @return {string} The invocation local index.
  39706. */
  39707. getInvocationLocalIndex() {
  39708. const workgroupSize = this.object.workgroupSize;
  39709. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  39710. return `uint( gl_InstanceID ) % ${size}u`;
  39711. }
  39712. /**
  39713. * Returns the draw index builtin.
  39714. *
  39715. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  39716. */
  39717. getDrawIndex() {
  39718. const extensions = this.renderer.backend.extensions;
  39719. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  39720. return 'uint( gl_DrawID )';
  39721. }
  39722. return null;
  39723. }
  39724. /**
  39725. * Returns the front facing builtin.
  39726. *
  39727. * @return {string} The front facing builtin.
  39728. */
  39729. getFrontFacing() {
  39730. return 'gl_FrontFacing';
  39731. }
  39732. /**
  39733. * Returns the frag coord builtin.
  39734. *
  39735. * @return {string} The frag coord builtin.
  39736. */
  39737. getFragCoord() {
  39738. return 'gl_FragCoord.xy';
  39739. }
  39740. /**
  39741. * Returns the frag depth builtin.
  39742. *
  39743. * @return {string} The frag depth builtin.
  39744. */
  39745. getFragDepth() {
  39746. return 'gl_FragDepth';
  39747. }
  39748. /**
  39749. * Enables the given extension.
  39750. *
  39751. * @param {string} name - The extension name.
  39752. * @param {string} behavior - The extension behavior.
  39753. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  39754. */
  39755. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  39756. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  39757. if ( map.has( name ) === false ) {
  39758. map.set( name, {
  39759. name,
  39760. behavior
  39761. } );
  39762. }
  39763. }
  39764. /**
  39765. * Returns the enabled extensions of the given shader stage as a GLSL string.
  39766. *
  39767. * @param {string} shaderStage - The shader stage.
  39768. * @return {string} The GLSL snippet that defines the enabled extensions.
  39769. */
  39770. getExtensions( shaderStage ) {
  39771. const snippets = [];
  39772. if ( shaderStage === 'vertex' ) {
  39773. const ext = this.renderer.backend.extensions;
  39774. const isBatchedMesh = this.object.isBatchedMesh;
  39775. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  39776. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  39777. }
  39778. }
  39779. const extensions = this.extensions[ shaderStage ];
  39780. if ( extensions !== undefined ) {
  39781. for ( const { name, behavior } of extensions.values() ) {
  39782. snippets.push( `#extension ${name} : ${behavior}` );
  39783. }
  39784. }
  39785. return snippets.join( '\n' );
  39786. }
  39787. /**
  39788. * Returns the clip distances builtin.
  39789. *
  39790. * @return {string} The clip distances builtin.
  39791. */
  39792. getClipDistance() {
  39793. return 'gl_ClipDistance';
  39794. }
  39795. /**
  39796. * Whether the requested feature is available or not.
  39797. *
  39798. * @param {string} name - The requested feature.
  39799. * @return {boolean} Whether the requested feature is supported or not.
  39800. */
  39801. isAvailable( name ) {
  39802. let result = supports$1[ name ];
  39803. if ( result === undefined ) {
  39804. let extensionName;
  39805. result = false;
  39806. switch ( name ) {
  39807. case 'float32Filterable':
  39808. extensionName = 'OES_texture_float_linear';
  39809. break;
  39810. case 'clipDistance':
  39811. extensionName = 'WEBGL_clip_cull_distance';
  39812. break;
  39813. }
  39814. if ( extensionName !== undefined ) {
  39815. const extensions = this.renderer.backend.extensions;
  39816. if ( extensions.has( extensionName ) ) {
  39817. extensions.get( extensionName );
  39818. result = true;
  39819. }
  39820. }
  39821. supports$1[ name ] = result;
  39822. }
  39823. return result;
  39824. }
  39825. /**
  39826. * Whether to flip texture data along its vertical axis or not.
  39827. *
  39828. * @return {boolean} Returns always `true` in context of GLSL.
  39829. */
  39830. isFlipY() {
  39831. return true;
  39832. }
  39833. /**
  39834. * Enables hardware clipping.
  39835. *
  39836. * @param {string} planeCount - The clipping plane count.
  39837. */
  39838. enableHardwareClipping( planeCount ) {
  39839. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  39840. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  39841. }
  39842. /**
  39843. * Enables multiview.
  39844. */
  39845. enableMultiview() {
  39846. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  39847. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  39848. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  39849. }
  39850. /**
  39851. * Registers a transform in context of Transform Feedback.
  39852. *
  39853. * @param {string} varyingName - The varying name.
  39854. * @param {AttributeNode} attributeNode - The attribute node.
  39855. */
  39856. registerTransform( varyingName, attributeNode ) {
  39857. this.transforms.push( { varyingName, attributeNode } );
  39858. }
  39859. /**
  39860. * Returns the transforms of the given shader stage as a GLSL string.
  39861. *
  39862. * @param {string} shaderStage - The shader stage.
  39863. * @return {string} The GLSL snippet that defines the transforms.
  39864. */
  39865. getTransforms( /* shaderStage */ ) {
  39866. const transforms = this.transforms;
  39867. let snippet = '';
  39868. for ( let i = 0; i < transforms.length; i ++ ) {
  39869. const transform = transforms[ i ];
  39870. const attributeName = this.getPropertyName( transform.attributeNode );
  39871. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  39872. }
  39873. return snippet;
  39874. }
  39875. /**
  39876. * Returns a GLSL struct based on the given name and variables.
  39877. *
  39878. * @private
  39879. * @param {string} name - The struct name.
  39880. * @param {string} vars - The struct variables.
  39881. * @return {string} The GLSL snippet representing a struct.
  39882. */
  39883. _getGLSLUniformStruct( name, vars ) {
  39884. return `
  39885. layout( std140 ) uniform ${name} {
  39886. ${vars}
  39887. };`;
  39888. }
  39889. /**
  39890. * Returns a GLSL vertex shader based on the given shader data.
  39891. *
  39892. * @private
  39893. * @param {Object} shaderData - The shader data.
  39894. * @return {string} The vertex shader.
  39895. */
  39896. _getGLSLVertexCode( shaderData ) {
  39897. return `#version 300 es
  39898. ${ this.getSignature() }
  39899. // extensions
  39900. ${shaderData.extensions}
  39901. // precision
  39902. ${ defaultPrecisions }
  39903. // uniforms
  39904. ${shaderData.uniforms}
  39905. // varyings
  39906. ${shaderData.varyings}
  39907. // attributes
  39908. ${shaderData.attributes}
  39909. // codes
  39910. ${shaderData.codes}
  39911. void main() {
  39912. // vars
  39913. ${shaderData.vars}
  39914. // transforms
  39915. ${shaderData.transforms}
  39916. // flow
  39917. ${shaderData.flow}
  39918. gl_PointSize = 1.0;
  39919. }
  39920. `;
  39921. }
  39922. /**
  39923. * Returns a GLSL fragment shader based on the given shader data.
  39924. *
  39925. * @private
  39926. * @param {Object} shaderData - The shader data.
  39927. * @return {string} The vertex shader.
  39928. */
  39929. _getGLSLFragmentCode( shaderData ) {
  39930. return `#version 300 es
  39931. ${ this.getSignature() }
  39932. // extensions
  39933. ${shaderData.extensions}
  39934. // precision
  39935. ${ defaultPrecisions }
  39936. // uniforms
  39937. ${shaderData.uniforms}
  39938. // varyings
  39939. ${shaderData.varyings}
  39940. // codes
  39941. ${shaderData.codes}
  39942. // structs
  39943. ${shaderData.structs}
  39944. void main() {
  39945. // vars
  39946. ${shaderData.vars}
  39947. // flow
  39948. ${shaderData.flow}
  39949. }
  39950. `;
  39951. }
  39952. /**
  39953. * Controls the code build of the shader stages.
  39954. */
  39955. buildCode() {
  39956. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  39957. this.sortBindingGroups();
  39958. for ( const shaderStage in shadersData ) {
  39959. let flow = '// code\n\n';
  39960. flow += this.flowCode[ shaderStage ];
  39961. const flowNodes = this.flowNodes[ shaderStage ];
  39962. const mainNode = flowNodes[ flowNodes.length - 1 ];
  39963. for ( const node of flowNodes ) {
  39964. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  39965. const slotName = node.name;
  39966. if ( slotName ) {
  39967. if ( flow.length > 0 ) flow += '\n';
  39968. flow += `\t// flow -> ${ slotName }\n\t`;
  39969. }
  39970. flow += `${ flowSlotData.code }\n\t`;
  39971. if ( node === mainNode && shaderStage !== 'compute' ) {
  39972. flow += '// result\n\t';
  39973. if ( shaderStage === 'vertex' ) {
  39974. flow += 'gl_Position = ';
  39975. flow += `${ flowSlotData.result };`;
  39976. } else if ( shaderStage === 'fragment' ) {
  39977. if ( ! node.outputNode.isOutputStructNode ) {
  39978. flow += 'fragColor = ';
  39979. flow += `${ flowSlotData.result };`;
  39980. }
  39981. }
  39982. }
  39983. }
  39984. const stageData = shadersData[ shaderStage ];
  39985. stageData.extensions = this.getExtensions( shaderStage );
  39986. stageData.uniforms = this.getUniforms( shaderStage );
  39987. stageData.attributes = this.getAttributes( shaderStage );
  39988. stageData.varyings = this.getVaryings( shaderStage );
  39989. stageData.vars = this.getVars( shaderStage );
  39990. stageData.structs = this.getStructs( shaderStage );
  39991. stageData.codes = this.getCodes( shaderStage );
  39992. stageData.transforms = this.getTransforms( shaderStage );
  39993. stageData.flow = flow;
  39994. }
  39995. if ( this.material !== null ) {
  39996. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39997. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39998. } else {
  39999. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  40000. }
  40001. }
  40002. /**
  40003. * This method is one of the more important ones since it's responsible
  40004. * for generating a matching binding instance for the given uniform node.
  40005. *
  40006. * These bindings are later used in the renderer to create bind groups
  40007. * and layouts.
  40008. *
  40009. * @param {UniformNode} node - The uniform node.
  40010. * @param {string} type - The node data type.
  40011. * @param {string} shaderStage - The shader stage.
  40012. * @param {?string} [name=null] - An optional uniform name.
  40013. * @return {NodeUniform} The node uniform object.
  40014. */
  40015. getUniformFromNode( node, type, shaderStage, name = null ) {
  40016. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  40017. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  40018. let uniformGPU = nodeData.uniformGPU;
  40019. if ( uniformGPU === undefined ) {
  40020. const group = node.groupNode;
  40021. const groupName = group.name;
  40022. const bindings = this.getBindGroupArray( groupName, shaderStage );
  40023. if ( type === 'texture' ) {
  40024. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  40025. bindings.push( uniformGPU );
  40026. } else if ( type === 'cubeTexture' ) {
  40027. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  40028. bindings.push( uniformGPU );
  40029. } else if ( type === 'texture3D' ) {
  40030. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  40031. bindings.push( uniformGPU );
  40032. } else if ( type === 'buffer' ) {
  40033. node.name = `NodeBuffer_${ node.id }`;
  40034. uniformNode.name = `buffer${ node.id }`;
  40035. const buffer = new NodeUniformBuffer( node, group );
  40036. buffer.name = node.name;
  40037. bindings.push( buffer );
  40038. uniformGPU = buffer;
  40039. } else {
  40040. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  40041. let uniformsGroup = uniformsStage[ groupName ];
  40042. if ( uniformsGroup === undefined ) {
  40043. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  40044. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40045. uniformsStage[ groupName ] = uniformsGroup;
  40046. bindings.push( uniformsGroup );
  40047. }
  40048. uniformGPU = this.getNodeUniform( uniformNode, type );
  40049. uniformsGroup.addUniform( uniformGPU );
  40050. }
  40051. nodeData.uniformGPU = uniformGPU;
  40052. }
  40053. return uniformNode;
  40054. }
  40055. }
  40056. let _vector2 = null;
  40057. let _color4 = null;
  40058. /**
  40059. * Most of the rendering related logic is implemented in the
  40060. * {@link Renderer} module and related management components.
  40061. * Sometimes it is required though to execute commands which are
  40062. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  40063. * This abstract base class defines an interface that encapsulates
  40064. * all backend-related logic. Derived classes for each backend must
  40065. * implement the interface.
  40066. *
  40067. * @abstract
  40068. * @private
  40069. */
  40070. class Backend {
  40071. /**
  40072. * Constructs a new backend.
  40073. *
  40074. * @param {Object} parameters - An object holding parameters for the backend.
  40075. */
  40076. constructor( parameters = {} ) {
  40077. /**
  40078. * The parameters of the backend.
  40079. *
  40080. * @type {Object}
  40081. */
  40082. this.parameters = Object.assign( {}, parameters );
  40083. /**
  40084. * This weak map holds backend-specific data of objects
  40085. * like textures, attributes or render targets.
  40086. *
  40087. * @type {WeakMap}
  40088. */
  40089. this.data = new WeakMap();
  40090. /**
  40091. * A reference to the renderer.
  40092. *
  40093. * @type {?Renderer}
  40094. * @default null
  40095. */
  40096. this.renderer = null;
  40097. /**
  40098. * A reference to the canvas element the renderer is drawing to.
  40099. *
  40100. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  40101. * @default null
  40102. */
  40103. this.domElement = null;
  40104. /**
  40105. * A reference to the timestamp query pool.
  40106. *
  40107. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  40108. */
  40109. this.timestampQueryPool = {
  40110. 'render': null,
  40111. 'compute': null
  40112. };
  40113. /**
  40114. * Whether to track timestamps with a Timestamp Query API or not.
  40115. *
  40116. * @type {boolean}
  40117. * @default false
  40118. */
  40119. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40120. }
  40121. /**
  40122. * Initializes the backend so it is ready for usage. Concrete backends
  40123. * are supposed to implement their rendering context creation and related
  40124. * operations in this method.
  40125. *
  40126. * @async
  40127. * @param {Renderer} renderer - The renderer.
  40128. * @return {Promise} A Promise that resolves when the backend has been initialized.
  40129. */
  40130. async init( renderer ) {
  40131. this.renderer = renderer;
  40132. }
  40133. /**
  40134. * The coordinate system of the backend.
  40135. *
  40136. * @abstract
  40137. * @type {number}
  40138. * @readonly
  40139. */
  40140. get coordinateSystem() {}
  40141. // render context
  40142. /**
  40143. * This method is executed at the beginning of a render call and
  40144. * can be used by the backend to prepare the state for upcoming
  40145. * draw calls.
  40146. *
  40147. * @abstract
  40148. * @param {RenderContext} renderContext - The render context.
  40149. */
  40150. beginRender( /*renderContext*/ ) {}
  40151. /**
  40152. * This method is executed at the end of a render call and
  40153. * can be used by the backend to finalize work after draw
  40154. * calls.
  40155. *
  40156. * @abstract
  40157. * @param {RenderContext} renderContext - The render context.
  40158. */
  40159. finishRender( /*renderContext*/ ) {}
  40160. /**
  40161. * This method is executed at the beginning of a compute call and
  40162. * can be used by the backend to prepare the state for upcoming
  40163. * compute tasks.
  40164. *
  40165. * @abstract
  40166. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40167. */
  40168. beginCompute( /*computeGroup*/ ) {}
  40169. /**
  40170. * This method is executed at the end of a compute call and
  40171. * can be used by the backend to finalize work after compute
  40172. * tasks.
  40173. *
  40174. * @abstract
  40175. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40176. */
  40177. finishCompute( /*computeGroup*/ ) {}
  40178. // render object
  40179. /**
  40180. * Executes a draw command for the given render object.
  40181. *
  40182. * @abstract
  40183. * @param {RenderObject} renderObject - The render object to draw.
  40184. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  40185. */
  40186. draw( /*renderObject, info*/ ) { }
  40187. // compute node
  40188. /**
  40189. * Executes a compute command for the given compute node.
  40190. *
  40191. * @abstract
  40192. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  40193. * @param {Node} computeNode - The compute node.
  40194. * @param {Array<BindGroup>} bindings - The bindings.
  40195. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40196. */
  40197. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  40198. // program
  40199. /**
  40200. * Creates a shader program from the given programmable stage.
  40201. *
  40202. * @abstract
  40203. * @param {ProgrammableStage} program - The programmable stage.
  40204. */
  40205. createProgram( /*program*/ ) { }
  40206. /**
  40207. * Destroys the shader program of the given programmable stage.
  40208. *
  40209. * @abstract
  40210. * @param {ProgrammableStage} program - The programmable stage.
  40211. */
  40212. destroyProgram( /*program*/ ) { }
  40213. // bindings
  40214. /**
  40215. * Creates bindings from the given bind group definition.
  40216. *
  40217. * @abstract
  40218. * @param {BindGroup} bindGroup - The bind group.
  40219. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40220. * @param {number} cacheIndex - The cache index.
  40221. * @param {number} version - The version.
  40222. */
  40223. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40224. /**
  40225. * Updates the given bind group definition.
  40226. *
  40227. * @abstract
  40228. * @param {BindGroup} bindGroup - The bind group.
  40229. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40230. * @param {number} cacheIndex - The cache index.
  40231. * @param {number} version - The version.
  40232. */
  40233. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40234. /**
  40235. * Updates a buffer binding.
  40236. *
  40237. * @abstract
  40238. * @param {Buffer} binding - The buffer binding to update.
  40239. */
  40240. updateBinding( /*binding*/ ) { }
  40241. // pipeline
  40242. /**
  40243. * Creates a render pipeline for the given render object.
  40244. *
  40245. * @abstract
  40246. * @param {RenderObject} renderObject - The render object.
  40247. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  40248. */
  40249. createRenderPipeline( /*renderObject, promises*/ ) { }
  40250. /**
  40251. * Creates a compute pipeline for the given compute node.
  40252. *
  40253. * @abstract
  40254. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40255. * @param {Array<BindGroup>} bindings - The bindings.
  40256. */
  40257. createComputePipeline( /*computePipeline, bindings*/ ) { }
  40258. // cache key
  40259. /**
  40260. * Returns `true` if the render pipeline requires an update.
  40261. *
  40262. * @abstract
  40263. * @param {RenderObject} renderObject - The render object.
  40264. * @return {boolean} Whether the render pipeline requires an update or not.
  40265. */
  40266. needsRenderUpdate( /*renderObject*/ ) { }
  40267. /**
  40268. * Returns a cache key that is used to identify render pipelines.
  40269. *
  40270. * @abstract
  40271. * @param {RenderObject} renderObject - The render object.
  40272. * @return {string} The cache key.
  40273. */
  40274. getRenderCacheKey( /*renderObject*/ ) { }
  40275. // node builder
  40276. /**
  40277. * Returns a node builder for the given render object.
  40278. *
  40279. * @abstract
  40280. * @param {RenderObject} renderObject - The render object.
  40281. * @param {Renderer} renderer - The renderer.
  40282. * @return {NodeBuilder} The node builder.
  40283. */
  40284. createNodeBuilder( /*renderObject, renderer*/ ) { }
  40285. // textures
  40286. /**
  40287. * Creates a GPU sampler for the given texture.
  40288. *
  40289. * @abstract
  40290. * @param {Texture} texture - The texture to create the sampler for.
  40291. */
  40292. createSampler( /*texture*/ ) { }
  40293. /**
  40294. * Destroys the GPU sampler for the given texture.
  40295. *
  40296. * @abstract
  40297. * @param {Texture} texture - The texture to destroy the sampler for.
  40298. */
  40299. destroySampler( /*texture*/ ) {}
  40300. /**
  40301. * Creates a default texture for the given texture that can be used
  40302. * as a placeholder until the actual texture is ready for usage.
  40303. *
  40304. * @abstract
  40305. * @param {Texture} texture - The texture to create a default texture for.
  40306. */
  40307. createDefaultTexture( /*texture*/ ) { }
  40308. /**
  40309. * Defines a texture on the GPU for the given texture object.
  40310. *
  40311. * @abstract
  40312. * @param {Texture} texture - The texture.
  40313. * @param {Object} [options={}] - Optional configuration parameter.
  40314. */
  40315. createTexture( /*texture, options={}*/ ) { }
  40316. /**
  40317. * Uploads the updated texture data to the GPU.
  40318. *
  40319. * @abstract
  40320. * @param {Texture} texture - The texture.
  40321. * @param {Object} [options={}] - Optional configuration parameter.
  40322. */
  40323. updateTexture( /*texture, options = {}*/ ) { }
  40324. /**
  40325. * Generates mipmaps for the given texture.
  40326. *
  40327. * @abstract
  40328. * @param {Texture} texture - The texture.
  40329. */
  40330. generateMipmaps( /*texture*/ ) { }
  40331. /**
  40332. * Destroys the GPU data for the given texture object.
  40333. *
  40334. * @abstract
  40335. * @param {Texture} texture - The texture.
  40336. */
  40337. destroyTexture( /*texture*/ ) { }
  40338. /**
  40339. * Returns texture data as a typed array.
  40340. *
  40341. * @abstract
  40342. * @async
  40343. * @param {Texture} texture - The texture to copy.
  40344. * @param {number} x - The x coordinate of the copy origin.
  40345. * @param {number} y - The y coordinate of the copy origin.
  40346. * @param {number} width - The width of the copy.
  40347. * @param {number} height - The height of the copy.
  40348. * @param {number} faceIndex - The face index.
  40349. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40350. */
  40351. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  40352. /**
  40353. * Copies data of the given source texture to the given destination texture.
  40354. *
  40355. * @abstract
  40356. * @param {Texture} srcTexture - The source texture.
  40357. * @param {Texture} dstTexture - The destination texture.
  40358. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  40359. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  40360. * @param {number} [srcLevel=0] - The source mip level to copy from.
  40361. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  40362. */
  40363. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  40364. /**
  40365. * Copies the current bound framebuffer to the given texture.
  40366. *
  40367. * @abstract
  40368. * @param {Texture} texture - The destination texture.
  40369. * @param {RenderContext} renderContext - The render context.
  40370. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40371. */
  40372. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  40373. // attributes
  40374. /**
  40375. * Creates the GPU buffer of a shader attribute.
  40376. *
  40377. * @abstract
  40378. * @param {BufferAttribute} attribute - The buffer attribute.
  40379. */
  40380. createAttribute( /*attribute*/ ) { }
  40381. /**
  40382. * Creates the GPU buffer of an indexed shader attribute.
  40383. *
  40384. * @abstract
  40385. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  40386. */
  40387. createIndexAttribute( /*attribute*/ ) { }
  40388. /**
  40389. * Creates the GPU buffer of a storage attribute.
  40390. *
  40391. * @abstract
  40392. * @param {BufferAttribute} attribute - The buffer attribute.
  40393. */
  40394. createStorageAttribute( /*attribute*/ ) { }
  40395. /**
  40396. * Updates the GPU buffer of a shader attribute.
  40397. *
  40398. * @abstract
  40399. * @param {BufferAttribute} attribute - The buffer attribute to update.
  40400. */
  40401. updateAttribute( /*attribute*/ ) { }
  40402. /**
  40403. * Destroys the GPU buffer of a shader attribute.
  40404. *
  40405. * @abstract
  40406. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  40407. */
  40408. destroyAttribute( /*attribute*/ ) { }
  40409. // canvas
  40410. /**
  40411. * Returns the backend's rendering context.
  40412. *
  40413. * @abstract
  40414. * @return {Object} The rendering context.
  40415. */
  40416. getContext() { }
  40417. /**
  40418. * Backends can use this method if they have to run
  40419. * logic when the renderer gets resized.
  40420. *
  40421. * @abstract
  40422. */
  40423. updateSize() { }
  40424. /**
  40425. * Updates the viewport with the values from the given render context.
  40426. *
  40427. * @abstract
  40428. * @param {RenderContext} renderContext - The render context.
  40429. */
  40430. updateViewport( /*renderContext*/ ) {}
  40431. // utils
  40432. /**
  40433. * Returns `true` if the given 3D object is fully occluded by other
  40434. * 3D objects in the scene. Backends must implement this method by using
  40435. * a Occlusion Query API.
  40436. *
  40437. * @abstract
  40438. * @param {RenderContext} renderContext - The render context.
  40439. * @param {Object3D} object - The 3D object to test.
  40440. * @return {boolean} Whether the 3D object is fully occluded or not.
  40441. */
  40442. isOccluded( /*renderContext, object*/ ) {}
  40443. /**
  40444. * Resolves the time stamp for the given render context and type.
  40445. *
  40446. * @async
  40447. * @abstract
  40448. * @param {string} [type='render'] - The type of the time stamp.
  40449. * @return {Promise<number>} A Promise that resolves with the time stamp.
  40450. */
  40451. async resolveTimestampsAsync( type = 'render' ) {
  40452. if ( ! this.trackTimestamp ) {
  40453. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  40454. return;
  40455. }
  40456. const queryPool = this.timestampQueryPool[ type ];
  40457. if ( ! queryPool ) {
  40458. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  40459. return;
  40460. }
  40461. const duration = await queryPool.resolveQueriesAsync();
  40462. this.renderer.info[ type ].timestamp = duration;
  40463. return duration;
  40464. }
  40465. /**
  40466. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40467. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40468. *
  40469. * @async
  40470. * @abstract
  40471. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40472. */
  40473. async waitForGPU() {}
  40474. /**
  40475. * This method performs a readback operation by moving buffer data from
  40476. * a storage buffer attribute from the GPU to the CPU.
  40477. *
  40478. * @async
  40479. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40480. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40481. */
  40482. async getArrayBufferAsync( /* attribute */ ) {}
  40483. /**
  40484. * Checks if the given feature is supported by the backend.
  40485. *
  40486. * @async
  40487. * @abstract
  40488. * @param {string} name - The feature's name.
  40489. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  40490. */
  40491. async hasFeatureAsync( /*name*/ ) { }
  40492. /**
  40493. * Checks if the given feature is supported by the backend.
  40494. *
  40495. * @abstract
  40496. * @param {string} name - The feature's name.
  40497. * @return {boolean} Whether the feature is supported or not.
  40498. */
  40499. hasFeature( /*name*/ ) {}
  40500. /**
  40501. * Returns the maximum anisotropy texture filtering value.
  40502. *
  40503. * @abstract
  40504. * @return {number} The maximum anisotropy texture filtering value.
  40505. */
  40506. getMaxAnisotropy() {}
  40507. /**
  40508. * Returns the drawing buffer size.
  40509. *
  40510. * @return {Vector2} The drawing buffer size.
  40511. */
  40512. getDrawingBufferSize() {
  40513. _vector2 = _vector2 || new Vector2();
  40514. return this.renderer.getDrawingBufferSize( _vector2 );
  40515. }
  40516. /**
  40517. * Defines the scissor test.
  40518. *
  40519. * @abstract
  40520. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40521. */
  40522. setScissorTest( /*boolean*/ ) { }
  40523. /**
  40524. * Returns the clear color and alpha into a single
  40525. * color object.
  40526. *
  40527. * @return {Color4} The clear color.
  40528. */
  40529. getClearColor() {
  40530. const renderer = this.renderer;
  40531. _color4 = _color4 || new Color4();
  40532. renderer.getClearColor( _color4 );
  40533. _color4.getRGB( _color4 );
  40534. return _color4;
  40535. }
  40536. /**
  40537. * Returns the DOM element. If no DOM element exists, the backend
  40538. * creates a new one.
  40539. *
  40540. * @return {HTMLCanvasElement} The DOM element.
  40541. */
  40542. getDomElement() {
  40543. let domElement = this.domElement;
  40544. if ( domElement === null ) {
  40545. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  40546. // OffscreenCanvas does not have setAttribute, see #22811
  40547. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  40548. this.domElement = domElement;
  40549. }
  40550. return domElement;
  40551. }
  40552. /**
  40553. * Sets a dictionary for the given object into the
  40554. * internal data structure.
  40555. *
  40556. * @param {Object} object - The object.
  40557. * @param {Object} value - The dictionary to set.
  40558. */
  40559. set( object, value ) {
  40560. this.data.set( object, value );
  40561. }
  40562. /**
  40563. * Returns the dictionary for the given object.
  40564. *
  40565. * @param {Object} object - The object.
  40566. * @return {Object} The object's dictionary.
  40567. */
  40568. get( object ) {
  40569. let map = this.data.get( object );
  40570. if ( map === undefined ) {
  40571. map = {};
  40572. this.data.set( object, map );
  40573. }
  40574. return map;
  40575. }
  40576. /**
  40577. * Checks if the given object has a dictionary
  40578. * with data defined.
  40579. *
  40580. * @param {Object} object - The object.
  40581. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  40582. */
  40583. has( object ) {
  40584. return this.data.has( object );
  40585. }
  40586. /**
  40587. * Deletes an object from the internal data structure.
  40588. *
  40589. * @param {Object} object - The object to delete.
  40590. */
  40591. delete( object ) {
  40592. this.data.delete( object );
  40593. }
  40594. /**
  40595. * Frees internal resources.
  40596. *
  40597. * @abstract
  40598. */
  40599. dispose() { }
  40600. }
  40601. let _id$1 = 0;
  40602. /**
  40603. * This module is internally used in context of compute shaders.
  40604. * This type of shader is not natively supported in WebGL 2 and
  40605. * thus implemented via Transform Feedback. `DualAttributeData`
  40606. * manages the related data.
  40607. *
  40608. * @private
  40609. */
  40610. class DualAttributeData {
  40611. constructor( attributeData, dualBuffer ) {
  40612. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  40613. this.type = attributeData.type;
  40614. this.bufferType = attributeData.bufferType;
  40615. this.pbo = attributeData.pbo;
  40616. this.byteLength = attributeData.byteLength;
  40617. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  40618. this.version = attributeData.version;
  40619. this.isInteger = attributeData.isInteger;
  40620. this.activeBufferIndex = 0;
  40621. this.baseId = attributeData.id;
  40622. }
  40623. get id() {
  40624. return `${ this.baseId }|${ this.activeBufferIndex }`;
  40625. }
  40626. get bufferGPU() {
  40627. return this.buffers[ this.activeBufferIndex ];
  40628. }
  40629. get transformBuffer() {
  40630. return this.buffers[ this.activeBufferIndex ^ 1 ];
  40631. }
  40632. switchBuffers() {
  40633. this.activeBufferIndex ^= 1;
  40634. }
  40635. }
  40636. /**
  40637. * A WebGL 2 backend utility module for managing shader attributes.
  40638. *
  40639. * @private
  40640. */
  40641. class WebGLAttributeUtils {
  40642. /**
  40643. * Constructs a new utility object.
  40644. *
  40645. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40646. */
  40647. constructor( backend ) {
  40648. /**
  40649. * A reference to the WebGL 2 backend.
  40650. *
  40651. * @type {WebGLBackend}
  40652. */
  40653. this.backend = backend;
  40654. }
  40655. /**
  40656. * Creates the GPU buffer for the given buffer attribute.
  40657. *
  40658. * @param {BufferAttribute} attribute - The buffer attribute.
  40659. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  40660. */
  40661. createAttribute( attribute, bufferType ) {
  40662. const backend = this.backend;
  40663. const { gl } = backend;
  40664. const array = attribute.array;
  40665. const usage = attribute.usage || gl.STATIC_DRAW;
  40666. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40667. const bufferData = backend.get( bufferAttribute );
  40668. let bufferGPU = bufferData.bufferGPU;
  40669. if ( bufferGPU === undefined ) {
  40670. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  40671. bufferData.bufferGPU = bufferGPU;
  40672. bufferData.bufferType = bufferType;
  40673. bufferData.version = bufferAttribute.version;
  40674. }
  40675. //attribute.onUploadCallback();
  40676. let type;
  40677. if ( array instanceof Float32Array ) {
  40678. type = gl.FLOAT;
  40679. } else if ( array instanceof Uint16Array ) {
  40680. if ( attribute.isFloat16BufferAttribute ) {
  40681. type = gl.HALF_FLOAT;
  40682. } else {
  40683. type = gl.UNSIGNED_SHORT;
  40684. }
  40685. } else if ( array instanceof Int16Array ) {
  40686. type = gl.SHORT;
  40687. } else if ( array instanceof Uint32Array ) {
  40688. type = gl.UNSIGNED_INT;
  40689. } else if ( array instanceof Int32Array ) {
  40690. type = gl.INT;
  40691. } else if ( array instanceof Int8Array ) {
  40692. type = gl.BYTE;
  40693. } else if ( array instanceof Uint8Array ) {
  40694. type = gl.UNSIGNED_BYTE;
  40695. } else if ( array instanceof Uint8ClampedArray ) {
  40696. type = gl.UNSIGNED_BYTE;
  40697. } else {
  40698. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  40699. }
  40700. let attributeData = {
  40701. bufferGPU,
  40702. bufferType,
  40703. type,
  40704. byteLength: array.byteLength,
  40705. bytesPerElement: array.BYTES_PER_ELEMENT,
  40706. version: attribute.version,
  40707. pbo: attribute.pbo,
  40708. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  40709. id: _id$1 ++
  40710. };
  40711. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  40712. // create buffer for transform feedback use
  40713. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  40714. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  40715. }
  40716. backend.set( attribute, attributeData );
  40717. }
  40718. /**
  40719. * Updates the GPU buffer of the given buffer attribute.
  40720. *
  40721. * @param {BufferAttribute} attribute - The buffer attribute.
  40722. */
  40723. updateAttribute( attribute ) {
  40724. const backend = this.backend;
  40725. const { gl } = backend;
  40726. const array = attribute.array;
  40727. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40728. const bufferData = backend.get( bufferAttribute );
  40729. const bufferType = bufferData.bufferType;
  40730. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  40731. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  40732. if ( updateRanges.length === 0 ) {
  40733. // Not using update ranges
  40734. gl.bufferSubData( bufferType, 0, array );
  40735. } else {
  40736. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  40737. const range = updateRanges[ i ];
  40738. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  40739. array, range.start, range.count );
  40740. }
  40741. bufferAttribute.clearUpdateRanges();
  40742. }
  40743. gl.bindBuffer( bufferType, null );
  40744. bufferData.version = bufferAttribute.version;
  40745. }
  40746. /**
  40747. * Destroys the GPU buffer of the given buffer attribute.
  40748. *
  40749. * @param {BufferAttribute} attribute - The buffer attribute.
  40750. */
  40751. destroyAttribute( attribute ) {
  40752. const backend = this.backend;
  40753. const { gl } = backend;
  40754. if ( attribute.isInterleavedBufferAttribute ) {
  40755. backend.delete( attribute.data );
  40756. }
  40757. const attributeData = backend.get( attribute );
  40758. gl.deleteBuffer( attributeData.bufferGPU );
  40759. backend.delete( attribute );
  40760. }
  40761. /**
  40762. * This method performs a readback operation by moving buffer data from
  40763. * a storage buffer attribute from the GPU to the CPU.
  40764. *
  40765. * @async
  40766. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40767. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40768. */
  40769. async getArrayBufferAsync( attribute ) {
  40770. const backend = this.backend;
  40771. const { gl } = backend;
  40772. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40773. const { bufferGPU } = backend.get( bufferAttribute );
  40774. const array = attribute.array;
  40775. const byteLength = array.byteLength;
  40776. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  40777. const writeBuffer = gl.createBuffer();
  40778. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  40779. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  40780. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  40781. await backend.utils._clientWaitAsync();
  40782. const dstBuffer = new attribute.array.constructor( array.length );
  40783. // Ensure the buffer is bound before reading
  40784. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  40785. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  40786. gl.deleteBuffer( writeBuffer );
  40787. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  40788. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  40789. return dstBuffer.buffer;
  40790. }
  40791. /**
  40792. * Creates a WebGL buffer with the given data.
  40793. *
  40794. * @private
  40795. * @param {WebGL2RenderingContext} gl - The rendering context.
  40796. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  40797. * @param {TypedArray} array - The array of the buffer attribute.
  40798. * @param {GLenum} usage - The usage.
  40799. * @return {WebGLBuffer} The WebGL buffer.
  40800. */
  40801. _createBuffer( gl, bufferType, array, usage ) {
  40802. const bufferGPU = gl.createBuffer();
  40803. gl.bindBuffer( bufferType, bufferGPU );
  40804. gl.bufferData( bufferType, array, usage );
  40805. gl.bindBuffer( bufferType, null );
  40806. return bufferGPU;
  40807. }
  40808. }
  40809. let equationToGL, factorToGL;
  40810. /**
  40811. * A WebGL 2 backend utility module for managing the WebGL state.
  40812. *
  40813. * The major goal of this module is to reduce the number of state changes
  40814. * by caching the WEbGL state with a series of variables. In this way, the
  40815. * renderer only executes state change commands when necessary which
  40816. * improves the overall performance.
  40817. *
  40818. * @private
  40819. */
  40820. class WebGLState {
  40821. /**
  40822. * Constructs a new utility object.
  40823. *
  40824. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40825. */
  40826. constructor( backend ) {
  40827. /**
  40828. * A reference to the WebGL 2 backend.
  40829. *
  40830. * @type {WebGLBackend}
  40831. */
  40832. this.backend = backend;
  40833. /**
  40834. * A reference to the rendering context.
  40835. *
  40836. * @type {WebGL2RenderingContext}
  40837. */
  40838. this.gl = this.backend.gl;
  40839. // Below properties are intended to cache
  40840. // the WebGL state and are not explicitly
  40841. // documented for convenience reasons.
  40842. this.enabled = {};
  40843. this.currentFlipSided = null;
  40844. this.currentCullFace = null;
  40845. this.currentProgram = null;
  40846. this.currentBlendingEnabled = false;
  40847. this.currentBlending = null;
  40848. this.currentBlendSrc = null;
  40849. this.currentBlendDst = null;
  40850. this.currentBlendSrcAlpha = null;
  40851. this.currentBlendDstAlpha = null;
  40852. this.currentPremultipledAlpha = null;
  40853. this.currentPolygonOffsetFactor = null;
  40854. this.currentPolygonOffsetUnits = null;
  40855. this.currentColorMask = null;
  40856. this.currentDepthFunc = null;
  40857. this.currentDepthMask = null;
  40858. this.currentStencilFunc = null;
  40859. this.currentStencilRef = null;
  40860. this.currentStencilFuncMask = null;
  40861. this.currentStencilFail = null;
  40862. this.currentStencilZFail = null;
  40863. this.currentStencilZPass = null;
  40864. this.currentStencilMask = null;
  40865. this.currentLineWidth = null;
  40866. this.currentClippingPlanes = 0;
  40867. this.currentVAO = null;
  40868. this.currentIndex = null;
  40869. this.currentBoundFramebuffers = {};
  40870. this.currentDrawbuffers = new WeakMap();
  40871. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  40872. this.currentTextureSlot = null;
  40873. this.currentBoundTextures = {};
  40874. this.currentBoundBufferBases = {};
  40875. this._init();
  40876. }
  40877. /**
  40878. * Inits the state of the utility.
  40879. *
  40880. * @private
  40881. */
  40882. _init() {
  40883. const gl = this.gl;
  40884. // Store only WebGL constants here.
  40885. equationToGL = {
  40886. [ AddEquation ]: gl.FUNC_ADD,
  40887. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  40888. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  40889. };
  40890. factorToGL = {
  40891. [ ZeroFactor ]: gl.ZERO,
  40892. [ OneFactor ]: gl.ONE,
  40893. [ SrcColorFactor ]: gl.SRC_COLOR,
  40894. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  40895. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  40896. [ DstColorFactor ]: gl.DST_COLOR,
  40897. [ DstAlphaFactor ]: gl.DST_ALPHA,
  40898. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  40899. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  40900. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  40901. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  40902. };
  40903. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  40904. const viewportParam = gl.getParameter( gl.VIEWPORT );
  40905. this.currentScissor = new Vector4().fromArray( scissorParam );
  40906. this.currentViewport = new Vector4().fromArray( viewportParam );
  40907. this._tempVec4 = new Vector4();
  40908. }
  40909. /**
  40910. * Enables the given WebGL capability.
  40911. *
  40912. * This method caches the capability state so
  40913. * `gl.enable()` is only called when necessary.
  40914. *
  40915. * @param {GLenum} id - The capability to enable.
  40916. */
  40917. enable( id ) {
  40918. const { enabled } = this;
  40919. if ( enabled[ id ] !== true ) {
  40920. this.gl.enable( id );
  40921. enabled[ id ] = true;
  40922. }
  40923. }
  40924. /**
  40925. * Disables the given WebGL capability.
  40926. *
  40927. * This method caches the capability state so
  40928. * `gl.disable()` is only called when necessary.
  40929. *
  40930. * @param {GLenum} id - The capability to enable.
  40931. */
  40932. disable( id ) {
  40933. const { enabled } = this;
  40934. if ( enabled[ id ] !== false ) {
  40935. this.gl.disable( id );
  40936. enabled[ id ] = false;
  40937. }
  40938. }
  40939. /**
  40940. * Specifies whether polygons are front- or back-facing
  40941. * by setting the winding orientation.
  40942. *
  40943. * This method caches the state so `gl.frontFace()` is only
  40944. * called when necessary.
  40945. *
  40946. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  40947. */
  40948. setFlipSided( flipSided ) {
  40949. if ( this.currentFlipSided !== flipSided ) {
  40950. const { gl } = this;
  40951. if ( flipSided ) {
  40952. gl.frontFace( gl.CW );
  40953. } else {
  40954. gl.frontFace( gl.CCW );
  40955. }
  40956. this.currentFlipSided = flipSided;
  40957. }
  40958. }
  40959. /**
  40960. * Specifies whether or not front- and/or back-facing
  40961. * polygons can be culled.
  40962. *
  40963. * This method caches the state so `gl.cullFace()` is only
  40964. * called when necessary.
  40965. *
  40966. * @param {number} cullFace - Defines which polygons are candidates for culling.
  40967. */
  40968. setCullFace( cullFace ) {
  40969. const { gl } = this;
  40970. if ( cullFace !== CullFaceNone ) {
  40971. this.enable( gl.CULL_FACE );
  40972. if ( cullFace !== this.currentCullFace ) {
  40973. if ( cullFace === CullFaceBack ) {
  40974. gl.cullFace( gl.BACK );
  40975. } else if ( cullFace === CullFaceFront ) {
  40976. gl.cullFace( gl.FRONT );
  40977. } else {
  40978. gl.cullFace( gl.FRONT_AND_BACK );
  40979. }
  40980. }
  40981. } else {
  40982. this.disable( gl.CULL_FACE );
  40983. }
  40984. this.currentCullFace = cullFace;
  40985. }
  40986. /**
  40987. * Specifies the width of line primitives.
  40988. *
  40989. * This method caches the state so `gl.lineWidth()` is only
  40990. * called when necessary.
  40991. *
  40992. * @param {number} width - The line width.
  40993. */
  40994. setLineWidth( width ) {
  40995. const { currentLineWidth, gl } = this;
  40996. if ( width !== currentLineWidth ) {
  40997. gl.lineWidth( width );
  40998. this.currentLineWidth = width;
  40999. }
  41000. }
  41001. /**
  41002. * Defines the blending.
  41003. *
  41004. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  41005. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  41006. *
  41007. * @param {number} blending - The blending type.
  41008. * @param {number} blendEquation - The blending equation.
  41009. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  41010. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  41011. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  41012. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  41013. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  41014. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  41015. */
  41016. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  41017. const { gl } = this;
  41018. if ( blending === NoBlending ) {
  41019. if ( this.currentBlendingEnabled === true ) {
  41020. this.disable( gl.BLEND );
  41021. this.currentBlendingEnabled = false;
  41022. }
  41023. return;
  41024. }
  41025. if ( this.currentBlendingEnabled === false ) {
  41026. this.enable( gl.BLEND );
  41027. this.currentBlendingEnabled = true;
  41028. }
  41029. if ( blending !== CustomBlending ) {
  41030. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  41031. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  41032. gl.blendEquation( gl.FUNC_ADD );
  41033. this.currentBlendEquation = AddEquation;
  41034. this.currentBlendEquationAlpha = AddEquation;
  41035. }
  41036. if ( premultipliedAlpha ) {
  41037. switch ( blending ) {
  41038. case NormalBlending:
  41039. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41040. break;
  41041. case AdditiveBlending:
  41042. gl.blendFunc( gl.ONE, gl.ONE );
  41043. break;
  41044. case SubtractiveBlending:
  41045. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41046. break;
  41047. case MultiplyBlending:
  41048. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  41049. break;
  41050. default:
  41051. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41052. break;
  41053. }
  41054. } else {
  41055. switch ( blending ) {
  41056. case NormalBlending:
  41057. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41058. break;
  41059. case AdditiveBlending:
  41060. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  41061. break;
  41062. case SubtractiveBlending:
  41063. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41064. break;
  41065. case MultiplyBlending:
  41066. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  41067. break;
  41068. default:
  41069. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41070. break;
  41071. }
  41072. }
  41073. this.currentBlendSrc = null;
  41074. this.currentBlendDst = null;
  41075. this.currentBlendSrcAlpha = null;
  41076. this.currentBlendDstAlpha = null;
  41077. this.currentBlending = blending;
  41078. this.currentPremultipledAlpha = premultipliedAlpha;
  41079. }
  41080. return;
  41081. }
  41082. // custom blending
  41083. blendEquationAlpha = blendEquationAlpha || blendEquation;
  41084. blendSrcAlpha = blendSrcAlpha || blendSrc;
  41085. blendDstAlpha = blendDstAlpha || blendDst;
  41086. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  41087. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  41088. this.currentBlendEquation = blendEquation;
  41089. this.currentBlendEquationAlpha = blendEquationAlpha;
  41090. }
  41091. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  41092. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  41093. this.currentBlendSrc = blendSrc;
  41094. this.currentBlendDst = blendDst;
  41095. this.currentBlendSrcAlpha = blendSrcAlpha;
  41096. this.currentBlendDstAlpha = blendDstAlpha;
  41097. }
  41098. this.currentBlending = blending;
  41099. this.currentPremultipledAlpha = false;
  41100. }
  41101. /**
  41102. * Specifies whether colors can be written when rendering
  41103. * into a framebuffer or not.
  41104. *
  41105. * This method caches the state so `gl.colorMask()` is only
  41106. * called when necessary.
  41107. *
  41108. * @param {boolean} colorMask - The color mask.
  41109. */
  41110. setColorMask( colorMask ) {
  41111. if ( this.currentColorMask !== colorMask ) {
  41112. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  41113. this.currentColorMask = colorMask;
  41114. }
  41115. }
  41116. /**
  41117. * Specifies whether the depth test is enabled or not.
  41118. *
  41119. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  41120. */
  41121. setDepthTest( depthTest ) {
  41122. const { gl } = this;
  41123. if ( depthTest ) {
  41124. this.enable( gl.DEPTH_TEST );
  41125. } else {
  41126. this.disable( gl.DEPTH_TEST );
  41127. }
  41128. }
  41129. /**
  41130. * Specifies whether depth values can be written when rendering
  41131. * into a framebuffer or not.
  41132. *
  41133. * This method caches the state so `gl.depthMask()` is only
  41134. * called when necessary.
  41135. *
  41136. * @param {boolean} depthMask - The depth mask.
  41137. */
  41138. setDepthMask( depthMask ) {
  41139. if ( this.currentDepthMask !== depthMask ) {
  41140. this.gl.depthMask( depthMask );
  41141. this.currentDepthMask = depthMask;
  41142. }
  41143. }
  41144. /**
  41145. * Specifies the depth compare function.
  41146. *
  41147. * This method caches the state so `gl.depthFunc()` is only
  41148. * called when necessary.
  41149. *
  41150. * @param {number} depthFunc - The depth compare function.
  41151. */
  41152. setDepthFunc( depthFunc ) {
  41153. if ( this.currentDepthFunc !== depthFunc ) {
  41154. const { gl } = this;
  41155. switch ( depthFunc ) {
  41156. case NeverDepth:
  41157. gl.depthFunc( gl.NEVER );
  41158. break;
  41159. case AlwaysDepth:
  41160. gl.depthFunc( gl.ALWAYS );
  41161. break;
  41162. case LessDepth:
  41163. gl.depthFunc( gl.LESS );
  41164. break;
  41165. case LessEqualDepth:
  41166. gl.depthFunc( gl.LEQUAL );
  41167. break;
  41168. case EqualDepth:
  41169. gl.depthFunc( gl.EQUAL );
  41170. break;
  41171. case GreaterEqualDepth:
  41172. gl.depthFunc( gl.GEQUAL );
  41173. break;
  41174. case GreaterDepth:
  41175. gl.depthFunc( gl.GREATER );
  41176. break;
  41177. case NotEqualDepth:
  41178. gl.depthFunc( gl.NOTEQUAL );
  41179. break;
  41180. default:
  41181. gl.depthFunc( gl.LEQUAL );
  41182. }
  41183. this.currentDepthFunc = depthFunc;
  41184. }
  41185. }
  41186. /**
  41187. * Specifies the scissor box.
  41188. *
  41189. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41190. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41191. * @param {number} width - The width of the viewport.
  41192. * @param {number} height - The height of the viewport.
  41193. *
  41194. */
  41195. scissor( x, y, width, height ) {
  41196. const scissor = this._tempVec4.set( x, y, width, height );
  41197. if ( this.currentScissor.equals( scissor ) === false ) {
  41198. const { gl } = this;
  41199. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  41200. this.currentScissor.copy( scissor );
  41201. }
  41202. }
  41203. /**
  41204. * Specifies the viewport.
  41205. *
  41206. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41207. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41208. * @param {number} width - The width of the viewport.
  41209. * @param {number} height - The height of the viewport.
  41210. *
  41211. */
  41212. viewport( x, y, width, height ) {
  41213. const viewport = this._tempVec4.set( x, y, width, height );
  41214. if ( this.currentViewport.equals( viewport ) === false ) {
  41215. const { gl } = this;
  41216. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  41217. this.currentViewport.copy( viewport );
  41218. }
  41219. }
  41220. /**
  41221. * Defines the scissor test.
  41222. *
  41223. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41224. */
  41225. setScissorTest( boolean ) {
  41226. const gl = this.gl;
  41227. if ( boolean ) {
  41228. gl.enable( gl.SCISSOR_TEST );
  41229. } else {
  41230. gl.disable( gl.SCISSOR_TEST );
  41231. }
  41232. }
  41233. /**
  41234. * Specifies whether the stencil test is enabled or not.
  41235. *
  41236. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  41237. */
  41238. setStencilTest( stencilTest ) {
  41239. const { gl } = this;
  41240. if ( stencilTest ) {
  41241. this.enable( gl.STENCIL_TEST );
  41242. } else {
  41243. this.disable( gl.STENCIL_TEST );
  41244. }
  41245. }
  41246. /**
  41247. * Specifies whether stencil values can be written when rendering
  41248. * into a framebuffer or not.
  41249. *
  41250. * This method caches the state so `gl.stencilMask()` is only
  41251. * called when necessary.
  41252. *
  41253. * @param {boolean} stencilMask - The stencil mask.
  41254. */
  41255. setStencilMask( stencilMask ) {
  41256. if ( this.currentStencilMask !== stencilMask ) {
  41257. this.gl.stencilMask( stencilMask );
  41258. this.currentStencilMask = stencilMask;
  41259. }
  41260. }
  41261. /**
  41262. * Specifies whether the stencil test functions.
  41263. *
  41264. * This method caches the state so `gl.stencilFunc()` is only
  41265. * called when necessary.
  41266. *
  41267. * @param {number} stencilFunc - The stencil compare function.
  41268. * @param {number} stencilRef - The reference value for the stencil test.
  41269. * @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.
  41270. */
  41271. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  41272. if ( this.currentStencilFunc !== stencilFunc ||
  41273. this.currentStencilRef !== stencilRef ||
  41274. this.currentStencilFuncMask !== stencilMask ) {
  41275. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  41276. this.currentStencilFunc = stencilFunc;
  41277. this.currentStencilRef = stencilRef;
  41278. this.currentStencilFuncMask = stencilMask;
  41279. }
  41280. }
  41281. /**
  41282. * Specifies whether the stencil test operation.
  41283. *
  41284. * This method caches the state so `gl.stencilOp()` is only
  41285. * called when necessary.
  41286. *
  41287. * @param {number} stencilFail - The function to use when the stencil test fails.
  41288. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  41289. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  41290. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  41291. */
  41292. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  41293. if ( this.currentStencilFail !== stencilFail ||
  41294. this.currentStencilZFail !== stencilZFail ||
  41295. this.currentStencilZPass !== stencilZPass ) {
  41296. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  41297. this.currentStencilFail = stencilFail;
  41298. this.currentStencilZFail = stencilZFail;
  41299. this.currentStencilZPass = stencilZPass;
  41300. }
  41301. }
  41302. /**
  41303. * Configures the WebGL state for the given material.
  41304. *
  41305. * @param {Material} material - The material to configure the state for.
  41306. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  41307. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  41308. */
  41309. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  41310. const { gl } = this;
  41311. material.side === DoubleSide
  41312. ? this.disable( gl.CULL_FACE )
  41313. : this.enable( gl.CULL_FACE );
  41314. let flipSided = ( material.side === BackSide );
  41315. if ( frontFaceCW ) flipSided = ! flipSided;
  41316. this.setFlipSided( flipSided );
  41317. ( material.blending === NormalBlending && material.transparent === false )
  41318. ? this.setBlending( NoBlending )
  41319. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  41320. this.setDepthFunc( material.depthFunc );
  41321. this.setDepthTest( material.depthTest );
  41322. this.setDepthMask( material.depthWrite );
  41323. this.setColorMask( material.colorWrite );
  41324. const stencilWrite = material.stencilWrite;
  41325. this.setStencilTest( stencilWrite );
  41326. if ( stencilWrite ) {
  41327. this.setStencilMask( material.stencilWriteMask );
  41328. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  41329. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  41330. }
  41331. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  41332. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  41333. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  41334. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  41335. if ( hardwareClippingPlanes > 0 ) {
  41336. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  41337. const CLIP_DISTANCE0_WEBGL = 0x3000;
  41338. for ( let i = 0; i < 8; i ++ ) {
  41339. if ( i < hardwareClippingPlanes ) {
  41340. this.enable( CLIP_DISTANCE0_WEBGL + i );
  41341. } else {
  41342. this.disable( CLIP_DISTANCE0_WEBGL + i );
  41343. }
  41344. }
  41345. }
  41346. }
  41347. }
  41348. /**
  41349. * Specifies the polygon offset.
  41350. *
  41351. * This method caches the state so `gl.polygonOffset()` is only
  41352. * called when necessary.
  41353. *
  41354. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  41355. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  41356. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  41357. */
  41358. setPolygonOffset( polygonOffset, factor, units ) {
  41359. const { gl } = this;
  41360. if ( polygonOffset ) {
  41361. this.enable( gl.POLYGON_OFFSET_FILL );
  41362. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  41363. gl.polygonOffset( factor, units );
  41364. this.currentPolygonOffsetFactor = factor;
  41365. this.currentPolygonOffsetUnits = units;
  41366. }
  41367. } else {
  41368. this.disable( gl.POLYGON_OFFSET_FILL );
  41369. }
  41370. }
  41371. /**
  41372. * Defines the usage of the given WebGL program.
  41373. *
  41374. * This method caches the state so `gl.useProgram()` is only
  41375. * called when necessary.
  41376. *
  41377. * @param {WebGLProgram} program - The WebGL program to use.
  41378. * @return {boolean} Whether a program change has been executed or not.
  41379. */
  41380. useProgram( program ) {
  41381. if ( this.currentProgram !== program ) {
  41382. this.gl.useProgram( program );
  41383. this.currentProgram = program;
  41384. return true;
  41385. }
  41386. return false;
  41387. }
  41388. /**
  41389. * Sets the vertex state by binding the given VAO and element buffer.
  41390. *
  41391. * @param {WebGLVertexArrayObject} vao - The VAO.
  41392. * @param {WebGLBuffer} indexBuffer - The index buffer.
  41393. * @return {boolean} Whether a vertex state has been changed or not.
  41394. */
  41395. setVertexState( vao, indexBuffer = null ) {
  41396. const gl = this.gl;
  41397. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  41398. gl.bindVertexArray( vao );
  41399. if ( indexBuffer !== null ) {
  41400. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  41401. }
  41402. this.currentVAO = vao;
  41403. this.currentIndex = indexBuffer;
  41404. return true;
  41405. }
  41406. return false;
  41407. }
  41408. /**
  41409. * Resets the vertex array state by resetting the VAO and element buffer.
  41410. */
  41411. resetVertexState() {
  41412. const gl = this.gl;
  41413. gl.bindVertexArray( null );
  41414. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  41415. this.currentVAO = null;
  41416. this.currentIndex = null;
  41417. }
  41418. // framebuffer
  41419. /**
  41420. * Binds the given framebuffer.
  41421. *
  41422. * This method caches the state so `gl.bindFramebuffer()` is only
  41423. * called when necessary.
  41424. *
  41425. * @param {number} target - The binding point (target).
  41426. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  41427. * @return {boolean} Whether a bind has been executed or not.
  41428. */
  41429. bindFramebuffer( target, framebuffer ) {
  41430. const { gl, currentBoundFramebuffers } = this;
  41431. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  41432. gl.bindFramebuffer( target, framebuffer );
  41433. currentBoundFramebuffers[ target ] = framebuffer;
  41434. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  41435. if ( target === gl.DRAW_FRAMEBUFFER ) {
  41436. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  41437. }
  41438. if ( target === gl.FRAMEBUFFER ) {
  41439. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  41440. }
  41441. return true;
  41442. }
  41443. return false;
  41444. }
  41445. /**
  41446. * Defines draw buffers to which fragment colors are written into.
  41447. * Configures the MRT setup of custom framebuffers.
  41448. *
  41449. * This method caches the state so `gl.drawBuffers()` is only
  41450. * called when necessary.
  41451. *
  41452. * @param {RenderContext} renderContext - The render context.
  41453. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  41454. */
  41455. drawBuffers( renderContext, framebuffer ) {
  41456. const { gl } = this;
  41457. let drawBuffers = [];
  41458. let needsUpdate = false;
  41459. if ( renderContext.textures !== null ) {
  41460. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  41461. if ( drawBuffers === undefined ) {
  41462. drawBuffers = [];
  41463. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  41464. }
  41465. const textures = renderContext.textures;
  41466. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  41467. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  41468. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  41469. }
  41470. drawBuffers.length = textures.length;
  41471. needsUpdate = true;
  41472. }
  41473. } else {
  41474. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  41475. drawBuffers[ 0 ] = gl.BACK;
  41476. needsUpdate = true;
  41477. }
  41478. }
  41479. if ( needsUpdate ) {
  41480. gl.drawBuffers( drawBuffers );
  41481. }
  41482. }
  41483. // texture
  41484. /**
  41485. * Makes the given texture unit active.
  41486. *
  41487. * This method caches the state so `gl.activeTexture()` is only
  41488. * called when necessary.
  41489. *
  41490. * @param {number} webglSlot - The texture unit to make active.
  41491. */
  41492. activeTexture( webglSlot ) {
  41493. const { gl, currentTextureSlot, maxTextures } = this;
  41494. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41495. if ( currentTextureSlot !== webglSlot ) {
  41496. gl.activeTexture( webglSlot );
  41497. this.currentTextureSlot = webglSlot;
  41498. }
  41499. }
  41500. /**
  41501. * Binds the given WebGL texture to a target.
  41502. *
  41503. * This method caches the state so `gl.bindTexture()` is only
  41504. * called when necessary.
  41505. *
  41506. * @param {number} webglType - The binding point (target).
  41507. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  41508. * @param {number} webglSlot - The texture.
  41509. */
  41510. bindTexture( webglType, webglTexture, webglSlot ) {
  41511. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  41512. if ( webglSlot === undefined ) {
  41513. if ( currentTextureSlot === null ) {
  41514. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41515. } else {
  41516. webglSlot = currentTextureSlot;
  41517. }
  41518. }
  41519. let boundTexture = currentBoundTextures[ webglSlot ];
  41520. if ( boundTexture === undefined ) {
  41521. boundTexture = { type: undefined, texture: undefined };
  41522. currentBoundTextures[ webglSlot ] = boundTexture;
  41523. }
  41524. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  41525. if ( currentTextureSlot !== webglSlot ) {
  41526. gl.activeTexture( webglSlot );
  41527. this.currentTextureSlot = webglSlot;
  41528. }
  41529. gl.bindTexture( webglType, webglTexture );
  41530. boundTexture.type = webglType;
  41531. boundTexture.texture = webglTexture;
  41532. }
  41533. }
  41534. /**
  41535. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  41536. *
  41537. * This method caches the state so `gl.bindBufferBase()` is only
  41538. * called when necessary.
  41539. *
  41540. * @param {number} target - The target for the bind operation.
  41541. * @param {number} index - The index of the target.
  41542. * @param {WebGLBuffer} buffer - The WebGL buffer.
  41543. * @return {boolean} Whether a bind has been executed or not.
  41544. */
  41545. bindBufferBase( target, index, buffer ) {
  41546. const { gl } = this;
  41547. const key = `${target}-${index}`;
  41548. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  41549. gl.bindBufferBase( target, index, buffer );
  41550. this.currentBoundBufferBases[ key ] = buffer;
  41551. return true;
  41552. }
  41553. return false;
  41554. }
  41555. /**
  41556. * Unbinds the current bound texture.
  41557. *
  41558. * This method caches the state so `gl.bindTexture()` is only
  41559. * called when necessary.
  41560. */
  41561. unbindTexture() {
  41562. const { gl, currentTextureSlot, currentBoundTextures } = this;
  41563. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  41564. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  41565. gl.bindTexture( boundTexture.type, null );
  41566. boundTexture.type = undefined;
  41567. boundTexture.texture = undefined;
  41568. }
  41569. }
  41570. }
  41571. /**
  41572. * A WebGL 2 backend utility module with common helpers.
  41573. *
  41574. * @private
  41575. */
  41576. class WebGLUtils {
  41577. /**
  41578. * Constructs a new utility object.
  41579. *
  41580. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41581. */
  41582. constructor( backend ) {
  41583. /**
  41584. * A reference to the WebGL 2 backend.
  41585. *
  41586. * @type {WebGLBackend}
  41587. */
  41588. this.backend = backend;
  41589. /**
  41590. * A reference to the rendering context.
  41591. *
  41592. * @type {WebGL2RenderingContext}
  41593. */
  41594. this.gl = this.backend.gl;
  41595. /**
  41596. * A reference to a backend module holding extension-related
  41597. * utility functions.
  41598. *
  41599. * @type {WebGLExtensions}
  41600. */
  41601. this.extensions = backend.extensions;
  41602. }
  41603. /**
  41604. * Converts the given three.js constant into a WebGL constant.
  41605. * The method currently supports the conversion of texture formats
  41606. * and types.
  41607. *
  41608. * @param {number} p - The three.js constant.
  41609. * @param {string} [colorSpace=NoColorSpace] - The color space.
  41610. * @return {?number} The corresponding WebGL constant.
  41611. */
  41612. convert( p, colorSpace = NoColorSpace ) {
  41613. const { gl, extensions } = this;
  41614. let extension;
  41615. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  41616. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  41617. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  41618. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  41619. if ( p === ByteType ) return gl.BYTE;
  41620. if ( p === ShortType ) return gl.SHORT;
  41621. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  41622. if ( p === IntType ) return gl.INT;
  41623. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  41624. if ( p === FloatType ) return gl.FLOAT;
  41625. if ( p === HalfFloatType ) {
  41626. return gl.HALF_FLOAT;
  41627. }
  41628. if ( p === AlphaFormat ) return gl.ALPHA;
  41629. if ( p === RGBFormat ) return gl.RGB;
  41630. if ( p === RGBAFormat ) return gl.RGBA;
  41631. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  41632. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  41633. // WebGL2 formats.
  41634. if ( p === RedFormat ) return gl.RED;
  41635. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  41636. if ( p === RGFormat ) return gl.RG;
  41637. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  41638. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  41639. // S3TC
  41640. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  41641. if ( colorSpace === SRGBColorSpace ) {
  41642. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  41643. if ( extension !== null ) {
  41644. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  41645. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  41646. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  41647. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  41648. } else {
  41649. return null;
  41650. }
  41651. } else {
  41652. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  41653. if ( extension !== null ) {
  41654. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  41655. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41656. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41657. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41658. } else {
  41659. return null;
  41660. }
  41661. }
  41662. }
  41663. // PVRTC
  41664. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  41665. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  41666. if ( extension !== null ) {
  41667. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  41668. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  41669. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  41670. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  41671. } else {
  41672. return null;
  41673. }
  41674. }
  41675. // ETC
  41676. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  41677. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  41678. if ( extension !== null ) {
  41679. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  41680. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  41681. } else {
  41682. return null;
  41683. }
  41684. }
  41685. // ASTC
  41686. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  41687. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  41688. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  41689. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  41690. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  41691. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  41692. if ( extension !== null ) {
  41693. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  41694. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  41695. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  41696. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  41697. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  41698. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  41699. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  41700. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  41701. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  41702. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  41703. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  41704. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  41705. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  41706. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  41707. } else {
  41708. return null;
  41709. }
  41710. }
  41711. // BPTC
  41712. if ( p === RGBA_BPTC_Format ) {
  41713. extension = extensions.get( 'EXT_texture_compression_bptc' );
  41714. if ( extension !== null ) {
  41715. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  41716. } else {
  41717. return null;
  41718. }
  41719. }
  41720. // RGTC
  41721. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  41722. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  41723. if ( extension !== null ) {
  41724. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  41725. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  41726. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  41727. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  41728. } else {
  41729. return null;
  41730. }
  41731. }
  41732. //
  41733. if ( p === UnsignedInt248Type ) {
  41734. return gl.UNSIGNED_INT_24_8;
  41735. }
  41736. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  41737. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  41738. }
  41739. /**
  41740. * This method can be used to synchronize the CPU with the GPU by waiting until
  41741. * ongoing GPU commands have been completed.
  41742. *
  41743. * @private
  41744. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  41745. */
  41746. _clientWaitAsync() {
  41747. const { gl } = this;
  41748. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  41749. gl.flush();
  41750. return new Promise( ( resolve, reject ) => {
  41751. function test() {
  41752. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  41753. if ( res === gl.WAIT_FAILED ) {
  41754. gl.deleteSync( sync );
  41755. reject();
  41756. return;
  41757. }
  41758. if ( res === gl.TIMEOUT_EXPIRED ) {
  41759. requestAnimationFrame( test );
  41760. return;
  41761. }
  41762. gl.deleteSync( sync );
  41763. resolve();
  41764. }
  41765. test();
  41766. } );
  41767. }
  41768. }
  41769. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  41770. /**
  41771. * A WebGL 2 backend utility module for managing textures.
  41772. *
  41773. * @private
  41774. */
  41775. class WebGLTextureUtils {
  41776. /**
  41777. * Constructs a new utility object.
  41778. *
  41779. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41780. */
  41781. constructor( backend ) {
  41782. /**
  41783. * A reference to the WebGL 2 backend.
  41784. *
  41785. * @type {WebGLBackend}
  41786. */
  41787. this.backend = backend;
  41788. /**
  41789. * A reference to the rendering context.
  41790. *
  41791. * @type {WebGL2RenderingContext}
  41792. */
  41793. this.gl = backend.gl;
  41794. /**
  41795. * A reference to a backend module holding extension-related
  41796. * utility functions.
  41797. *
  41798. * @type {WebGLExtensions}
  41799. */
  41800. this.extensions = backend.extensions;
  41801. /**
  41802. * A dictionary for managing default textures. The key
  41803. * is the binding point (target), the value the WEbGL texture object.
  41804. *
  41805. * @type {Object<GLenum,WebGLTexture>}
  41806. */
  41807. this.defaultTextures = {};
  41808. if ( initialized === false ) {
  41809. this._init();
  41810. initialized = true;
  41811. }
  41812. }
  41813. /**
  41814. * Inits the state of the utility.
  41815. *
  41816. * @private
  41817. */
  41818. _init() {
  41819. const gl = this.gl;
  41820. // Store only WebGL constants here.
  41821. wrappingToGL = {
  41822. [ RepeatWrapping ]: gl.REPEAT,
  41823. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  41824. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  41825. };
  41826. filterToGL = {
  41827. [ NearestFilter ]: gl.NEAREST,
  41828. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  41829. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  41830. [ LinearFilter ]: gl.LINEAR,
  41831. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  41832. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  41833. };
  41834. compareToGL = {
  41835. [ NeverCompare ]: gl.NEVER,
  41836. [ AlwaysCompare ]: gl.ALWAYS,
  41837. [ LessCompare ]: gl.LESS,
  41838. [ LessEqualCompare ]: gl.LEQUAL,
  41839. [ EqualCompare ]: gl.EQUAL,
  41840. [ GreaterEqualCompare ]: gl.GEQUAL,
  41841. [ GreaterCompare ]: gl.GREATER,
  41842. [ NotEqualCompare ]: gl.NOTEQUAL
  41843. };
  41844. }
  41845. /**
  41846. * Returns the native texture type for the given texture.
  41847. *
  41848. * @param {Texture} texture - The texture.
  41849. * @return {GLenum} The native texture type.
  41850. */
  41851. getGLTextureType( texture ) {
  41852. const { gl } = this;
  41853. let glTextureType;
  41854. if ( texture.isCubeTexture === true ) {
  41855. glTextureType = gl.TEXTURE_CUBE_MAP;
  41856. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  41857. glTextureType = gl.TEXTURE_2D_ARRAY;
  41858. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  41859. glTextureType = gl.TEXTURE_3D;
  41860. } else {
  41861. glTextureType = gl.TEXTURE_2D;
  41862. }
  41863. return glTextureType;
  41864. }
  41865. /**
  41866. * Returns the native texture type for the given texture.
  41867. *
  41868. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  41869. * @param {GLenum} glFormat - The WebGL format.
  41870. * @param {GLenum} glType - The WebGL type.
  41871. * @param {string} colorSpace - The texture's color space.
  41872. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  41873. * @return {GLenum} The internal format.
  41874. */
  41875. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  41876. const { gl, extensions } = this;
  41877. if ( internalFormatName !== null ) {
  41878. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  41879. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  41880. }
  41881. let internalFormat = glFormat;
  41882. if ( glFormat === gl.RED ) {
  41883. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  41884. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  41885. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  41886. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  41887. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  41888. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  41889. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  41890. if ( glType === gl.INT ) internalFormat = gl.R32I;
  41891. }
  41892. if ( glFormat === gl.RED_INTEGER ) {
  41893. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  41894. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  41895. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  41896. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  41897. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  41898. if ( glType === gl.INT ) internalFormat = gl.R32I;
  41899. }
  41900. if ( glFormat === gl.RG ) {
  41901. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  41902. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  41903. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  41904. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  41905. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  41906. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  41907. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  41908. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  41909. }
  41910. if ( glFormat === gl.RG_INTEGER ) {
  41911. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  41912. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  41913. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  41914. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  41915. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  41916. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  41917. }
  41918. if ( glFormat === gl.RGB ) {
  41919. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  41920. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  41921. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  41922. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  41923. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  41924. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  41925. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  41926. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  41927. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  41928. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  41929. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  41930. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  41931. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  41932. }
  41933. if ( glFormat === gl.RGB_INTEGER ) {
  41934. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  41935. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  41936. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  41937. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  41938. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  41939. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  41940. }
  41941. if ( glFormat === gl.RGBA ) {
  41942. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  41943. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  41944. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  41945. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  41946. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  41947. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  41948. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  41949. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  41950. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  41951. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  41952. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  41953. }
  41954. if ( glFormat === gl.RGBA_INTEGER ) {
  41955. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  41956. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  41957. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  41958. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  41959. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  41960. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  41961. }
  41962. if ( glFormat === gl.DEPTH_COMPONENT ) {
  41963. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  41964. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  41965. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  41966. }
  41967. if ( glFormat === gl.DEPTH_STENCIL ) {
  41968. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  41969. }
  41970. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  41971. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  41972. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  41973. extensions.get( 'EXT_color_buffer_float' );
  41974. }
  41975. return internalFormat;
  41976. }
  41977. /**
  41978. * Sets the texture parameters for the given texture.
  41979. *
  41980. * @param {GLenum} textureType - The texture type.
  41981. * @param {Texture} texture - The texture.
  41982. */
  41983. setTextureParameters( textureType, texture ) {
  41984. const { gl, extensions, backend } = this;
  41985. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  41986. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  41987. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  41988. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  41989. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  41990. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  41991. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  41992. // WebGL 2 does not support wrapping for depth 2D array textures
  41993. if ( ! texture.isArrayTexture ) {
  41994. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  41995. }
  41996. }
  41997. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  41998. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  41999. // follow WebGPU backend mapping for texture filtering
  42000. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  42001. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  42002. if ( texture.compareFunction ) {
  42003. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  42004. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  42005. }
  42006. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  42007. if ( texture.magFilter === NearestFilter ) return;
  42008. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  42009. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  42010. if ( texture.anisotropy > 1 ) {
  42011. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  42012. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  42013. }
  42014. }
  42015. }
  42016. /**
  42017. * Creates a default texture for the given texture that can be used
  42018. * as a placeholder until the actual texture is ready for usage.
  42019. *
  42020. * @param {Texture} texture - The texture to create a default texture for.
  42021. */
  42022. createDefaultTexture( texture ) {
  42023. const { gl, backend, defaultTextures } = this;
  42024. const glTextureType = this.getGLTextureType( texture );
  42025. let textureGPU = defaultTextures[ glTextureType ];
  42026. if ( textureGPU === undefined ) {
  42027. textureGPU = gl.createTexture();
  42028. backend.state.bindTexture( glTextureType, textureGPU );
  42029. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  42030. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  42031. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  42032. defaultTextures[ glTextureType ] = textureGPU;
  42033. }
  42034. backend.set( texture, {
  42035. textureGPU,
  42036. glTextureType,
  42037. isDefault: true
  42038. } );
  42039. }
  42040. /**
  42041. * Defines a texture on the GPU for the given texture object.
  42042. *
  42043. * @param {Texture} texture - The texture.
  42044. * @param {Object} [options={}] - Optional configuration parameter.
  42045. * @return {undefined}
  42046. */
  42047. createTexture( texture, options ) {
  42048. const { gl, backend } = this;
  42049. const { levels, width, height, depth } = options;
  42050. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  42051. const glType = backend.utils.convert( texture.type );
  42052. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  42053. const textureGPU = gl.createTexture();
  42054. const glTextureType = this.getGLTextureType( texture );
  42055. backend.state.bindTexture( glTextureType, textureGPU );
  42056. this.setTextureParameters( glTextureType, texture );
  42057. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  42058. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  42059. } else if ( texture.isData3DTexture ) {
  42060. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  42061. } else if ( ! texture.isVideoTexture ) {
  42062. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  42063. }
  42064. backend.set( texture, {
  42065. textureGPU,
  42066. glTextureType,
  42067. glFormat,
  42068. glType,
  42069. glInternalFormat
  42070. } );
  42071. }
  42072. /**
  42073. * Uploads texture buffer data to the GPU memory.
  42074. *
  42075. * @param {WebGLBuffer} buffer - The buffer data.
  42076. * @param {Texture} texture - The texture,
  42077. */
  42078. copyBufferToTexture( buffer, texture ) {
  42079. const { gl, backend } = this;
  42080. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  42081. const { width, height } = texture.source.data;
  42082. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  42083. backend.state.bindTexture( glTextureType, textureGPU );
  42084. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  42085. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  42086. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  42087. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  42088. backend.state.unbindTexture();
  42089. // debug
  42090. // const framebuffer = gl.createFramebuffer();
  42091. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  42092. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  42093. // const readout = new Float32Array( width * height * 4 );
  42094. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  42095. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  42096. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  42097. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  42098. // console.log( readout );
  42099. }
  42100. /**
  42101. * Uploads the updated texture data to the GPU.
  42102. *
  42103. * @param {Texture} texture - The texture.
  42104. * @param {Object} [options={}] - Optional configuration parameter.
  42105. */
  42106. updateTexture( texture, options ) {
  42107. const { gl } = this;
  42108. const { width, height } = options;
  42109. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  42110. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  42111. return;
  42112. const getImage = ( source ) => {
  42113. if ( source.isDataTexture ) {
  42114. return source.image.data;
  42115. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  42116. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  42117. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  42118. source instanceof OffscreenCanvas ) {
  42119. return source;
  42120. }
  42121. return source.data;
  42122. };
  42123. this.backend.state.bindTexture( glTextureType, textureGPU );
  42124. this.setTextureParameters( glTextureType, texture );
  42125. if ( texture.isCompressedTexture ) {
  42126. const mipmaps = texture.mipmaps;
  42127. const image = options.image;
  42128. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42129. const mipmap = mipmaps[ i ];
  42130. if ( texture.isCompressedArrayTexture ) {
  42131. if ( texture.format !== gl.RGBA ) {
  42132. if ( glFormat !== null ) {
  42133. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  42134. } else {
  42135. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  42136. }
  42137. } else {
  42138. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  42139. }
  42140. } else {
  42141. if ( glFormat !== null ) {
  42142. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  42143. } else {
  42144. console.warn( 'Unsupported compressed texture format' );
  42145. }
  42146. }
  42147. }
  42148. } else if ( texture.isCubeTexture ) {
  42149. const images = options.images;
  42150. for ( let i = 0; i < 6; i ++ ) {
  42151. const image = getImage( images[ i ] );
  42152. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  42153. }
  42154. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  42155. const image = options.image;
  42156. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42157. } else if ( texture.isData3DTexture ) {
  42158. const image = options.image;
  42159. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42160. } else if ( texture.isVideoTexture ) {
  42161. texture.update();
  42162. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  42163. } else {
  42164. const image = getImage( options.image );
  42165. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  42166. }
  42167. }
  42168. /**
  42169. * Generates mipmaps for the given texture.
  42170. *
  42171. * @param {Texture} texture - The texture.
  42172. */
  42173. generateMipmaps( texture ) {
  42174. const { gl, backend } = this;
  42175. const { textureGPU, glTextureType } = backend.get( texture );
  42176. backend.state.bindTexture( glTextureType, textureGPU );
  42177. gl.generateMipmap( glTextureType );
  42178. }
  42179. /**
  42180. * Deallocates the render buffers of the given render target.
  42181. *
  42182. * @param {RenderTarget} renderTarget - The render target.
  42183. */
  42184. deallocateRenderBuffers( renderTarget ) {
  42185. const { gl, backend } = this;
  42186. // remove framebuffer reference
  42187. if ( renderTarget ) {
  42188. const renderContextData = backend.get( renderTarget );
  42189. renderContextData.renderBufferStorageSetup = undefined;
  42190. if ( renderContextData.framebuffers ) {
  42191. for ( const cacheKey in renderContextData.framebuffers ) {
  42192. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  42193. }
  42194. delete renderContextData.framebuffers;
  42195. }
  42196. if ( renderContextData.depthRenderbuffer ) {
  42197. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  42198. delete renderContextData.depthRenderbuffer;
  42199. }
  42200. if ( renderContextData.stencilRenderbuffer ) {
  42201. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  42202. delete renderContextData.stencilRenderbuffer;
  42203. }
  42204. if ( renderContextData.msaaFrameBuffer ) {
  42205. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  42206. delete renderContextData.msaaFrameBuffer;
  42207. }
  42208. if ( renderContextData.msaaRenderbuffers ) {
  42209. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  42210. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  42211. }
  42212. delete renderContextData.msaaRenderbuffers;
  42213. }
  42214. }
  42215. }
  42216. /**
  42217. * Destroys the GPU data for the given texture object.
  42218. *
  42219. * @param {Texture} texture - The texture.
  42220. */
  42221. destroyTexture( texture ) {
  42222. const { gl, backend } = this;
  42223. const { textureGPU, renderTarget } = backend.get( texture );
  42224. this.deallocateRenderBuffers( renderTarget );
  42225. gl.deleteTexture( textureGPU );
  42226. backend.delete( texture );
  42227. }
  42228. /**
  42229. * Copies data of the given source texture to the given destination texture.
  42230. *
  42231. * @param {Texture} srcTexture - The source texture.
  42232. * @param {Texture} dstTexture - The destination texture.
  42233. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  42234. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42235. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42236. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42237. */
  42238. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42239. const { gl, backend } = this;
  42240. const { state } = this.backend;
  42241. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  42242. state.bindTexture( glTextureType, dstTextureGPU );
  42243. // gather the necessary dimensions to copy
  42244. let width, height, depth, minX, minY, minZ;
  42245. let dstX, dstY, dstZ;
  42246. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  42247. if ( srcRegion !== null ) {
  42248. width = srcRegion.max.x - srcRegion.min.x;
  42249. height = srcRegion.max.y - srcRegion.min.y;
  42250. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  42251. minX = srcRegion.min.x;
  42252. minY = srcRegion.min.y;
  42253. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  42254. } else {
  42255. const levelScale = Math.pow( 2, - srcLevel );
  42256. width = Math.floor( image.width * levelScale );
  42257. height = Math.floor( image.height * levelScale );
  42258. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  42259. depth = image.depth;
  42260. } else if ( srcTexture.isData3DTexture ) {
  42261. depth = Math.floor( image.depth * levelScale );
  42262. } else {
  42263. depth = 1;
  42264. }
  42265. minX = 0;
  42266. minY = 0;
  42267. minZ = 0;
  42268. }
  42269. if ( dstPosition !== null ) {
  42270. dstX = dstPosition.x;
  42271. dstY = dstPosition.y;
  42272. dstZ = dstPosition.z;
  42273. } else {
  42274. dstX = 0;
  42275. dstY = 0;
  42276. dstZ = 0;
  42277. }
  42278. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  42279. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  42280. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  42281. // used for copying data from cpu
  42282. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  42283. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  42284. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  42285. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  42286. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  42287. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  42288. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  42289. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  42290. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  42291. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  42292. // set up the src texture
  42293. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  42294. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  42295. const srcTextureData = backend.get( srcTexture );
  42296. const dstTextureData = backend.get( dstTexture );
  42297. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  42298. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  42299. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  42300. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  42301. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  42302. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  42303. let mask = gl.COLOR_BUFFER_BIT;
  42304. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  42305. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  42306. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  42307. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  42308. } else {
  42309. if ( isDst3D ) {
  42310. // copy data into the 3d texture
  42311. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  42312. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  42313. } else if ( dstTexture.isCompressedArrayTexture ) {
  42314. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  42315. } else {
  42316. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  42317. }
  42318. } else {
  42319. // copy data into the 2d texture
  42320. if ( srcTexture.isDataTexture ) {
  42321. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  42322. } else if ( srcTexture.isCompressedTexture ) {
  42323. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  42324. } else {
  42325. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  42326. }
  42327. }
  42328. }
  42329. // reset values
  42330. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  42331. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  42332. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  42333. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  42334. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  42335. // Generate mipmaps only when copying level 0
  42336. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  42337. gl.generateMipmap( glTextureType );
  42338. }
  42339. state.unbindTexture();
  42340. }
  42341. /**
  42342. * Copies the current bound framebuffer to the given texture.
  42343. *
  42344. * @param {Texture} texture - The destination texture.
  42345. * @param {RenderContext} renderContext - The render context.
  42346. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42347. */
  42348. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42349. const { gl } = this;
  42350. const { state } = this.backend;
  42351. const { textureGPU } = this.backend.get( texture );
  42352. const { x, y, z: width, w: height } = rectangle;
  42353. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  42354. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  42355. if ( requireDrawFrameBuffer ) {
  42356. const partial = ( x !== 0 || y !== 0 );
  42357. let mask;
  42358. let attachment;
  42359. if ( texture.isDepthTexture === true ) {
  42360. mask = gl.DEPTH_BUFFER_BIT;
  42361. attachment = gl.DEPTH_ATTACHMENT;
  42362. if ( renderContext.stencil ) {
  42363. mask |= gl.STENCIL_BUFFER_BIT;
  42364. }
  42365. } else {
  42366. mask = gl.COLOR_BUFFER_BIT;
  42367. attachment = gl.COLOR_ATTACHMENT0;
  42368. }
  42369. if ( partial ) {
  42370. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  42371. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  42372. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42373. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42374. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  42375. const flippedY = srcHeight - y - height;
  42376. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  42377. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42378. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42379. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  42380. state.unbindTexture();
  42381. } else {
  42382. const fb = gl.createFramebuffer();
  42383. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42384. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  42385. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  42386. gl.deleteFramebuffer( fb );
  42387. }
  42388. } else {
  42389. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42390. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  42391. state.unbindTexture();
  42392. }
  42393. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  42394. this.backend._setFramebuffer( renderContext );
  42395. }
  42396. /**
  42397. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  42398. *
  42399. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  42400. * @param {RenderContext} renderContext - The render context.
  42401. * @param {number} samples - The MSAA sample count.
  42402. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  42403. */
  42404. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  42405. const { gl } = this;
  42406. const renderTarget = renderContext.renderTarget;
  42407. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  42408. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  42409. if ( depthBuffer && ! stencilBuffer ) {
  42410. let glInternalFormat = gl.DEPTH_COMPONENT24;
  42411. if ( useMultisampledRTT === true ) {
  42412. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42413. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  42414. } else if ( samples > 0 ) {
  42415. if ( depthTexture && depthTexture.isDepthTexture ) {
  42416. if ( depthTexture.type === gl.FLOAT ) {
  42417. glInternalFormat = gl.DEPTH_COMPONENT32F;
  42418. }
  42419. }
  42420. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  42421. } else {
  42422. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  42423. }
  42424. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42425. } else if ( depthBuffer && stencilBuffer ) {
  42426. if ( samples > 0 ) {
  42427. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  42428. } else {
  42429. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  42430. }
  42431. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42432. }
  42433. }
  42434. /**
  42435. * Returns texture data as a typed array.
  42436. *
  42437. * @async
  42438. * @param {Texture} texture - The texture to copy.
  42439. * @param {number} x - The x coordinate of the copy origin.
  42440. * @param {number} y - The y coordinate of the copy origin.
  42441. * @param {number} width - The width of the copy.
  42442. * @param {number} height - The height of the copy.
  42443. * @param {number} faceIndex - The face index.
  42444. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42445. */
  42446. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42447. const { backend, gl } = this;
  42448. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  42449. const fb = gl.createFramebuffer();
  42450. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42451. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  42452. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  42453. const typedArrayType = this._getTypedArrayType( glType );
  42454. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  42455. const elementCount = width * height;
  42456. const byteLength = elementCount * bytesPerTexel;
  42457. const buffer = gl.createBuffer();
  42458. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42459. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  42460. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  42461. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42462. await backend.utils._clientWaitAsync();
  42463. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  42464. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42465. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  42466. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42467. gl.deleteFramebuffer( fb );
  42468. return dstBuffer;
  42469. }
  42470. /**
  42471. * Returns the corresponding typed array type for the given WebGL data type.
  42472. *
  42473. * @private
  42474. * @param {GLenum} glType - The WebGL data type.
  42475. * @return {TypedArray.constructor} The typed array type.
  42476. */
  42477. _getTypedArrayType( glType ) {
  42478. const { gl } = this;
  42479. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  42480. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  42481. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  42482. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  42483. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  42484. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  42485. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  42486. if ( glType === gl.FLOAT ) return Float32Array;
  42487. throw new Error( `Unsupported WebGL type: ${glType}` );
  42488. }
  42489. /**
  42490. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  42491. *
  42492. * @private
  42493. * @param {GLenum} glType - The WebGL data type.
  42494. * @param {GLenum} glFormat - The WebGL texture format.
  42495. * @return {number} The bytes-per-texel.
  42496. */
  42497. _getBytesPerTexel( glType, glFormat ) {
  42498. const { gl } = this;
  42499. let bytesPerComponent = 0;
  42500. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  42501. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  42502. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  42503. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  42504. glType === gl.UNSIGNED_SHORT ||
  42505. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  42506. if ( glType === gl.UNSIGNED_INT ||
  42507. glType === gl.FLOAT ) bytesPerComponent = 4;
  42508. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  42509. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  42510. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  42511. }
  42512. }
  42513. /**
  42514. * A WebGL 2 backend utility module for managing extensions.
  42515. *
  42516. * @private
  42517. */
  42518. class WebGLExtensions {
  42519. /**
  42520. * Constructs a new utility object.
  42521. *
  42522. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42523. */
  42524. constructor( backend ) {
  42525. /**
  42526. * A reference to the WebGL 2 backend.
  42527. *
  42528. * @type {WebGLBackend}
  42529. */
  42530. this.backend = backend;
  42531. /**
  42532. * A reference to the rendering context.
  42533. *
  42534. * @type {WebGL2RenderingContext}
  42535. */
  42536. this.gl = this.backend.gl;
  42537. /**
  42538. * A list with all the supported WebGL extensions.
  42539. *
  42540. * @type {Array<string>}
  42541. */
  42542. this.availableExtensions = this.gl.getSupportedExtensions();
  42543. /**
  42544. * A dictionary with requested WebGL extensions.
  42545. * The key is the name of the extension, the value
  42546. * the requested extension object.
  42547. *
  42548. * @type {Object<string,Object>}
  42549. */
  42550. this.extensions = {};
  42551. }
  42552. /**
  42553. * Returns the extension object for the given extension name.
  42554. *
  42555. * @param {string} name - The extension name.
  42556. * @return {Object} The extension object.
  42557. */
  42558. get( name ) {
  42559. let extension = this.extensions[ name ];
  42560. if ( extension === undefined ) {
  42561. extension = this.gl.getExtension( name );
  42562. this.extensions[ name ] = extension;
  42563. }
  42564. return extension;
  42565. }
  42566. /**
  42567. * Returns `true` if the requested extension is available.
  42568. *
  42569. * @param {string} name - The extension name.
  42570. * @return {boolean} Whether the given extension is available or not.
  42571. */
  42572. has( name ) {
  42573. return this.availableExtensions.includes( name );
  42574. }
  42575. }
  42576. /**
  42577. * A WebGL 2 backend utility module for managing the device's capabilities.
  42578. *
  42579. * @private
  42580. */
  42581. class WebGLCapabilities {
  42582. /**
  42583. * Constructs a new utility object.
  42584. *
  42585. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42586. */
  42587. constructor( backend ) {
  42588. /**
  42589. * A reference to the WebGL 2 backend.
  42590. *
  42591. * @type {WebGLBackend}
  42592. */
  42593. this.backend = backend;
  42594. /**
  42595. * This value holds the cached max anisotropy value.
  42596. *
  42597. * @type {?number}
  42598. * @default null
  42599. */
  42600. this.maxAnisotropy = null;
  42601. }
  42602. /**
  42603. * Returns the maximum anisotropy texture filtering value. This value
  42604. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  42605. * WebGL extension.
  42606. *
  42607. * @return {number} The maximum anisotropy texture filtering value.
  42608. */
  42609. getMaxAnisotropy() {
  42610. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  42611. const gl = this.backend.gl;
  42612. const extensions = this.backend.extensions;
  42613. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  42614. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  42615. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  42616. } else {
  42617. this.maxAnisotropy = 0;
  42618. }
  42619. return this.maxAnisotropy;
  42620. }
  42621. }
  42622. const GLFeatureName = {
  42623. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  42624. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  42625. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  42626. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  42627. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  42628. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  42629. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  42630. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  42631. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  42632. 'OVR_multiview2': 'OVR_multiview2'
  42633. };
  42634. class WebGLBufferRenderer {
  42635. constructor( backend ) {
  42636. this.gl = backend.gl;
  42637. this.extensions = backend.extensions;
  42638. this.info = backend.renderer.info;
  42639. this.mode = null;
  42640. this.index = 0;
  42641. this.type = null;
  42642. this.object = null;
  42643. }
  42644. render( start, count ) {
  42645. const { gl, mode, object, type, info, index } = this;
  42646. if ( index !== 0 ) {
  42647. gl.drawElements( mode, count, type, start );
  42648. } else {
  42649. gl.drawArrays( mode, start, count );
  42650. }
  42651. info.update( object, count, 1 );
  42652. }
  42653. renderInstances( start, count, primcount ) {
  42654. const { gl, mode, type, index, object, info } = this;
  42655. if ( primcount === 0 ) return;
  42656. if ( index !== 0 ) {
  42657. gl.drawElementsInstanced( mode, count, type, start, primcount );
  42658. } else {
  42659. gl.drawArraysInstanced( mode, start, count, primcount );
  42660. }
  42661. info.update( object, count, primcount );
  42662. }
  42663. renderMultiDraw( starts, counts, drawCount ) {
  42664. const { extensions, mode, object, info } = this;
  42665. if ( drawCount === 0 ) return;
  42666. const extension = extensions.get( 'WEBGL_multi_draw' );
  42667. if ( extension === null ) {
  42668. for ( let i = 0; i < drawCount; i ++ ) {
  42669. this.render( starts[ i ], counts[ i ] );
  42670. }
  42671. } else {
  42672. if ( this.index !== 0 ) {
  42673. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  42674. } else {
  42675. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  42676. }
  42677. let elementCount = 0;
  42678. for ( let i = 0; i < drawCount; i ++ ) {
  42679. elementCount += counts[ i ];
  42680. }
  42681. info.update( object, elementCount, 1 );
  42682. }
  42683. }
  42684. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  42685. const { extensions, mode, object, info } = this;
  42686. if ( drawCount === 0 ) return;
  42687. const extension = extensions.get( 'WEBGL_multi_draw' );
  42688. if ( extension === null ) {
  42689. for ( let i = 0; i < drawCount; i ++ ) {
  42690. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  42691. }
  42692. } else {
  42693. if ( this.index !== 0 ) {
  42694. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  42695. } else {
  42696. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  42697. }
  42698. let elementCount = 0;
  42699. for ( let i = 0; i < drawCount; i ++ ) {
  42700. elementCount += counts[ i ] * primcount[ i ];
  42701. }
  42702. info.update( object, elementCount, 1 );
  42703. }
  42704. }
  42705. //
  42706. }
  42707. /**
  42708. * Abstract base class of a timestamp query pool.
  42709. *
  42710. * @abstract
  42711. */
  42712. class TimestampQueryPool {
  42713. /**
  42714. * Creates a new timestamp query pool.
  42715. *
  42716. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  42717. */
  42718. constructor( maxQueries = 256 ) {
  42719. /**
  42720. * Whether to track timestamps or not.
  42721. *
  42722. * @type {boolean}
  42723. * @default true
  42724. */
  42725. this.trackTimestamp = true;
  42726. /**
  42727. * Maximum number of queries this pool can hold.
  42728. *
  42729. * @type {number}
  42730. * @default 256
  42731. */
  42732. this.maxQueries = maxQueries;
  42733. /**
  42734. * How many queries allocated so far.
  42735. *
  42736. * @type {number}
  42737. * @default 0
  42738. */
  42739. this.currentQueryIndex = 0;
  42740. /**
  42741. * Tracks offsets for different contexts.
  42742. *
  42743. * @type {Map<string, number>}
  42744. */
  42745. this.queryOffsets = new Map();
  42746. /**
  42747. * Whether the pool has been disposed or not.
  42748. *
  42749. * @type {boolean}
  42750. * @default false
  42751. */
  42752. this.isDisposed = false;
  42753. /**
  42754. * TODO
  42755. *
  42756. * @type {number}
  42757. * @default 0
  42758. */
  42759. this.lastValue = 0;
  42760. /**
  42761. * TODO
  42762. *
  42763. * @type {boolean}
  42764. * @default false
  42765. */
  42766. this.pendingResolve = false;
  42767. }
  42768. /**
  42769. * Allocate queries for a specific renderContext.
  42770. *
  42771. * @abstract
  42772. * @param {Object} renderContext - The render context to allocate queries for.
  42773. * @returns {?number}
  42774. */
  42775. allocateQueriesForContext( /* renderContext */ ) {}
  42776. /**
  42777. * Resolve all timestamps and return data (or process them).
  42778. *
  42779. * @abstract
  42780. * @async
  42781. * @returns {Promise<number>|number} The resolved timestamp value.
  42782. */
  42783. async resolveQueriesAsync() {}
  42784. /**
  42785. * Dispose of the query pool.
  42786. *
  42787. * @abstract
  42788. */
  42789. dispose() {}
  42790. }
  42791. /**
  42792. * Manages a pool of WebGL timestamp queries for performance measurement.
  42793. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  42794. *
  42795. * @augments TimestampQueryPool
  42796. */
  42797. class WebGLTimestampQueryPool extends TimestampQueryPool {
  42798. /**
  42799. * Creates a new WebGL timestamp query pool.
  42800. *
  42801. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  42802. * @param {string} type - The type identifier for this query pool.
  42803. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  42804. */
  42805. constructor( gl, type, maxQueries = 2048 ) {
  42806. super( maxQueries );
  42807. this.gl = gl;
  42808. this.type = type;
  42809. // Check for timer query extensions
  42810. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  42811. gl.getExtension( 'EXT_disjoint_timer_query' );
  42812. if ( ! this.ext ) {
  42813. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  42814. this.trackTimestamp = false;
  42815. return;
  42816. }
  42817. // Create query objects
  42818. this.queries = [];
  42819. for ( let i = 0; i < this.maxQueries; i ++ ) {
  42820. this.queries.push( gl.createQuery() );
  42821. }
  42822. this.activeQuery = null;
  42823. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  42824. }
  42825. /**
  42826. * Allocates a pair of queries for a given render context.
  42827. *
  42828. * @param {Object} renderContext - The render context to allocate queries for.
  42829. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  42830. */
  42831. allocateQueriesForContext( renderContext ) {
  42832. if ( ! this.trackTimestamp ) return null;
  42833. // Check if we have enough space for a new query pair
  42834. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  42835. 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() } ).` );
  42836. return null;
  42837. }
  42838. const baseOffset = this.currentQueryIndex;
  42839. this.currentQueryIndex += 2;
  42840. // Initialize query states
  42841. this.queryStates.set( baseOffset, 'inactive' );
  42842. this.queryOffsets.set( renderContext.id, baseOffset );
  42843. return baseOffset;
  42844. }
  42845. /**
  42846. * Begins a timestamp query for the specified render context.
  42847. *
  42848. * @param {Object} renderContext - The render context to begin timing for.
  42849. */
  42850. beginQuery( renderContext ) {
  42851. if ( ! this.trackTimestamp || this.isDisposed ) {
  42852. return;
  42853. }
  42854. const baseOffset = this.queryOffsets.get( renderContext.id );
  42855. if ( baseOffset == null ) {
  42856. return;
  42857. }
  42858. // Don't start a new query if there's an active one
  42859. if ( this.activeQuery !== null ) {
  42860. return;
  42861. }
  42862. const query = this.queries[ baseOffset ];
  42863. if ( ! query ) {
  42864. return;
  42865. }
  42866. try {
  42867. // Only begin if query is inactive
  42868. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  42869. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  42870. this.activeQuery = baseOffset;
  42871. this.queryStates.set( baseOffset, 'started' );
  42872. }
  42873. } catch ( error ) {
  42874. console.error( 'Error in beginQuery:', error );
  42875. this.activeQuery = null;
  42876. this.queryStates.set( baseOffset, 'inactive' );
  42877. }
  42878. }
  42879. /**
  42880. * Ends the active timestamp query for the specified render context.
  42881. *
  42882. * @param {Object} renderContext - The render context to end timing for.
  42883. * @param {string} renderContext.id - Unique identifier for the render context.
  42884. */
  42885. endQuery( renderContext ) {
  42886. if ( ! this.trackTimestamp || this.isDisposed ) {
  42887. return;
  42888. }
  42889. const baseOffset = this.queryOffsets.get( renderContext.id );
  42890. if ( baseOffset == null ) {
  42891. return;
  42892. }
  42893. // Only end if this is the active query
  42894. if ( this.activeQuery !== baseOffset ) {
  42895. return;
  42896. }
  42897. try {
  42898. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  42899. this.queryStates.set( baseOffset, 'ended' );
  42900. this.activeQuery = null;
  42901. } catch ( error ) {
  42902. console.error( 'Error in endQuery:', error );
  42903. // Reset state on error
  42904. this.queryStates.set( baseOffset, 'inactive' );
  42905. this.activeQuery = null;
  42906. }
  42907. }
  42908. /**
  42909. * Asynchronously resolves all completed queries and returns the total duration.
  42910. *
  42911. * @async
  42912. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  42913. */
  42914. async resolveQueriesAsync() {
  42915. if ( ! this.trackTimestamp || this.pendingResolve ) {
  42916. return this.lastValue;
  42917. }
  42918. this.pendingResolve = true;
  42919. try {
  42920. // Wait for all ended queries to complete
  42921. const resolvePromises = [];
  42922. for ( const [ baseOffset, state ] of this.queryStates ) {
  42923. if ( state === 'ended' ) {
  42924. const query = this.queries[ baseOffset ];
  42925. resolvePromises.push( this.resolveQuery( query ) );
  42926. }
  42927. }
  42928. if ( resolvePromises.length === 0 ) {
  42929. return this.lastValue;
  42930. }
  42931. const results = await Promise.all( resolvePromises );
  42932. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  42933. // Store the last valid result
  42934. this.lastValue = totalDuration;
  42935. // Reset states
  42936. this.currentQueryIndex = 0;
  42937. this.queryOffsets.clear();
  42938. this.queryStates.clear();
  42939. this.activeQuery = null;
  42940. return totalDuration;
  42941. } catch ( error ) {
  42942. console.error( 'Error resolving queries:', error );
  42943. return this.lastValue;
  42944. } finally {
  42945. this.pendingResolve = false;
  42946. }
  42947. }
  42948. /**
  42949. * Resolves a single query, checking for completion and disjoint operation.
  42950. *
  42951. * @async
  42952. * @param {WebGLQuery} query - The query object to resolve.
  42953. * @returns {Promise<number>} The elapsed time in milliseconds.
  42954. */
  42955. async resolveQuery( query ) {
  42956. return new Promise( ( resolve ) => {
  42957. if ( this.isDisposed ) {
  42958. resolve( this.lastValue );
  42959. return;
  42960. }
  42961. let timeoutId;
  42962. let isResolved = false;
  42963. const cleanup = () => {
  42964. if ( timeoutId ) {
  42965. clearTimeout( timeoutId );
  42966. timeoutId = null;
  42967. }
  42968. };
  42969. const finalizeResolution = ( value ) => {
  42970. if ( ! isResolved ) {
  42971. isResolved = true;
  42972. cleanup();
  42973. resolve( value );
  42974. }
  42975. };
  42976. const checkQuery = () => {
  42977. if ( this.isDisposed ) {
  42978. finalizeResolution( this.lastValue );
  42979. return;
  42980. }
  42981. try {
  42982. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  42983. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  42984. if ( disjoint ) {
  42985. finalizeResolution( this.lastValue );
  42986. return;
  42987. }
  42988. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  42989. if ( ! available ) {
  42990. timeoutId = setTimeout( checkQuery, 1 );
  42991. return;
  42992. }
  42993. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  42994. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  42995. } catch ( error ) {
  42996. console.error( 'Error checking query:', error );
  42997. resolve( this.lastValue );
  42998. }
  42999. };
  43000. checkQuery();
  43001. } );
  43002. }
  43003. /**
  43004. * Releases all resources held by this query pool.
  43005. * This includes deleting all query objects and clearing internal state.
  43006. */
  43007. dispose() {
  43008. if ( this.isDisposed ) {
  43009. return;
  43010. }
  43011. this.isDisposed = true;
  43012. if ( ! this.trackTimestamp ) return;
  43013. for ( const query of this.queries ) {
  43014. this.gl.deleteQuery( query );
  43015. }
  43016. this.queries = [];
  43017. this.queryStates.clear();
  43018. this.queryOffsets.clear();
  43019. this.lastValue = 0;
  43020. this.activeQuery = null;
  43021. }
  43022. }
  43023. /**
  43024. * A backend implementation targeting WebGL 2.
  43025. *
  43026. * @private
  43027. * @augments Backend
  43028. */
  43029. class WebGLBackend extends Backend {
  43030. /**
  43031. * WebGLBackend options.
  43032. *
  43033. * @typedef {Object} WebGLBackend~Options
  43034. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  43035. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  43036. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  43037. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  43038. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  43039. * @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.
  43040. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  43041. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  43042. */
  43043. /**
  43044. * Constructs a new WebGPU backend.
  43045. *
  43046. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  43047. */
  43048. constructor( parameters = {} ) {
  43049. super( parameters );
  43050. /**
  43051. * This flag can be used for type testing.
  43052. *
  43053. * @type {boolean}
  43054. * @readonly
  43055. * @default true
  43056. */
  43057. this.isWebGLBackend = true;
  43058. /**
  43059. * A reference to a backend module holding shader attribute-related
  43060. * utility functions.
  43061. *
  43062. * @type {?WebGLAttributeUtils}
  43063. * @default null
  43064. */
  43065. this.attributeUtils = null;
  43066. /**
  43067. * A reference to a backend module holding extension-related
  43068. * utility functions.
  43069. *
  43070. * @type {?WebGLExtensions}
  43071. * @default null
  43072. */
  43073. this.extensions = null;
  43074. /**
  43075. * A reference to a backend module holding capability-related
  43076. * utility functions.
  43077. *
  43078. * @type {?WebGLCapabilities}
  43079. * @default null
  43080. */
  43081. this.capabilities = null;
  43082. /**
  43083. * A reference to a backend module holding texture-related
  43084. * utility functions.
  43085. *
  43086. * @type {?WebGLTextureUtils}
  43087. * @default null
  43088. */
  43089. this.textureUtils = null;
  43090. /**
  43091. * A reference to a backend module holding renderer-related
  43092. * utility functions.
  43093. *
  43094. * @type {?WebGLBufferRenderer}
  43095. * @default null
  43096. */
  43097. this.bufferRenderer = null;
  43098. /**
  43099. * A reference to the rendering context.
  43100. *
  43101. * @type {?WebGL2RenderingContext}
  43102. * @default null
  43103. */
  43104. this.gl = null;
  43105. /**
  43106. * A reference to a backend module holding state-related
  43107. * utility functions.
  43108. *
  43109. * @type {?WebGLState}
  43110. * @default null
  43111. */
  43112. this.state = null;
  43113. /**
  43114. * A reference to a backend module holding common
  43115. * utility functions.
  43116. *
  43117. * @type {?WebGLUtils}
  43118. * @default null
  43119. */
  43120. this.utils = null;
  43121. /**
  43122. * Dictionary for caching VAOs.
  43123. *
  43124. * @type {Object<string,WebGLVertexArrayObject>}
  43125. */
  43126. this.vaoCache = {};
  43127. /**
  43128. * Dictionary for caching transform feedback objects.
  43129. *
  43130. * @type {Object<string,WebGLTransformFeedback>}
  43131. */
  43132. this.transformFeedbackCache = {};
  43133. /**
  43134. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  43135. * Only relevant when using compute shaders.
  43136. *
  43137. * @type {boolean}
  43138. * @default false
  43139. */
  43140. this.discard = false;
  43141. /**
  43142. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  43143. * device does not support the extension.
  43144. *
  43145. * @type {?EXTDisjointTimerQueryWebGL2}
  43146. * @default null
  43147. */
  43148. this.disjoint = null;
  43149. /**
  43150. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  43151. * device does not support the extension.
  43152. *
  43153. * @type {?KHRParallelShaderCompile}
  43154. * @default null
  43155. */
  43156. this.parallel = null;
  43157. /**
  43158. * A reference to the current render context.
  43159. *
  43160. * @private
  43161. * @type {RenderContext}
  43162. * @default null
  43163. */
  43164. this._currentContext = null;
  43165. /**
  43166. * A unique collection of bindings.
  43167. *
  43168. * @private
  43169. * @type {WeakSet}
  43170. */
  43171. this._knownBindings = new WeakSet();
  43172. /**
  43173. * Whether the device supports framebuffers invalidation or not.
  43174. *
  43175. * @private
  43176. * @type {boolean}
  43177. */
  43178. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  43179. /**
  43180. * The target framebuffer when rendering with
  43181. * the WebXR device API.
  43182. *
  43183. * @private
  43184. * @type {WebGLFramebuffer}
  43185. * @default null
  43186. */
  43187. this._xrFramebuffer = null;
  43188. }
  43189. /**
  43190. * Initializes the backend so it is ready for usage.
  43191. *
  43192. * @param {Renderer} renderer - The renderer.
  43193. */
  43194. init( renderer ) {
  43195. super.init( renderer );
  43196. //
  43197. const parameters = this.parameters;
  43198. const contextAttributes = {
  43199. antialias: renderer.samples > 0,
  43200. alpha: true, // always true for performance reasons
  43201. depth: renderer.depth,
  43202. stencil: renderer.stencil
  43203. };
  43204. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  43205. function onContextLost( event ) {
  43206. event.preventDefault();
  43207. const contextLossInfo = {
  43208. api: 'WebGL',
  43209. message: event.statusMessage || 'Unknown reason',
  43210. reason: null,
  43211. originalEvent: event
  43212. };
  43213. renderer.onDeviceLost( contextLossInfo );
  43214. }
  43215. this._onContextLost = onContextLost;
  43216. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  43217. this.gl = glContext;
  43218. this.extensions = new WebGLExtensions( this );
  43219. this.capabilities = new WebGLCapabilities( this );
  43220. this.attributeUtils = new WebGLAttributeUtils( this );
  43221. this.textureUtils = new WebGLTextureUtils( this );
  43222. this.bufferRenderer = new WebGLBufferRenderer( this );
  43223. this.state = new WebGLState( this );
  43224. this.utils = new WebGLUtils( this );
  43225. this.extensions.get( 'EXT_color_buffer_float' );
  43226. this.extensions.get( 'WEBGL_clip_cull_distance' );
  43227. this.extensions.get( 'OES_texture_float_linear' );
  43228. this.extensions.get( 'EXT_color_buffer_half_float' );
  43229. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43230. this.extensions.get( 'WEBGL_render_shared_exponent' );
  43231. this.extensions.get( 'WEBGL_multi_draw' );
  43232. this.extensions.get( 'OVR_multiview2' );
  43233. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  43234. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  43235. }
  43236. /**
  43237. * The coordinate system of the backend.
  43238. *
  43239. * @type {number}
  43240. * @readonly
  43241. */
  43242. get coordinateSystem() {
  43243. return WebGLCoordinateSystem;
  43244. }
  43245. /**
  43246. * This method performs a readback operation by moving buffer data from
  43247. * a storage buffer attribute from the GPU to the CPU.
  43248. *
  43249. * @async
  43250. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43251. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43252. */
  43253. async getArrayBufferAsync( attribute ) {
  43254. return await this.attributeUtils.getArrayBufferAsync( attribute );
  43255. }
  43256. /**
  43257. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43258. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43259. *
  43260. * @async
  43261. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43262. */
  43263. async waitForGPU() {
  43264. await this.utils._clientWaitAsync();
  43265. }
  43266. /**
  43267. * Ensures the backend is XR compatible.
  43268. *
  43269. * @async
  43270. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  43271. */
  43272. async makeXRCompatible() {
  43273. const attributes = this.gl.getContextAttributes();
  43274. if ( attributes.xrCompatible !== true ) {
  43275. await this.gl.makeXRCompatible();
  43276. }
  43277. }
  43278. /**
  43279. * Sets the XR rendering destination.
  43280. *
  43281. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  43282. */
  43283. setXRTarget( xrFramebuffer ) {
  43284. this._xrFramebuffer = xrFramebuffer;
  43285. }
  43286. /**
  43287. * Configures the given XR render target with external textures.
  43288. *
  43289. * This method is only relevant when using the WebXR Layers API.
  43290. *
  43291. * @param {XRRenderTarget} renderTarget - The XR render target.
  43292. * @param {WebGLTexture} colorTexture - A native color texture.
  43293. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  43294. */
  43295. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  43296. const gl = this.gl;
  43297. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  43298. if ( depthTexture !== null ) {
  43299. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  43300. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  43301. // The multisample_render_to_texture extension doesn't work properly if there
  43302. // are midframe flushes and an external depth texture.
  43303. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget.autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  43304. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  43305. }
  43306. renderTarget.autoAllocateDepthBuffer = false;
  43307. }
  43308. }
  43309. /**
  43310. * Inits a time stamp query for the given render context.
  43311. *
  43312. * @param {RenderContext} renderContext - The render context.
  43313. */
  43314. initTimestampQuery( renderContext ) {
  43315. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43316. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43317. if ( ! this.timestampQueryPool[ type ] ) {
  43318. // TODO: Variable maxQueries?
  43319. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  43320. }
  43321. const timestampQueryPool = this.timestampQueryPool[ type ];
  43322. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  43323. if ( baseOffset !== null ) {
  43324. timestampQueryPool.beginQuery( renderContext );
  43325. }
  43326. }
  43327. // timestamp utils
  43328. /**
  43329. * Prepares the timestamp buffer.
  43330. *
  43331. * @param {RenderContext} renderContext - The render context.
  43332. */
  43333. prepareTimestampBuffer( renderContext ) {
  43334. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43335. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43336. const timestampQueryPool = this.timestampQueryPool[ type ];
  43337. timestampQueryPool.endQuery( renderContext );
  43338. }
  43339. /**
  43340. * Returns the backend's rendering context.
  43341. *
  43342. * @return {WebGL2RenderingContext} The rendering context.
  43343. */
  43344. getContext() {
  43345. return this.gl;
  43346. }
  43347. /**
  43348. * This method is executed at the beginning of a render call and prepares
  43349. * the WebGL state for upcoming render calls
  43350. *
  43351. * @param {RenderContext} renderContext - The render context.
  43352. */
  43353. beginRender( renderContext ) {
  43354. const { state, gl } = this;
  43355. const renderContextData = this.get( renderContext );
  43356. //
  43357. if ( renderContext.viewport ) {
  43358. this.updateViewport( renderContext );
  43359. } else {
  43360. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  43361. }
  43362. if ( renderContext.scissor ) {
  43363. const { x, y, width, height } = renderContext.scissorValue;
  43364. state.scissor( x, renderContext.height - height - y, width, height );
  43365. }
  43366. //
  43367. this.initTimestampQuery( renderContext );
  43368. renderContextData.previousContext = this._currentContext;
  43369. this._currentContext = renderContext;
  43370. this._setFramebuffer( renderContext );
  43371. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  43372. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43373. if ( occlusionQueryCount > 0 ) {
  43374. // Get a reference to the array of objects with queries. The renderContextData property
  43375. // can be changed by another render pass before the async reading of all previous queries complete
  43376. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  43377. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  43378. renderContextData.lastOcclusionObject = null;
  43379. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  43380. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  43381. renderContextData.occlusionQueryIndex = 0;
  43382. }
  43383. }
  43384. /**
  43385. * This method is executed at the end of a render call and finalizes work
  43386. * after draw calls.
  43387. *
  43388. * @param {RenderContext} renderContext - The render context.
  43389. */
  43390. finishRender( renderContext ) {
  43391. const { gl, state } = this;
  43392. const renderContextData = this.get( renderContext );
  43393. const previousContext = renderContextData.previousContext;
  43394. state.resetVertexState();
  43395. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43396. if ( occlusionQueryCount > 0 ) {
  43397. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43398. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  43399. }
  43400. this.resolveOccludedAsync( renderContext );
  43401. }
  43402. const textures = renderContext.textures;
  43403. if ( textures !== null ) {
  43404. for ( let i = 0; i < textures.length; i ++ ) {
  43405. const texture = textures[ i ];
  43406. if ( texture.generateMipmaps ) {
  43407. this.generateMipmaps( texture );
  43408. }
  43409. }
  43410. }
  43411. this._currentContext = previousContext;
  43412. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  43413. const renderTargetContextData = this.get( renderContext.renderTarget );
  43414. const { samples } = renderContext.renderTarget;
  43415. if ( samples > 0 && this._useMultisampledExtension( renderContext.renderTarget ) === false ) {
  43416. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43417. const mask = gl.COLOR_BUFFER_BIT;
  43418. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43419. const textures = renderContext.textures;
  43420. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  43421. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43422. for ( let i = 0; i < textures.length; i ++ ) {
  43423. // TODO Add support for MRT
  43424. if ( renderContext.scissor ) {
  43425. const { x, y, width, height } = renderContext.scissorValue;
  43426. const viewY = renderContext.height - height - y;
  43427. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  43428. if ( this._supportsInvalidateFramebuffer === true ) {
  43429. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  43430. }
  43431. } else {
  43432. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  43433. if ( this._supportsInvalidateFramebuffer === true ) {
  43434. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  43435. }
  43436. }
  43437. }
  43438. }
  43439. }
  43440. if ( previousContext !== null ) {
  43441. this._setFramebuffer( previousContext );
  43442. if ( previousContext.viewport ) {
  43443. this.updateViewport( previousContext );
  43444. } else {
  43445. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  43446. }
  43447. }
  43448. this.prepareTimestampBuffer( renderContext );
  43449. }
  43450. /**
  43451. * This method processes the result of occlusion queries and writes it
  43452. * into render context data.
  43453. *
  43454. * @async
  43455. * @param {RenderContext} renderContext - The render context.
  43456. */
  43457. resolveOccludedAsync( renderContext ) {
  43458. const renderContextData = this.get( renderContext );
  43459. // handle occlusion query results
  43460. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  43461. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  43462. const occluded = new WeakSet();
  43463. const { gl } = this;
  43464. renderContextData.currentOcclusionQueryObjects = null;
  43465. renderContextData.currentOcclusionQueries = null;
  43466. const check = () => {
  43467. let completed = 0;
  43468. // check all queries and requeue as appropriate
  43469. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  43470. const query = currentOcclusionQueries[ i ];
  43471. if ( query === null ) continue;
  43472. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  43473. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  43474. currentOcclusionQueries[ i ] = null;
  43475. gl.deleteQuery( query );
  43476. completed ++;
  43477. }
  43478. }
  43479. if ( completed < currentOcclusionQueries.length ) {
  43480. requestAnimationFrame( check );
  43481. } else {
  43482. renderContextData.occluded = occluded;
  43483. }
  43484. };
  43485. check();
  43486. }
  43487. }
  43488. /**
  43489. * Returns `true` if the given 3D object is fully occluded by other
  43490. * 3D objects in the scene.
  43491. *
  43492. * @param {RenderContext} renderContext - The render context.
  43493. * @param {Object3D} object - The 3D object to test.
  43494. * @return {boolean} Whether the 3D object is fully occluded or not.
  43495. */
  43496. isOccluded( renderContext, object ) {
  43497. const renderContextData = this.get( renderContext );
  43498. return renderContextData.occluded && renderContextData.occluded.has( object );
  43499. }
  43500. /**
  43501. * Updates the viewport with the values from the given render context.
  43502. *
  43503. * @param {RenderContext} renderContext - The render context.
  43504. */
  43505. updateViewport( renderContext ) {
  43506. const { state } = this;
  43507. const { x, y, width, height } = renderContext.viewportValue;
  43508. state.viewport( x, renderContext.height - height - y, width, height );
  43509. }
  43510. /**
  43511. * Defines the scissor test.
  43512. *
  43513. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43514. */
  43515. setScissorTest( boolean ) {
  43516. const state = this.state;
  43517. state.setScissorTest( boolean );
  43518. }
  43519. /**
  43520. * Returns the clear color and alpha into a single
  43521. * color object.
  43522. *
  43523. * @return {Color4} The clear color.
  43524. */
  43525. getClearColor() {
  43526. const clearColor = super.getClearColor();
  43527. // Since the canvas is always created with alpha: true,
  43528. // WebGL must always premultiply the clear color.
  43529. clearColor.r *= clearColor.a;
  43530. clearColor.g *= clearColor.a;
  43531. clearColor.b *= clearColor.a;
  43532. return clearColor;
  43533. }
  43534. /**
  43535. * Performs a clear operation.
  43536. *
  43537. * @param {boolean} color - Whether the color buffer should be cleared or not.
  43538. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  43539. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  43540. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  43541. * @param {boolean} [setFrameBuffer=true] - TODO.
  43542. */
  43543. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  43544. const { gl, renderer } = this;
  43545. if ( descriptor === null ) {
  43546. const clearColor = this.getClearColor();
  43547. descriptor = {
  43548. textures: null,
  43549. clearColorValue: clearColor
  43550. };
  43551. }
  43552. //
  43553. let clear = 0;
  43554. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  43555. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  43556. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  43557. if ( clear !== 0 ) {
  43558. let clearColor;
  43559. if ( descriptor.clearColorValue ) {
  43560. clearColor = descriptor.clearColorValue;
  43561. } else {
  43562. clearColor = this.getClearColor();
  43563. }
  43564. const clearDepth = renderer.getClearDepth();
  43565. const clearStencil = renderer.getClearStencil();
  43566. if ( depth ) this.state.setDepthMask( true );
  43567. if ( descriptor.textures === null ) {
  43568. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  43569. gl.clear( clear );
  43570. } else {
  43571. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  43572. if ( color ) {
  43573. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  43574. if ( i === 0 ) {
  43575. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  43576. } else {
  43577. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  43578. }
  43579. }
  43580. }
  43581. if ( depth && stencil ) {
  43582. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  43583. } else if ( depth ) {
  43584. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  43585. } else if ( stencil ) {
  43586. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  43587. }
  43588. }
  43589. }
  43590. }
  43591. /**
  43592. * This method is executed at the beginning of a compute call and
  43593. * prepares the state for upcoming compute tasks.
  43594. *
  43595. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43596. */
  43597. beginCompute( computeGroup ) {
  43598. const { state, gl } = this;
  43599. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  43600. this.initTimestampQuery( computeGroup );
  43601. }
  43602. /**
  43603. * Executes a compute command for the given compute node.
  43604. *
  43605. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  43606. * @param {Node} computeNode - The compute node.
  43607. * @param {Array<BindGroup>} bindings - The bindings.
  43608. * @param {ComputePipeline} pipeline - The compute pipeline.
  43609. */
  43610. compute( computeGroup, computeNode, bindings, pipeline ) {
  43611. const { state, gl } = this;
  43612. if ( this.discard === false ) {
  43613. // required here to handle async behaviour of render.compute()
  43614. gl.enable( gl.RASTERIZER_DISCARD );
  43615. this.discard = true;
  43616. }
  43617. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  43618. const vaoKey = this._getVaoKey( attributes );
  43619. const vaoGPU = this.vaoCache[ vaoKey ];
  43620. if ( vaoGPU === undefined ) {
  43621. this._createVao( attributes );
  43622. } else {
  43623. state.setVertexState( vaoGPU );
  43624. }
  43625. state.useProgram( programGPU );
  43626. this._bindUniforms( bindings );
  43627. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  43628. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  43629. gl.beginTransformFeedback( gl.POINTS );
  43630. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  43631. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  43632. } else {
  43633. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  43634. }
  43635. gl.endTransformFeedback();
  43636. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  43637. // switch active buffers
  43638. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  43639. const dualAttributeData = transformBuffers[ i ];
  43640. if ( dualAttributeData.pbo ) {
  43641. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  43642. }
  43643. dualAttributeData.switchBuffers();
  43644. }
  43645. }
  43646. /**
  43647. * This method is executed at the end of a compute call and
  43648. * finalizes work after compute tasks.
  43649. *
  43650. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43651. */
  43652. finishCompute( computeGroup ) {
  43653. const gl = this.gl;
  43654. this.discard = false;
  43655. gl.disable( gl.RASTERIZER_DISCARD );
  43656. this.prepareTimestampBuffer( computeGroup );
  43657. if ( this._currentContext ) {
  43658. this._setFramebuffer( this._currentContext );
  43659. }
  43660. }
  43661. /**
  43662. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  43663. *
  43664. * @param {RenderContext} renderContext - The render context.
  43665. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  43666. *
  43667. * @private
  43668. */
  43669. _isRenderCameraDepthArray( renderContext ) {
  43670. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  43671. }
  43672. /**
  43673. * Executes a draw command for the given render object.
  43674. *
  43675. * @param {RenderObject} renderObject - The render object to draw.
  43676. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  43677. */
  43678. draw( renderObject/*, info*/ ) {
  43679. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  43680. const { programGPU } = this.get( pipeline );
  43681. const { gl, state } = this;
  43682. const contextData = this.get( context );
  43683. const drawParams = renderObject.getDrawParameters();
  43684. if ( drawParams === null ) return;
  43685. //
  43686. this._bindUniforms( renderObject.getBindings() );
  43687. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  43688. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  43689. state.useProgram( programGPU );
  43690. // vertex state
  43691. const renderObjectData = this.get( renderObject );
  43692. let vaoGPU = renderObjectData.staticVao;
  43693. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  43694. const vaoKey = this._getVaoKey( renderObject.getAttributes() );
  43695. vaoGPU = this.vaoCache[ vaoKey ];
  43696. if ( vaoGPU === undefined ) {
  43697. let staticVao;
  43698. ( { vaoGPU, staticVao } = this._createVao( renderObject.getAttributes() ) );
  43699. if ( staticVao ) {
  43700. renderObjectData.staticVao = vaoGPU;
  43701. renderObjectData.geometryId = renderObject.geometry.id;
  43702. }
  43703. }
  43704. }
  43705. const index = renderObject.getIndex();
  43706. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  43707. state.setVertexState( vaoGPU, indexGPU );
  43708. //
  43709. const lastObject = contextData.lastOcclusionObject;
  43710. if ( lastObject !== object && lastObject !== undefined ) {
  43711. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  43712. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  43713. contextData.occlusionQueryIndex ++;
  43714. }
  43715. if ( object.occlusionTest === true ) {
  43716. const query = gl.createQuery();
  43717. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  43718. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  43719. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  43720. }
  43721. contextData.lastOcclusionObject = object;
  43722. }
  43723. //
  43724. const renderer = this.bufferRenderer;
  43725. if ( object.isPoints ) renderer.mode = gl.POINTS;
  43726. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  43727. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  43728. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  43729. else {
  43730. if ( material.wireframe === true ) {
  43731. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  43732. renderer.mode = gl.LINES;
  43733. } else {
  43734. renderer.mode = gl.TRIANGLES;
  43735. }
  43736. }
  43737. //
  43738. const { vertexCount, instanceCount } = drawParams;
  43739. let { firstVertex } = drawParams;
  43740. renderer.object = object;
  43741. if ( index !== null ) {
  43742. firstVertex *= index.array.BYTES_PER_ELEMENT;
  43743. const indexData = this.get( index );
  43744. renderer.index = index.count;
  43745. renderer.type = indexData.type;
  43746. } else {
  43747. renderer.index = 0;
  43748. }
  43749. const draw = () => {
  43750. if ( object.isBatchedMesh ) {
  43751. if ( object._multiDrawInstances !== null ) {
  43752. // @deprecated, r174
  43753. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  43754. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  43755. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  43756. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  43757. } else {
  43758. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  43759. }
  43760. } else if ( instanceCount > 1 ) {
  43761. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  43762. } else {
  43763. renderer.render( firstVertex, vertexCount );
  43764. }
  43765. };
  43766. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  43767. const cameraData = this.get( renderObject.camera );
  43768. const cameras = renderObject.camera.cameras;
  43769. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  43770. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  43771. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  43772. const indexesGPU = [];
  43773. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  43774. const bufferGPU = gl.createBuffer();
  43775. data[ 0 ] = i;
  43776. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  43777. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  43778. indexesGPU.push( bufferGPU );
  43779. }
  43780. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  43781. }
  43782. const cameraIndexData = this.get( cameraIndex );
  43783. const pixelRatio = this.renderer.getPixelRatio();
  43784. const renderTarget = this._currentContext.renderTarget;
  43785. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  43786. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  43787. if ( isRenderCameraDepthArray ) {
  43788. // Clear the depth texture
  43789. const textureData = this.get( renderTarget.depthTexture );
  43790. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  43791. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  43792. const { stencilBuffer } = renderTarget;
  43793. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  43794. this.renderer._activeCubeFace = i;
  43795. this._currentContext.activeCubeFace = i;
  43796. this._setFramebuffer( this._currentContext );
  43797. this.clear( false, true, stencilBuffer, this._currentContext, false );
  43798. }
  43799. this.renderer._activeCubeFace = prevActiveCubeFace;
  43800. this._currentContext.activeCubeFace = prevActiveCubeFace;
  43801. }
  43802. }
  43803. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  43804. const subCamera = cameras[ i ];
  43805. if ( object.layers.test( subCamera.layers ) ) {
  43806. if ( isRenderCameraDepthArray ) {
  43807. // Update the active layer
  43808. this.renderer._activeCubeFace = i;
  43809. this._currentContext.activeCubeFace = i;
  43810. this._setFramebuffer( this._currentContext );
  43811. }
  43812. const vp = subCamera.viewport;
  43813. if ( vp !== undefined ) {
  43814. const x = vp.x * pixelRatio;
  43815. const y = vp.y * pixelRatio;
  43816. const width = vp.width * pixelRatio;
  43817. const height = vp.height * pixelRatio;
  43818. state.viewport(
  43819. Math.floor( x ),
  43820. Math.floor( renderObject.context.height - height - y ),
  43821. Math.floor( width ),
  43822. Math.floor( height )
  43823. );
  43824. }
  43825. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  43826. draw();
  43827. }
  43828. this._currentContext.activeCubeFace = prevActiveCubeFace;
  43829. this.renderer._activeCubeFace = prevActiveCubeFace;
  43830. }
  43831. } else {
  43832. draw();
  43833. }
  43834. }
  43835. /**
  43836. * Explain why always null is returned.
  43837. *
  43838. * @param {RenderObject} renderObject - The render object.
  43839. * @return {boolean} Whether the render pipeline requires an update or not.
  43840. */
  43841. needsRenderUpdate( /*renderObject*/ ) {
  43842. return false;
  43843. }
  43844. /**
  43845. * Explain why no cache key is computed.
  43846. *
  43847. * @param {RenderObject} renderObject - The render object.
  43848. * @return {string} The cache key.
  43849. */
  43850. getRenderCacheKey( /*renderObject*/ ) {
  43851. return '';
  43852. }
  43853. // textures
  43854. /**
  43855. * Creates a default texture for the given texture that can be used
  43856. * as a placeholder until the actual texture is ready for usage.
  43857. *
  43858. * @param {Texture} texture - The texture to create a default texture for.
  43859. */
  43860. createDefaultTexture( texture ) {
  43861. this.textureUtils.createDefaultTexture( texture );
  43862. }
  43863. /**
  43864. * Defines a texture on the GPU for the given texture object.
  43865. *
  43866. * @param {Texture} texture - The texture.
  43867. * @param {Object} [options={}] - Optional configuration parameter.
  43868. */
  43869. createTexture( texture, options ) {
  43870. this.textureUtils.createTexture( texture, options );
  43871. }
  43872. /**
  43873. * Uploads the updated texture data to the GPU.
  43874. *
  43875. * @param {Texture} texture - The texture.
  43876. * @param {Object} [options={}] - Optional configuration parameter.
  43877. */
  43878. updateTexture( texture, options ) {
  43879. this.textureUtils.updateTexture( texture, options );
  43880. }
  43881. /**
  43882. * Generates mipmaps for the given texture.
  43883. *
  43884. * @param {Texture} texture - The texture.
  43885. */
  43886. generateMipmaps( texture ) {
  43887. this.textureUtils.generateMipmaps( texture );
  43888. }
  43889. /**
  43890. * Destroys the GPU data for the given texture object.
  43891. *
  43892. * @param {Texture} texture - The texture.
  43893. */
  43894. destroyTexture( texture ) {
  43895. this.textureUtils.destroyTexture( texture );
  43896. }
  43897. /**
  43898. * Returns texture data as a typed array.
  43899. *
  43900. * @async
  43901. * @param {Texture} texture - The texture to copy.
  43902. * @param {number} x - The x coordinate of the copy origin.
  43903. * @param {number} y - The y coordinate of the copy origin.
  43904. * @param {number} width - The width of the copy.
  43905. * @param {number} height - The height of the copy.
  43906. * @param {number} faceIndex - The face index.
  43907. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43908. */
  43909. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43910. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  43911. }
  43912. /**
  43913. * This method does nothing since WebGL 2 has no concept of samplers.
  43914. *
  43915. * @param {Texture} texture - The texture to create the sampler for.
  43916. */
  43917. createSampler( /*texture*/ ) {
  43918. //console.warn( 'Abstract class.' );
  43919. }
  43920. /**
  43921. * This method does nothing since WebGL 2 has no concept of samplers.
  43922. *
  43923. * @param {Texture} texture - The texture to destroy the sampler for.
  43924. */
  43925. destroySampler( /*texture*/ ) {}
  43926. // node builder
  43927. /**
  43928. * Returns a node builder for the given render object.
  43929. *
  43930. * @param {RenderObject} object - The render object.
  43931. * @param {Renderer} renderer - The renderer.
  43932. * @return {GLSLNodeBuilder} The node builder.
  43933. */
  43934. createNodeBuilder( object, renderer ) {
  43935. return new GLSLNodeBuilder( object, renderer );
  43936. }
  43937. // program
  43938. /**
  43939. * Creates a shader program from the given programmable stage.
  43940. *
  43941. * @param {ProgrammableStage} program - The programmable stage.
  43942. */
  43943. createProgram( program ) {
  43944. const gl = this.gl;
  43945. const { stage, code } = program;
  43946. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  43947. gl.shaderSource( shader, code );
  43948. gl.compileShader( shader );
  43949. this.set( program, {
  43950. shaderGPU: shader
  43951. } );
  43952. }
  43953. /**
  43954. * Destroys the shader program of the given programmable stage.
  43955. *
  43956. * @param {ProgrammableStage} program - The programmable stage.
  43957. */
  43958. destroyProgram( program ) {
  43959. this.delete( program );
  43960. }
  43961. /**
  43962. * Creates a render pipeline for the given render object.
  43963. *
  43964. * @param {RenderObject} renderObject - The render object.
  43965. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  43966. */
  43967. createRenderPipeline( renderObject, promises ) {
  43968. const gl = this.gl;
  43969. const pipeline = renderObject.pipeline;
  43970. // Program
  43971. const { fragmentProgram, vertexProgram } = pipeline;
  43972. const programGPU = gl.createProgram();
  43973. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  43974. const vertexShader = this.get( vertexProgram ).shaderGPU;
  43975. gl.attachShader( programGPU, fragmentShader );
  43976. gl.attachShader( programGPU, vertexShader );
  43977. gl.linkProgram( programGPU );
  43978. this.set( pipeline, {
  43979. programGPU,
  43980. fragmentShader,
  43981. vertexShader
  43982. } );
  43983. if ( promises !== null && this.parallel ) {
  43984. const p = new Promise( ( resolve /*, reject*/ ) => {
  43985. const parallel = this.parallel;
  43986. const checkStatus = () => {
  43987. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  43988. this._completeCompile( renderObject, pipeline );
  43989. resolve();
  43990. } else {
  43991. requestAnimationFrame( checkStatus );
  43992. }
  43993. };
  43994. checkStatus();
  43995. } );
  43996. promises.push( p );
  43997. return;
  43998. }
  43999. this._completeCompile( renderObject, pipeline );
  44000. }
  44001. /**
  44002. * Formats the source code of error messages.
  44003. *
  44004. * @private
  44005. * @param {string} string - The code.
  44006. * @param {number} errorLine - The error line.
  44007. * @return {string} The formatted code.
  44008. */
  44009. _handleSource( string, errorLine ) {
  44010. const lines = string.split( '\n' );
  44011. const lines2 = [];
  44012. const from = Math.max( errorLine - 6, 0 );
  44013. const to = Math.min( errorLine + 6, lines.length );
  44014. for ( let i = from; i < to; i ++ ) {
  44015. const line = i + 1;
  44016. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  44017. }
  44018. return lines2.join( '\n' );
  44019. }
  44020. /**
  44021. * Gets the shader compilation errors from the info log.
  44022. *
  44023. * @private
  44024. * @param {WebGL2RenderingContext} gl - The rendering context.
  44025. * @param {WebGLShader} shader - The WebGL shader object.
  44026. * @param {string} type - The shader type.
  44027. * @return {string} The shader errors.
  44028. */
  44029. _getShaderErrors( gl, shader, type ) {
  44030. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  44031. const errors = gl.getShaderInfoLog( shader ).trim();
  44032. if ( status && errors === '' ) return '';
  44033. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  44034. if ( errorMatches ) {
  44035. const errorLine = parseInt( errorMatches[ 1 ] );
  44036. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  44037. } else {
  44038. return errors;
  44039. }
  44040. }
  44041. /**
  44042. * Logs shader compilation errors.
  44043. *
  44044. * @private
  44045. * @param {WebGLProgram} programGPU - The WebGL program.
  44046. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  44047. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  44048. */
  44049. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  44050. if ( this.renderer.debug.checkShaderErrors ) {
  44051. const gl = this.gl;
  44052. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  44053. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44054. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  44055. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  44056. } else {
  44057. // default error reporting
  44058. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  44059. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  44060. console.error(
  44061. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  44062. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  44063. 'Program Info Log: ' + programLog + '\n' +
  44064. vertexErrors + '\n' +
  44065. fragmentErrors
  44066. );
  44067. }
  44068. } else if ( programLog !== '' ) {
  44069. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  44070. }
  44071. }
  44072. }
  44073. /**
  44074. * Completes the shader program setup for the given render object.
  44075. *
  44076. * @private
  44077. * @param {RenderObject} renderObject - The render object.
  44078. * @param {RenderPipeline} pipeline - The render pipeline.
  44079. */
  44080. _completeCompile( renderObject, pipeline ) {
  44081. const { state, gl } = this;
  44082. const pipelineData = this.get( pipeline );
  44083. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  44084. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44085. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44086. }
  44087. state.useProgram( programGPU );
  44088. // Bindings
  44089. const bindings = renderObject.getBindings();
  44090. this._setupBindings( bindings, programGPU );
  44091. //
  44092. this.set( pipeline, {
  44093. programGPU
  44094. } );
  44095. }
  44096. /**
  44097. * Creates a compute pipeline for the given compute node.
  44098. *
  44099. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44100. * @param {Array<BindGroup>} bindings - The bindings.
  44101. */
  44102. createComputePipeline( computePipeline, bindings ) {
  44103. const { state, gl } = this;
  44104. // Program
  44105. const fragmentProgram = {
  44106. stage: 'fragment',
  44107. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  44108. };
  44109. this.createProgram( fragmentProgram );
  44110. const { computeProgram } = computePipeline;
  44111. const programGPU = gl.createProgram();
  44112. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44113. const vertexShader = this.get( computeProgram ).shaderGPU;
  44114. const transforms = computeProgram.transforms;
  44115. const transformVaryingNames = [];
  44116. const transformAttributeNodes = [];
  44117. for ( let i = 0; i < transforms.length; i ++ ) {
  44118. const transform = transforms[ i ];
  44119. transformVaryingNames.push( transform.varyingName );
  44120. transformAttributeNodes.push( transform.attributeNode );
  44121. }
  44122. gl.attachShader( programGPU, fragmentShader );
  44123. gl.attachShader( programGPU, vertexShader );
  44124. gl.transformFeedbackVaryings(
  44125. programGPU,
  44126. transformVaryingNames,
  44127. gl.SEPARATE_ATTRIBS
  44128. );
  44129. gl.linkProgram( programGPU );
  44130. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44131. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44132. }
  44133. state.useProgram( programGPU );
  44134. // Bindings
  44135. this._setupBindings( bindings, programGPU );
  44136. const attributeNodes = computeProgram.attributes;
  44137. const attributes = [];
  44138. const transformBuffers = [];
  44139. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  44140. const attribute = attributeNodes[ i ].node.attribute;
  44141. attributes.push( attribute );
  44142. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44143. }
  44144. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  44145. const attribute = transformAttributeNodes[ i ].attribute;
  44146. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44147. const attributeData = this.get( attribute );
  44148. transformBuffers.push( attributeData );
  44149. }
  44150. //
  44151. this.set( computePipeline, {
  44152. programGPU,
  44153. transformBuffers,
  44154. attributes
  44155. } );
  44156. }
  44157. /**
  44158. * Creates bindings from the given bind group definition.
  44159. *
  44160. * @param {BindGroup} bindGroup - The bind group.
  44161. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44162. * @param {number} cacheIndex - The cache index.
  44163. * @param {number} version - The version.
  44164. */
  44165. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  44166. if ( this._knownBindings.has( bindings ) === false ) {
  44167. this._knownBindings.add( bindings );
  44168. let uniformBuffers = 0;
  44169. let textures = 0;
  44170. for ( const bindGroup of bindings ) {
  44171. this.set( bindGroup, {
  44172. textures: textures,
  44173. uniformBuffers: uniformBuffers
  44174. } );
  44175. for ( const binding of bindGroup.bindings ) {
  44176. if ( binding.isUniformBuffer ) uniformBuffers ++;
  44177. if ( binding.isSampledTexture ) textures ++;
  44178. }
  44179. }
  44180. }
  44181. this.updateBindings( bindGroup, bindings );
  44182. }
  44183. /**
  44184. * Updates the given bind group definition.
  44185. *
  44186. * @param {BindGroup} bindGroup - The bind group.
  44187. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44188. * @param {number} cacheIndex - The cache index.
  44189. * @param {number} version - The version.
  44190. */
  44191. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  44192. const { gl } = this;
  44193. const bindGroupData = this.get( bindGroup );
  44194. let i = bindGroupData.uniformBuffers;
  44195. let t = bindGroupData.textures;
  44196. for ( const binding of bindGroup.bindings ) {
  44197. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44198. const data = binding.buffer;
  44199. const bufferGPU = gl.createBuffer();
  44200. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44201. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44202. this.set( binding, {
  44203. index: i ++,
  44204. bufferGPU
  44205. } );
  44206. } else if ( binding.isSampledTexture ) {
  44207. const { textureGPU, glTextureType } = this.get( binding.texture );
  44208. this.set( binding, {
  44209. index: t ++,
  44210. textureGPU,
  44211. glTextureType
  44212. } );
  44213. }
  44214. }
  44215. }
  44216. /**
  44217. * Updates a buffer binding.
  44218. *
  44219. * @param {Buffer} binding - The buffer binding to update.
  44220. */
  44221. updateBinding( binding ) {
  44222. const gl = this.gl;
  44223. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44224. const bindingData = this.get( binding );
  44225. const bufferGPU = bindingData.bufferGPU;
  44226. const data = binding.buffer;
  44227. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44228. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44229. }
  44230. }
  44231. // attributes
  44232. /**
  44233. * Creates the GPU buffer of an indexed shader attribute.
  44234. *
  44235. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  44236. */
  44237. createIndexAttribute( attribute ) {
  44238. const gl = this.gl;
  44239. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  44240. }
  44241. /**
  44242. * Creates the GPU buffer of a shader attribute.
  44243. *
  44244. * @param {BufferAttribute} attribute - The buffer attribute.
  44245. */
  44246. createAttribute( attribute ) {
  44247. if ( this.has( attribute ) ) return;
  44248. const gl = this.gl;
  44249. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44250. }
  44251. /**
  44252. * Creates the GPU buffer of a storage attribute.
  44253. *
  44254. * @param {BufferAttribute} attribute - The buffer attribute.
  44255. */
  44256. createStorageAttribute( attribute ) {
  44257. if ( this.has( attribute ) ) return;
  44258. const gl = this.gl;
  44259. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44260. }
  44261. /**
  44262. * Updates the GPU buffer of a shader attribute.
  44263. *
  44264. * @param {BufferAttribute} attribute - The buffer attribute to update.
  44265. */
  44266. updateAttribute( attribute ) {
  44267. this.attributeUtils.updateAttribute( attribute );
  44268. }
  44269. /**
  44270. * Destroys the GPU buffer of a shader attribute.
  44271. *
  44272. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  44273. */
  44274. destroyAttribute( attribute ) {
  44275. this.attributeUtils.destroyAttribute( attribute );
  44276. }
  44277. /**
  44278. * Checks if the given feature is supported by the backend.
  44279. *
  44280. * @param {string} name - The feature's name.
  44281. * @return {boolean} Whether the feature is supported or not.
  44282. */
  44283. hasFeature( name ) {
  44284. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  44285. const extensions = this.extensions;
  44286. for ( let i = 0; i < keysMatching.length; i ++ ) {
  44287. if ( extensions.has( keysMatching[ i ] ) ) return true;
  44288. }
  44289. return false;
  44290. }
  44291. /**
  44292. * Returns the maximum anisotropy texture filtering value.
  44293. *
  44294. * @return {number} The maximum anisotropy texture filtering value.
  44295. */
  44296. getMaxAnisotropy() {
  44297. return this.capabilities.getMaxAnisotropy();
  44298. }
  44299. /**
  44300. * Copies data of the given source texture to the given destination texture.
  44301. *
  44302. * @param {Texture} srcTexture - The source texture.
  44303. * @param {Texture} dstTexture - The destination texture.
  44304. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44305. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44306. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44307. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44308. */
  44309. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44310. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  44311. }
  44312. /**
  44313. * Copies the current bound framebuffer to the given texture.
  44314. *
  44315. * @param {Texture} texture - The destination texture.
  44316. * @param {RenderContext} renderContext - The render context.
  44317. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44318. */
  44319. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  44320. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  44321. }
  44322. /**
  44323. * Configures the active framebuffer from the given render context.
  44324. *
  44325. * @private
  44326. * @param {RenderContext} descriptor - The render context.
  44327. */
  44328. _setFramebuffer( descriptor ) {
  44329. const { gl, state } = this;
  44330. let currentFrameBuffer = null;
  44331. if ( descriptor.textures !== null ) {
  44332. const renderTarget = descriptor.renderTarget;
  44333. const renderTargetContextData = this.get( renderTarget );
  44334. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  44335. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  44336. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  44337. const isRenderTargetArray = renderTarget.depth > 1;
  44338. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  44339. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  44340. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  44341. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  44342. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44343. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  44344. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  44345. const cacheKey = getCacheKey( descriptor );
  44346. let fb;
  44347. if ( isCube ) {
  44348. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  44349. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  44350. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  44351. fb = this._xrFramebuffer;
  44352. } else {
  44353. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  44354. fb = renderTargetContextData.framebuffers[ cacheKey ];
  44355. }
  44356. if ( fb === undefined ) {
  44357. fb = gl.createFramebuffer();
  44358. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44359. const textures = descriptor.textures;
  44360. if ( isCube ) {
  44361. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  44362. const { textureGPU } = this.get( textures[ 0 ] );
  44363. const cubeFace = this.renderer._activeCubeFace;
  44364. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  44365. } else {
  44366. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  44367. for ( let i = 0; i < textures.length; i ++ ) {
  44368. const texture = textures[ i ];
  44369. const textureData = this.get( texture );
  44370. textureData.renderTarget = descriptor.renderTarget;
  44371. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44372. const attachment = gl.COLOR_ATTACHMENT0 + i;
  44373. if ( isRenderTarget3D || isRenderTargetArray ) {
  44374. const layer = this.renderer._activeCubeFace;
  44375. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  44376. } else {
  44377. if ( renderTarget.multiview ) {
  44378. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  44379. } else if ( hasExternalTextures && useMultisampledRTT ) {
  44380. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44381. } else {
  44382. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44383. }
  44384. }
  44385. }
  44386. state.drawBuffers( descriptor, fb );
  44387. }
  44388. if ( renderTarget.isXRRenderTarget && renderTarget.autoAllocateDepthBuffer === true ) {
  44389. const renderbuffer = gl.createRenderbuffer();
  44390. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  44391. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  44392. } else {
  44393. if ( descriptor.depthTexture !== null ) {
  44394. const textureData = this.get( descriptor.depthTexture );
  44395. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44396. textureData.renderTarget = descriptor.renderTarget;
  44397. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44398. if ( renderTarget.multiview ) {
  44399. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44400. } else if ( hasExternalTextures && useMultisampledRTT ) {
  44401. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44402. } else {
  44403. if ( descriptor.depthTexture.isArrayTexture ) {
  44404. const layer = this.renderer._activeCubeFace;
  44405. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  44406. } else {
  44407. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44408. }
  44409. }
  44410. }
  44411. }
  44412. } else {
  44413. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  44414. if ( isRenderCameraDepthArray ) {
  44415. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44416. const layer = this.renderer._activeCubeFace;
  44417. const depthData = this.get( descriptor.depthTexture );
  44418. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44419. gl.framebufferTextureLayer(
  44420. gl.FRAMEBUFFER,
  44421. depthStyle,
  44422. depthData.textureGPU,
  44423. 0,
  44424. layer
  44425. );
  44426. }
  44427. // rebind external XR textures
  44428. if ( ( isXRRenderTarget && hasExternalTextures ) || renderTarget.multiview ) {
  44429. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44430. // rebind color
  44431. const textureData = this.get( descriptor.textures[ 0 ] );
  44432. if ( renderTarget.multiview ) {
  44433. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  44434. } else if ( useMultisampledRTT ) {
  44435. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44436. } else {
  44437. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44438. }
  44439. // rebind depth
  44440. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44441. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  44442. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  44443. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44444. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  44445. } else {
  44446. const textureData = this.get( descriptor.depthTexture );
  44447. if ( renderTarget.multiview ) {
  44448. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44449. } else if ( useMultisampledRTT ) {
  44450. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44451. } else {
  44452. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44453. }
  44454. }
  44455. }
  44456. }
  44457. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  44458. if ( msaaFb === undefined ) {
  44459. const invalidationArray = [];
  44460. msaaFb = gl.createFramebuffer();
  44461. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  44462. const msaaRenderbuffers = [];
  44463. const textures = descriptor.textures;
  44464. for ( let i = 0; i < textures.length; i ++ ) {
  44465. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  44466. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44467. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  44468. if ( depthBuffer ) {
  44469. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44470. invalidationArray.push( depthStyle );
  44471. }
  44472. const texture = descriptor.textures[ i ];
  44473. const textureData = this.get( texture );
  44474. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  44475. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44476. }
  44477. renderTargetContextData.msaaFrameBuffer = msaaFb;
  44478. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  44479. if ( depthRenderbuffer === undefined ) {
  44480. depthRenderbuffer = gl.createRenderbuffer();
  44481. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  44482. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  44483. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44484. invalidationArray.push( depthStyle );
  44485. }
  44486. renderTargetContextData.invalidationArray = invalidationArray;
  44487. }
  44488. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44489. } else {
  44490. currentFrameBuffer = fb;
  44491. }
  44492. }
  44493. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  44494. }
  44495. /**
  44496. * Computes the VAO key for the given index and attributes.
  44497. *
  44498. * @private
  44499. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  44500. * @return {string} The VAO key.
  44501. */
  44502. _getVaoKey( attributes ) {
  44503. let key = '';
  44504. for ( let i = 0; i < attributes.length; i ++ ) {
  44505. const attributeData = this.get( attributes[ i ] );
  44506. key += ':' + attributeData.id;
  44507. }
  44508. return key;
  44509. }
  44510. /**
  44511. * Creates a VAO from the index and attributes.
  44512. *
  44513. * @private
  44514. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  44515. * @return {Object} The VAO data.
  44516. */
  44517. _createVao( attributes ) {
  44518. const { gl } = this;
  44519. const vaoGPU = gl.createVertexArray();
  44520. let key = '';
  44521. let staticVao = true;
  44522. gl.bindVertexArray( vaoGPU );
  44523. for ( let i = 0; i < attributes.length; i ++ ) {
  44524. const attribute = attributes[ i ];
  44525. const attributeData = this.get( attribute );
  44526. key += ':' + attributeData.id;
  44527. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  44528. gl.enableVertexAttribArray( i );
  44529. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  44530. let stride, offset;
  44531. if ( attribute.isInterleavedBufferAttribute === true ) {
  44532. stride = attribute.data.stride * attributeData.bytesPerElement;
  44533. offset = attribute.offset * attributeData.bytesPerElement;
  44534. } else {
  44535. stride = 0;
  44536. offset = 0;
  44537. }
  44538. if ( attributeData.isInteger ) {
  44539. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  44540. } else {
  44541. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  44542. }
  44543. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  44544. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  44545. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  44546. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  44547. }
  44548. }
  44549. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  44550. this.vaoCache[ key ] = vaoGPU;
  44551. return { vaoGPU, staticVao };
  44552. }
  44553. /**
  44554. * Creates a transform feedback from the given transform buffers.
  44555. *
  44556. * @private
  44557. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  44558. * @return {WebGLTransformFeedback} The transform feedback.
  44559. */
  44560. _getTransformFeedback( transformBuffers ) {
  44561. let key = '';
  44562. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44563. key += ':' + transformBuffers[ i ].id;
  44564. }
  44565. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  44566. if ( transformFeedbackGPU !== undefined ) {
  44567. return transformFeedbackGPU;
  44568. }
  44569. const { gl } = this;
  44570. transformFeedbackGPU = gl.createTransformFeedback();
  44571. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  44572. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44573. const attributeData = transformBuffers[ i ];
  44574. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  44575. }
  44576. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  44577. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  44578. return transformFeedbackGPU;
  44579. }
  44580. /**
  44581. * Setups the given bindings.
  44582. *
  44583. * @private
  44584. * @param {Array<BindGroup>} bindings - The bindings.
  44585. * @param {WebGLProgram} programGPU - The WebGL program.
  44586. */
  44587. _setupBindings( bindings, programGPU ) {
  44588. const gl = this.gl;
  44589. for ( const bindGroup of bindings ) {
  44590. for ( const binding of bindGroup.bindings ) {
  44591. const bindingData = this.get( binding );
  44592. const index = bindingData.index;
  44593. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44594. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  44595. gl.uniformBlockBinding( programGPU, location, index );
  44596. } else if ( binding.isSampledTexture ) {
  44597. const location = gl.getUniformLocation( programGPU, binding.name );
  44598. gl.uniform1i( location, index );
  44599. }
  44600. }
  44601. }
  44602. }
  44603. /**
  44604. * Binds the given uniforms.
  44605. *
  44606. * @private
  44607. * @param {Array<BindGroup>} bindings - The bindings.
  44608. */
  44609. _bindUniforms( bindings ) {
  44610. const { gl, state } = this;
  44611. for ( const bindGroup of bindings ) {
  44612. for ( const binding of bindGroup.bindings ) {
  44613. const bindingData = this.get( binding );
  44614. const index = bindingData.index;
  44615. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44616. // TODO USE bindBufferRange to group multiple uniform buffers
  44617. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  44618. } else if ( binding.isSampledTexture ) {
  44619. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  44620. }
  44621. }
  44622. }
  44623. }
  44624. /**
  44625. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  44626. * should be used when MSAA is enabled.
  44627. *
  44628. * @private
  44629. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  44630. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  44631. */
  44632. _useMultisampledExtension( renderTarget ) {
  44633. if ( renderTarget.multiview === true ) {
  44634. return true;
  44635. }
  44636. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget.autoAllocateDepthBuffer !== false;
  44637. }
  44638. /**
  44639. * Frees internal resources.
  44640. */
  44641. dispose() {
  44642. const extension = this.extensions.get( 'WEBGL_lose_context' );
  44643. if ( extension ) extension.loseContext();
  44644. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  44645. }
  44646. }
  44647. const GPUPrimitiveTopology = {
  44648. PointList: 'point-list',
  44649. LineList: 'line-list',
  44650. LineStrip: 'line-strip',
  44651. TriangleList: 'triangle-list',
  44652. TriangleStrip: 'triangle-strip',
  44653. };
  44654. const GPUCompareFunction = {
  44655. Never: 'never',
  44656. Less: 'less',
  44657. Equal: 'equal',
  44658. LessEqual: 'less-equal',
  44659. Greater: 'greater',
  44660. NotEqual: 'not-equal',
  44661. GreaterEqual: 'greater-equal',
  44662. Always: 'always'
  44663. };
  44664. const GPUStoreOp = {
  44665. Store: 'store'};
  44666. const GPULoadOp = {
  44667. Load: 'load',
  44668. Clear: 'clear'
  44669. };
  44670. const GPUFrontFace = {
  44671. CCW: 'ccw'};
  44672. const GPUCullMode = {
  44673. None: 'none',
  44674. Front: 'front',
  44675. Back: 'back'
  44676. };
  44677. const GPUIndexFormat = {
  44678. Uint16: 'uint16',
  44679. Uint32: 'uint32'
  44680. };
  44681. const GPUTextureFormat = {
  44682. // 8-bit formats
  44683. R8Unorm: 'r8unorm',
  44684. R8Snorm: 'r8snorm',
  44685. R8Uint: 'r8uint',
  44686. R8Sint: 'r8sint',
  44687. // 16-bit formats
  44688. R16Uint: 'r16uint',
  44689. R16Sint: 'r16sint',
  44690. R16Float: 'r16float',
  44691. RG8Unorm: 'rg8unorm',
  44692. RG8Snorm: 'rg8snorm',
  44693. RG8Uint: 'rg8uint',
  44694. RG8Sint: 'rg8sint',
  44695. // 32-bit formats
  44696. R32Uint: 'r32uint',
  44697. R32Sint: 'r32sint',
  44698. R32Float: 'r32float',
  44699. RG16Uint: 'rg16uint',
  44700. RG16Sint: 'rg16sint',
  44701. RG16Float: 'rg16float',
  44702. RGBA8Unorm: 'rgba8unorm',
  44703. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  44704. RGBA8Snorm: 'rgba8snorm',
  44705. RGBA8Uint: 'rgba8uint',
  44706. RGBA8Sint: 'rgba8sint',
  44707. BGRA8Unorm: 'bgra8unorm',
  44708. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  44709. // Packed 32-bit formats
  44710. RGB9E5UFloat: 'rgb9e5ufloat',
  44711. RGB10A2Unorm: 'rgb10a2unorm',
  44712. RG11B10UFloat: 'rgb10a2unorm',
  44713. // 64-bit formats
  44714. RG32Uint: 'rg32uint',
  44715. RG32Sint: 'rg32sint',
  44716. RG32Float: 'rg32float',
  44717. RGBA16Uint: 'rgba16uint',
  44718. RGBA16Sint: 'rgba16sint',
  44719. RGBA16Float: 'rgba16float',
  44720. // 128-bit formats
  44721. RGBA32Uint: 'rgba32uint',
  44722. RGBA32Sint: 'rgba32sint',
  44723. RGBA32Float: 'rgba32float',
  44724. Depth16Unorm: 'depth16unorm',
  44725. Depth24Plus: 'depth24plus',
  44726. Depth24PlusStencil8: 'depth24plus-stencil8',
  44727. Depth32Float: 'depth32float',
  44728. // 'depth32float-stencil8' extension
  44729. Depth32FloatStencil8: 'depth32float-stencil8',
  44730. // BC compressed formats usable if 'texture-compression-bc' is both
  44731. // supported by the device/user agent and enabled in requestDevice.
  44732. BC1RGBAUnorm: 'bc1-rgba-unorm',
  44733. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  44734. BC2RGBAUnorm: 'bc2-rgba-unorm',
  44735. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  44736. BC3RGBAUnorm: 'bc3-rgba-unorm',
  44737. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  44738. BC4RUnorm: 'bc4-r-unorm',
  44739. BC4RSnorm: 'bc4-r-snorm',
  44740. BC5RGUnorm: 'bc5-rg-unorm',
  44741. BC5RGSnorm: 'bc5-rg-snorm',
  44742. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  44743. BC6HRGBFloat: 'bc6h-rgb-float',
  44744. BC7RGBAUnorm: 'bc7-rgba-unorm',
  44745. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  44746. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  44747. // supported by the device/user agent and enabled in requestDevice.
  44748. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  44749. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  44750. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  44751. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  44752. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  44753. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  44754. EACR11Unorm: 'eac-r11unorm',
  44755. EACR11Snorm: 'eac-r11snorm',
  44756. EACRG11Unorm: 'eac-rg11unorm',
  44757. EACRG11Snorm: 'eac-rg11snorm',
  44758. // ASTC compressed formats usable if 'texture-compression-astc' is both
  44759. // supported by the device/user agent and enabled in requestDevice.
  44760. ASTC4x4Unorm: 'astc-4x4-unorm',
  44761. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  44762. ASTC5x4Unorm: 'astc-5x4-unorm',
  44763. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  44764. ASTC5x5Unorm: 'astc-5x5-unorm',
  44765. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  44766. ASTC6x5Unorm: 'astc-6x5-unorm',
  44767. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  44768. ASTC6x6Unorm: 'astc-6x6-unorm',
  44769. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  44770. ASTC8x5Unorm: 'astc-8x5-unorm',
  44771. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  44772. ASTC8x6Unorm: 'astc-8x6-unorm',
  44773. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  44774. ASTC8x8Unorm: 'astc-8x8-unorm',
  44775. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  44776. ASTC10x5Unorm: 'astc-10x5-unorm',
  44777. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  44778. ASTC10x6Unorm: 'astc-10x6-unorm',
  44779. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  44780. ASTC10x8Unorm: 'astc-10x8-unorm',
  44781. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  44782. ASTC10x10Unorm: 'astc-10x10-unorm',
  44783. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  44784. ASTC12x10Unorm: 'astc-12x10-unorm',
  44785. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  44786. ASTC12x12Unorm: 'astc-12x12-unorm',
  44787. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  44788. };
  44789. const GPUAddressMode = {
  44790. ClampToEdge: 'clamp-to-edge',
  44791. Repeat: 'repeat',
  44792. MirrorRepeat: 'mirror-repeat'
  44793. };
  44794. const GPUFilterMode = {
  44795. Linear: 'linear',
  44796. Nearest: 'nearest'
  44797. };
  44798. const GPUBlendFactor = {
  44799. Zero: 'zero',
  44800. One: 'one',
  44801. Src: 'src',
  44802. OneMinusSrc: 'one-minus-src',
  44803. SrcAlpha: 'src-alpha',
  44804. OneMinusSrcAlpha: 'one-minus-src-alpha',
  44805. Dst: 'dst',
  44806. OneMinusDstColor: 'one-minus-dst',
  44807. DstAlpha: 'dst-alpha',
  44808. OneMinusDstAlpha: 'one-minus-dst-alpha',
  44809. SrcAlphaSaturated: 'src-alpha-saturated',
  44810. Constant: 'constant',
  44811. OneMinusConstant: 'one-minus-constant'
  44812. };
  44813. const GPUBlendOperation = {
  44814. Add: 'add',
  44815. Subtract: 'subtract',
  44816. ReverseSubtract: 'reverse-subtract',
  44817. Min: 'min',
  44818. Max: 'max'
  44819. };
  44820. const GPUColorWriteFlags = {
  44821. None: 0,
  44822. All: 0xF
  44823. };
  44824. const GPUStencilOperation = {
  44825. Keep: 'keep',
  44826. Zero: 'zero',
  44827. Replace: 'replace',
  44828. Invert: 'invert',
  44829. IncrementClamp: 'increment-clamp',
  44830. DecrementClamp: 'decrement-clamp',
  44831. IncrementWrap: 'increment-wrap',
  44832. DecrementWrap: 'decrement-wrap'
  44833. };
  44834. const GPUBufferBindingType = {
  44835. Storage: 'storage',
  44836. ReadOnlyStorage: 'read-only-storage'
  44837. };
  44838. const GPUStorageTextureAccess = {
  44839. WriteOnly: 'write-only',
  44840. ReadOnly: 'read-only',
  44841. ReadWrite: 'read-write',
  44842. };
  44843. const GPUSamplerBindingType = {
  44844. NonFiltering: 'non-filtering',
  44845. Comparison: 'comparison'
  44846. };
  44847. const GPUTextureSampleType = {
  44848. Float: 'float',
  44849. UnfilterableFloat: 'unfilterable-float',
  44850. Depth: 'depth',
  44851. SInt: 'sint',
  44852. UInt: 'uint'
  44853. };
  44854. const GPUTextureDimension = {
  44855. TwoD: '2d',
  44856. ThreeD: '3d'
  44857. };
  44858. const GPUTextureViewDimension = {
  44859. TwoD: '2d',
  44860. TwoDArray: '2d-array',
  44861. Cube: 'cube',
  44862. ThreeD: '3d'
  44863. };
  44864. const GPUTextureAspect = {
  44865. All: 'all'};
  44866. const GPUInputStepMode = {
  44867. Vertex: 'vertex',
  44868. Instance: 'instance'
  44869. };
  44870. const GPUFeatureName = {
  44871. DepthClipControl: 'depth-clip-control',
  44872. Depth32FloatStencil8: 'depth32float-stencil8',
  44873. TextureCompressionBC: 'texture-compression-bc',
  44874. TextureCompressionETC2: 'texture-compression-etc2',
  44875. TextureCompressionASTC: 'texture-compression-astc',
  44876. TimestampQuery: 'timestamp-query',
  44877. IndirectFirstInstance: 'indirect-first-instance',
  44878. ShaderF16: 'shader-f16',
  44879. RG11B10UFloat: 'rg11b10ufloat-renderable',
  44880. BGRA8UNormStorage: 'bgra8unorm-storage',
  44881. Float32Filterable: 'float32-filterable',
  44882. ClipDistances: 'clip-distances',
  44883. DualSourceBlending: 'dual-source-blending',
  44884. Subgroups: 'subgroups'
  44885. };
  44886. /**
  44887. * Represents a sampler binding type.
  44888. *
  44889. * @private
  44890. * @augments Binding
  44891. */
  44892. class Sampler extends Binding {
  44893. /**
  44894. * Constructs a new sampler.
  44895. *
  44896. * @param {string} name - The samplers's name.
  44897. * @param {?Texture} texture - The texture this binding is referring to.
  44898. */
  44899. constructor( name, texture ) {
  44900. super( name );
  44901. /**
  44902. * The texture the sampler is referring to.
  44903. *
  44904. * @type {?Texture}
  44905. */
  44906. this.texture = texture;
  44907. /**
  44908. * The binding's version.
  44909. *
  44910. * @type {number}
  44911. */
  44912. this.version = texture ? texture.version : 0;
  44913. /**
  44914. * This flag can be used for type testing.
  44915. *
  44916. * @type {boolean}
  44917. * @readonly
  44918. * @default true
  44919. */
  44920. this.isSampler = true;
  44921. }
  44922. }
  44923. /**
  44924. * A special form of sampler binding type.
  44925. * It's texture value is managed by a node object.
  44926. *
  44927. * @private
  44928. * @augments Sampler
  44929. */
  44930. class NodeSampler extends Sampler {
  44931. /**
  44932. * Constructs a new node-based sampler.
  44933. *
  44934. * @param {string} name - The samplers's name.
  44935. * @param {TextureNode} textureNode - The texture node.
  44936. * @param {UniformGroupNode} groupNode - The uniform group node.
  44937. */
  44938. constructor( name, textureNode, groupNode ) {
  44939. super( name, textureNode ? textureNode.value : null );
  44940. /**
  44941. * The texture node.
  44942. *
  44943. * @type {TextureNode}
  44944. */
  44945. this.textureNode = textureNode;
  44946. /**
  44947. * The uniform group node.
  44948. *
  44949. * @type {UniformGroupNode}
  44950. */
  44951. this.groupNode = groupNode;
  44952. }
  44953. /**
  44954. * Updates the texture value of this sampler.
  44955. */
  44956. update() {
  44957. this.texture = this.textureNode.value;
  44958. }
  44959. }
  44960. /**
  44961. * Represents a storage buffer binding type.
  44962. *
  44963. * @private
  44964. * @augments Buffer
  44965. */
  44966. class StorageBuffer extends Buffer {
  44967. /**
  44968. * Constructs a new uniform buffer.
  44969. *
  44970. * @param {string} name - The buffer's name.
  44971. * @param {BufferAttribute} attribute - The buffer attribute.
  44972. */
  44973. constructor( name, attribute ) {
  44974. super( name, attribute ? attribute.array : null );
  44975. /**
  44976. * This flag can be used for type testing.
  44977. *
  44978. * @type {BufferAttribute}
  44979. */
  44980. this.attribute = attribute;
  44981. /**
  44982. * This flag can be used for type testing.
  44983. *
  44984. * @type {boolean}
  44985. * @readonly
  44986. * @default true
  44987. */
  44988. this.isStorageBuffer = true;
  44989. }
  44990. }
  44991. let _id = 0;
  44992. /**
  44993. * A special form of storage buffer binding type.
  44994. * It's buffer value is managed by a node object.
  44995. *
  44996. * @private
  44997. * @augments StorageBuffer
  44998. */
  44999. class NodeStorageBuffer extends StorageBuffer {
  45000. /**
  45001. * Constructs a new node-based storage buffer.
  45002. *
  45003. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  45004. * @param {UniformGroupNode} groupNode - The uniform group node.
  45005. */
  45006. constructor( nodeUniform, groupNode ) {
  45007. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  45008. /**
  45009. * The node uniform.
  45010. *
  45011. * @type {StorageBufferNode}
  45012. */
  45013. this.nodeUniform = nodeUniform;
  45014. /**
  45015. * The access type.
  45016. *
  45017. * @type {string}
  45018. */
  45019. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  45020. /**
  45021. * The uniform group node.
  45022. *
  45023. * @type {UniformGroupNode}
  45024. */
  45025. this.groupNode = groupNode;
  45026. }
  45027. /**
  45028. * The storage buffer.
  45029. *
  45030. * @type {BufferAttribute}
  45031. */
  45032. get buffer() {
  45033. return this.nodeUniform.value;
  45034. }
  45035. }
  45036. /**
  45037. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  45038. *
  45039. * @private
  45040. */
  45041. class WebGPUTexturePassUtils extends DataMap {
  45042. /**
  45043. * Constructs a new utility object.
  45044. *
  45045. * @param {GPUDevice} device - The WebGPU device.
  45046. */
  45047. constructor( device ) {
  45048. super();
  45049. /**
  45050. * The WebGPU device.
  45051. *
  45052. * @type {GPUDevice}
  45053. */
  45054. this.device = device;
  45055. const mipmapVertexSource = `
  45056. struct VarysStruct {
  45057. @builtin( position ) Position: vec4<f32>,
  45058. @location( 0 ) vTex : vec2<f32>
  45059. };
  45060. @vertex
  45061. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  45062. var Varys : VarysStruct;
  45063. var pos = array< vec2<f32>, 4 >(
  45064. vec2<f32>( -1.0, 1.0 ),
  45065. vec2<f32>( 1.0, 1.0 ),
  45066. vec2<f32>( -1.0, -1.0 ),
  45067. vec2<f32>( 1.0, -1.0 )
  45068. );
  45069. var tex = array< vec2<f32>, 4 >(
  45070. vec2<f32>( 0.0, 0.0 ),
  45071. vec2<f32>( 1.0, 0.0 ),
  45072. vec2<f32>( 0.0, 1.0 ),
  45073. vec2<f32>( 1.0, 1.0 )
  45074. );
  45075. Varys.vTex = tex[ vertexIndex ];
  45076. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  45077. return Varys;
  45078. }
  45079. `;
  45080. const mipmapFragmentSource = `
  45081. @group( 0 ) @binding( 0 )
  45082. var imgSampler : sampler;
  45083. @group( 0 ) @binding( 1 )
  45084. var img : texture_2d<f32>;
  45085. @fragment
  45086. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45087. return textureSample( img, imgSampler, vTex );
  45088. }
  45089. `;
  45090. const flipYFragmentSource = `
  45091. @group( 0 ) @binding( 0 )
  45092. var imgSampler : sampler;
  45093. @group( 0 ) @binding( 1 )
  45094. var img : texture_2d<f32>;
  45095. @fragment
  45096. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45097. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  45098. }
  45099. `;
  45100. /**
  45101. * The mipmap GPU sampler.
  45102. *
  45103. * @type {GPUSampler}
  45104. */
  45105. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  45106. /**
  45107. * The flipY GPU sampler.
  45108. *
  45109. * @type {GPUSampler}
  45110. */
  45111. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  45112. /**
  45113. * A cache for GPU render pipelines used for copy/transfer passes.
  45114. * Every texture format requires a unique pipeline.
  45115. *
  45116. * @type {Object<string,GPURenderPipeline>}
  45117. */
  45118. this.transferPipelines = {};
  45119. /**
  45120. * A cache for GPU render pipelines used for flipY passes.
  45121. * Every texture format requires a unique pipeline.
  45122. *
  45123. * @type {Object<string,GPURenderPipeline>}
  45124. */
  45125. this.flipYPipelines = {};
  45126. /**
  45127. * The mipmap vertex shader module.
  45128. *
  45129. * @type {GPUShaderModule}
  45130. */
  45131. this.mipmapVertexShaderModule = device.createShaderModule( {
  45132. label: 'mipmapVertex',
  45133. code: mipmapVertexSource
  45134. } );
  45135. /**
  45136. * The mipmap fragment shader module.
  45137. *
  45138. * @type {GPUShaderModule}
  45139. */
  45140. this.mipmapFragmentShaderModule = device.createShaderModule( {
  45141. label: 'mipmapFragment',
  45142. code: mipmapFragmentSource
  45143. } );
  45144. /**
  45145. * The flipY fragment shader module.
  45146. *
  45147. * @type {GPUShaderModule}
  45148. */
  45149. this.flipYFragmentShaderModule = device.createShaderModule( {
  45150. label: 'flipYFragment',
  45151. code: flipYFragmentSource
  45152. } );
  45153. }
  45154. /**
  45155. * Returns a render pipeline for the internal copy render pass. The pass
  45156. * requires a unique render pipeline for each texture format.
  45157. *
  45158. * @param {string} format - The GPU texture format
  45159. * @return {GPURenderPipeline} The GPU render pipeline.
  45160. */
  45161. getTransferPipeline( format ) {
  45162. let pipeline = this.transferPipelines[ format ];
  45163. if ( pipeline === undefined ) {
  45164. pipeline = this.device.createRenderPipeline( {
  45165. label: `mipmap-${ format }`,
  45166. vertex: {
  45167. module: this.mipmapVertexShaderModule,
  45168. entryPoint: 'main'
  45169. },
  45170. fragment: {
  45171. module: this.mipmapFragmentShaderModule,
  45172. entryPoint: 'main',
  45173. targets: [ { format } ]
  45174. },
  45175. primitive: {
  45176. topology: GPUPrimitiveTopology.TriangleStrip,
  45177. stripIndexFormat: GPUIndexFormat.Uint32
  45178. },
  45179. layout: 'auto'
  45180. } );
  45181. this.transferPipelines[ format ] = pipeline;
  45182. }
  45183. return pipeline;
  45184. }
  45185. /**
  45186. * Returns a render pipeline for the flipY render pass. The pass
  45187. * requires a unique render pipeline for each texture format.
  45188. *
  45189. * @param {string} format - The GPU texture format
  45190. * @return {GPURenderPipeline} The GPU render pipeline.
  45191. */
  45192. getFlipYPipeline( format ) {
  45193. let pipeline = this.flipYPipelines[ format ];
  45194. if ( pipeline === undefined ) {
  45195. pipeline = this.device.createRenderPipeline( {
  45196. label: `flipY-${ format }`,
  45197. vertex: {
  45198. module: this.mipmapVertexShaderModule,
  45199. entryPoint: 'main'
  45200. },
  45201. fragment: {
  45202. module: this.flipYFragmentShaderModule,
  45203. entryPoint: 'main',
  45204. targets: [ { format } ]
  45205. },
  45206. primitive: {
  45207. topology: GPUPrimitiveTopology.TriangleStrip,
  45208. stripIndexFormat: GPUIndexFormat.Uint32
  45209. },
  45210. layout: 'auto'
  45211. } );
  45212. this.flipYPipelines[ format ] = pipeline;
  45213. }
  45214. return pipeline;
  45215. }
  45216. /**
  45217. * Flip the contents of the given GPU texture along its vertical axis.
  45218. *
  45219. * @param {GPUTexture} textureGPU - The GPU texture object.
  45220. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45221. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45222. */
  45223. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45224. const format = textureGPUDescriptor.format;
  45225. const { width, height } = textureGPUDescriptor.size;
  45226. const transferPipeline = this.getTransferPipeline( format );
  45227. const flipYPipeline = this.getFlipYPipeline( format );
  45228. const tempTexture = this.device.createTexture( {
  45229. size: { width, height, depthOrArrayLayers: 1 },
  45230. format,
  45231. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  45232. } );
  45233. const srcView = textureGPU.createView( {
  45234. baseMipLevel: 0,
  45235. mipLevelCount: 1,
  45236. dimension: GPUTextureViewDimension.TwoD,
  45237. baseArrayLayer
  45238. } );
  45239. const dstView = tempTexture.createView( {
  45240. baseMipLevel: 0,
  45241. mipLevelCount: 1,
  45242. dimension: GPUTextureViewDimension.TwoD,
  45243. baseArrayLayer: 0
  45244. } );
  45245. const commandEncoder = this.device.createCommandEncoder( {} );
  45246. const pass = ( pipeline, sourceView, destinationView ) => {
  45247. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45248. const bindGroup = this.device.createBindGroup( {
  45249. layout: bindGroupLayout,
  45250. entries: [ {
  45251. binding: 0,
  45252. resource: this.flipYSampler
  45253. }, {
  45254. binding: 1,
  45255. resource: sourceView
  45256. } ]
  45257. } );
  45258. const passEncoder = commandEncoder.beginRenderPass( {
  45259. colorAttachments: [ {
  45260. view: destinationView,
  45261. loadOp: GPULoadOp.Clear,
  45262. storeOp: GPUStoreOp.Store,
  45263. clearValue: [ 0, 0, 0, 0 ]
  45264. } ]
  45265. } );
  45266. passEncoder.setPipeline( pipeline );
  45267. passEncoder.setBindGroup( 0, bindGroup );
  45268. passEncoder.draw( 4, 1, 0, 0 );
  45269. passEncoder.end();
  45270. };
  45271. pass( transferPipeline, srcView, dstView );
  45272. pass( flipYPipeline, dstView, srcView );
  45273. this.device.queue.submit( [ commandEncoder.finish() ] );
  45274. tempTexture.destroy();
  45275. }
  45276. /**
  45277. * Generates mipmaps for the given GPU texture.
  45278. *
  45279. * @param {GPUTexture} textureGPU - The GPU texture object.
  45280. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45281. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45282. */
  45283. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45284. const textureData = this.get( textureGPU );
  45285. if ( textureData.useCount === undefined ) {
  45286. textureData.useCount = 0;
  45287. textureData.layers = [];
  45288. }
  45289. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  45290. const commandEncoder = this.device.createCommandEncoder( {} );
  45291. this._mipmapRunBundles( commandEncoder, passes );
  45292. this.device.queue.submit( [ commandEncoder.finish() ] );
  45293. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  45294. textureData.useCount ++;
  45295. }
  45296. /**
  45297. * Since multiple copy render passes are required to generate mipmaps, the passes
  45298. * are managed as render bundles to improve performance.
  45299. *
  45300. * @param {GPUTexture} textureGPU - The GPU texture object.
  45301. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45302. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  45303. * @return {Array<Object>} An array of render bundles.
  45304. */
  45305. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  45306. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  45307. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45308. let srcView = textureGPU.createView( {
  45309. baseMipLevel: 0,
  45310. mipLevelCount: 1,
  45311. dimension: GPUTextureViewDimension.TwoD,
  45312. baseArrayLayer
  45313. } );
  45314. const passes = [];
  45315. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  45316. const bindGroup = this.device.createBindGroup( {
  45317. layout: bindGroupLayout,
  45318. entries: [ {
  45319. binding: 0,
  45320. resource: this.mipmapSampler
  45321. }, {
  45322. binding: 1,
  45323. resource: srcView
  45324. } ]
  45325. } );
  45326. const dstView = textureGPU.createView( {
  45327. baseMipLevel: i,
  45328. mipLevelCount: 1,
  45329. dimension: GPUTextureViewDimension.TwoD,
  45330. baseArrayLayer
  45331. } );
  45332. const passDescriptor = {
  45333. colorAttachments: [ {
  45334. view: dstView,
  45335. loadOp: GPULoadOp.Clear,
  45336. storeOp: GPUStoreOp.Store,
  45337. clearValue: [ 0, 0, 0, 0 ]
  45338. } ]
  45339. };
  45340. const passEncoder = this.device.createRenderBundleEncoder( {
  45341. colorFormats: [ textureGPUDescriptor.format ]
  45342. } );
  45343. passEncoder.setPipeline( pipeline );
  45344. passEncoder.setBindGroup( 0, bindGroup );
  45345. passEncoder.draw( 4, 1, 0, 0 );
  45346. passes.push( {
  45347. renderBundles: [ passEncoder.finish() ],
  45348. passDescriptor
  45349. } );
  45350. srcView = dstView;
  45351. }
  45352. return passes;
  45353. }
  45354. /**
  45355. * Executes the render bundles.
  45356. *
  45357. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  45358. * @param {Array<Object>} passes - An array of render bundles.
  45359. */
  45360. _mipmapRunBundles( commandEncoder, passes ) {
  45361. const levels = passes.length;
  45362. for ( let i = 0; i < levels; i ++ ) {
  45363. const pass = passes[ i ];
  45364. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  45365. passEncoder.executeBundles( pass.renderBundles );
  45366. passEncoder.end();
  45367. }
  45368. }
  45369. }
  45370. const _compareToWebGPU = {
  45371. [ NeverCompare ]: 'never',
  45372. [ LessCompare ]: 'less',
  45373. [ EqualCompare ]: 'equal',
  45374. [ LessEqualCompare ]: 'less-equal',
  45375. [ GreaterCompare ]: 'greater',
  45376. [ GreaterEqualCompare ]: 'greater-equal',
  45377. [ AlwaysCompare ]: 'always',
  45378. [ NotEqualCompare ]: 'not-equal'
  45379. };
  45380. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  45381. /**
  45382. * A WebGPU backend utility module for managing textures.
  45383. *
  45384. * @private
  45385. */
  45386. class WebGPUTextureUtils {
  45387. /**
  45388. * Constructs a new utility object.
  45389. *
  45390. * @param {WebGPUBackend} backend - The WebGPU backend.
  45391. */
  45392. constructor( backend ) {
  45393. /**
  45394. * A reference to the WebGPU backend.
  45395. *
  45396. * @type {WebGPUBackend}
  45397. */
  45398. this.backend = backend;
  45399. /**
  45400. * A reference to the pass utils.
  45401. *
  45402. * @type {?WebGPUTexturePassUtils}
  45403. * @default null
  45404. */
  45405. this._passUtils = null;
  45406. /**
  45407. * A dictionary for managing default textures. The key
  45408. * is the texture format, the value the texture object.
  45409. *
  45410. * @type {Object<string,Texture>}
  45411. */
  45412. this.defaultTexture = {};
  45413. /**
  45414. * A dictionary for managing default cube textures. The key
  45415. * is the texture format, the value the texture object.
  45416. *
  45417. * @type {Object<string,CubeTexture>}
  45418. */
  45419. this.defaultCubeTexture = {};
  45420. /**
  45421. * A default video frame.
  45422. *
  45423. * @type {?VideoFrame}
  45424. * @default null
  45425. */
  45426. this.defaultVideoFrame = null;
  45427. /**
  45428. * Represents the color attachment of the default framebuffer.
  45429. *
  45430. * @type {?GPUTexture}
  45431. * @default null
  45432. */
  45433. this.colorBuffer = null;
  45434. /**
  45435. * Represents the depth attachment of the default framebuffer.
  45436. *
  45437. * @type {DepthTexture}
  45438. */
  45439. this.depthTexture = new DepthTexture();
  45440. this.depthTexture.name = 'depthBuffer';
  45441. }
  45442. /**
  45443. * Creates a GPU sampler for the given texture.
  45444. *
  45445. * @param {Texture} texture - The texture to create the sampler for.
  45446. */
  45447. createSampler( texture ) {
  45448. const backend = this.backend;
  45449. const device = backend.device;
  45450. const textureGPU = backend.get( texture );
  45451. const samplerDescriptorGPU = {
  45452. addressModeU: this._convertAddressMode( texture.wrapS ),
  45453. addressModeV: this._convertAddressMode( texture.wrapT ),
  45454. addressModeW: this._convertAddressMode( texture.wrapR ),
  45455. magFilter: this._convertFilterMode( texture.magFilter ),
  45456. minFilter: this._convertFilterMode( texture.minFilter ),
  45457. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  45458. maxAnisotropy: 1
  45459. };
  45460. // anisotropy can only be used when all filter modes are set to linear.
  45461. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  45462. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  45463. }
  45464. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  45465. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  45466. }
  45467. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  45468. }
  45469. /**
  45470. * Creates a default texture for the given texture that can be used
  45471. * as a placeholder until the actual texture is ready for usage.
  45472. *
  45473. * @param {Texture} texture - The texture to create a default texture for.
  45474. */
  45475. createDefaultTexture( texture ) {
  45476. let textureGPU;
  45477. const format = getFormat( texture );
  45478. if ( texture.isCubeTexture ) {
  45479. textureGPU = this._getDefaultCubeTextureGPU( format );
  45480. } else if ( texture.isVideoTexture ) {
  45481. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  45482. } else {
  45483. textureGPU = this._getDefaultTextureGPU( format );
  45484. }
  45485. this.backend.get( texture ).texture = textureGPU;
  45486. }
  45487. /**
  45488. * Defines a texture on the GPU for the given texture object.
  45489. *
  45490. * @param {Texture} texture - The texture.
  45491. * @param {Object} [options={}] - Optional configuration parameter.
  45492. */
  45493. createTexture( texture, options = {} ) {
  45494. const backend = this.backend;
  45495. const textureData = backend.get( texture );
  45496. if ( textureData.initialized ) {
  45497. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  45498. }
  45499. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  45500. if ( options.levels === undefined ) options.levels = 1;
  45501. if ( options.depth === undefined ) options.depth = 1;
  45502. const { width, height, depth, levels } = options;
  45503. if ( texture.isFramebufferTexture ) {
  45504. if ( options.renderTarget ) {
  45505. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  45506. } else {
  45507. options.format = this.backend.utils.getPreferredCanvasFormat();
  45508. }
  45509. }
  45510. const dimension = this._getDimension( texture );
  45511. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  45512. textureData.format = format;
  45513. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  45514. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  45515. if ( texture.isStorageTexture === true ) {
  45516. usage |= GPUTextureUsage.STORAGE_BINDING;
  45517. }
  45518. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  45519. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  45520. }
  45521. const textureDescriptorGPU = {
  45522. label: texture.name,
  45523. size: {
  45524. width: width,
  45525. height: height,
  45526. depthOrArrayLayers: depth,
  45527. },
  45528. mipLevelCount: levels,
  45529. sampleCount: primarySamples,
  45530. dimension: dimension,
  45531. format: format,
  45532. usage: usage
  45533. };
  45534. // texture creation
  45535. if ( texture.isVideoTexture ) {
  45536. const video = texture.source.data;
  45537. const videoFrame = new VideoFrame( video );
  45538. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  45539. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  45540. videoFrame.close();
  45541. textureData.externalTexture = video;
  45542. } else {
  45543. if ( format === undefined ) {
  45544. console.warn( 'WebGPURenderer: Texture format not supported.' );
  45545. this.createDefaultTexture( texture );
  45546. return;
  45547. }
  45548. if ( texture.isCubeTexture ) {
  45549. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  45550. }
  45551. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  45552. }
  45553. if ( isMSAA ) {
  45554. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  45555. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  45556. msaaTextureDescriptorGPU.sampleCount = samples;
  45557. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  45558. }
  45559. textureData.initialized = true;
  45560. textureData.textureDescriptorGPU = textureDescriptorGPU;
  45561. }
  45562. /**
  45563. * Destroys the GPU data for the given texture object.
  45564. *
  45565. * @param {Texture} texture - The texture.
  45566. */
  45567. destroyTexture( texture ) {
  45568. const backend = this.backend;
  45569. const textureData = backend.get( texture );
  45570. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  45571. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  45572. backend.delete( texture );
  45573. }
  45574. /**
  45575. * Destroys the GPU sampler for the given texture.
  45576. *
  45577. * @param {Texture} texture - The texture to destroy the sampler for.
  45578. */
  45579. destroySampler( texture ) {
  45580. const backend = this.backend;
  45581. const textureData = backend.get( texture );
  45582. delete textureData.sampler;
  45583. }
  45584. /**
  45585. * Generates mipmaps for the given texture.
  45586. *
  45587. * @param {Texture} texture - The texture.
  45588. */
  45589. generateMipmaps( texture ) {
  45590. const textureData = this.backend.get( texture );
  45591. if ( texture.isCubeTexture ) {
  45592. for ( let i = 0; i < 6; i ++ ) {
  45593. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  45594. }
  45595. } else {
  45596. const depth = texture.image.depth || 1;
  45597. for ( let i = 0; i < depth; i ++ ) {
  45598. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  45599. }
  45600. }
  45601. }
  45602. /**
  45603. * Returns the color buffer representing the color
  45604. * attachment of the default framebuffer.
  45605. *
  45606. * @return {GPUTexture} The color buffer.
  45607. */
  45608. getColorBuffer() {
  45609. if ( this.colorBuffer ) this.colorBuffer.destroy();
  45610. const backend = this.backend;
  45611. const { width, height } = backend.getDrawingBufferSize();
  45612. this.colorBuffer = backend.device.createTexture( {
  45613. label: 'colorBuffer',
  45614. size: {
  45615. width: width,
  45616. height: height,
  45617. depthOrArrayLayers: 1
  45618. },
  45619. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  45620. format: backend.utils.getPreferredCanvasFormat(),
  45621. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  45622. } );
  45623. return this.colorBuffer;
  45624. }
  45625. /**
  45626. * Returns the depth buffer representing the depth
  45627. * attachment of the default framebuffer.
  45628. *
  45629. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  45630. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  45631. * @return {GPUTexture} The depth buffer.
  45632. */
  45633. getDepthBuffer( depth = true, stencil = false ) {
  45634. const backend = this.backend;
  45635. const { width, height } = backend.getDrawingBufferSize();
  45636. const depthTexture = this.depthTexture;
  45637. const depthTextureGPU = backend.get( depthTexture ).texture;
  45638. let format, type;
  45639. if ( stencil ) {
  45640. format = DepthStencilFormat;
  45641. type = UnsignedInt248Type;
  45642. } else if ( depth ) {
  45643. format = DepthFormat;
  45644. type = UnsignedIntType;
  45645. }
  45646. if ( depthTextureGPU !== undefined ) {
  45647. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  45648. return depthTextureGPU;
  45649. }
  45650. this.destroyTexture( depthTexture );
  45651. }
  45652. depthTexture.name = 'depthBuffer';
  45653. depthTexture.format = format;
  45654. depthTexture.type = type;
  45655. depthTexture.image.width = width;
  45656. depthTexture.image.height = height;
  45657. this.createTexture( depthTexture, { width, height } );
  45658. return backend.get( depthTexture ).texture;
  45659. }
  45660. /**
  45661. * Uploads the updated texture data to the GPU.
  45662. *
  45663. * @param {Texture} texture - The texture.
  45664. * @param {Object} [options={}] - Optional configuration parameter.
  45665. */
  45666. updateTexture( texture, options ) {
  45667. const textureData = this.backend.get( texture );
  45668. const { textureDescriptorGPU } = textureData;
  45669. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  45670. return;
  45671. // transfer texture data
  45672. if ( texture.isDataTexture ) {
  45673. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  45674. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  45675. for ( let i = 0; i < options.image.depth; i ++ ) {
  45676. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  45677. }
  45678. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  45679. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  45680. } else if ( texture.isCubeTexture ) {
  45681. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  45682. } else if ( texture.isVideoTexture ) {
  45683. const video = texture.source.data;
  45684. textureData.externalTexture = video;
  45685. } else {
  45686. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  45687. }
  45688. //
  45689. textureData.version = texture.version;
  45690. if ( texture.onUpdate ) texture.onUpdate( texture );
  45691. }
  45692. /**
  45693. * Returns texture data as a typed array.
  45694. *
  45695. * @async
  45696. * @param {Texture} texture - The texture to copy.
  45697. * @param {number} x - The x coordinate of the copy origin.
  45698. * @param {number} y - The y coordinate of the copy origin.
  45699. * @param {number} width - The width of the copy.
  45700. * @param {number} height - The height of the copy.
  45701. * @param {number} faceIndex - The face index.
  45702. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45703. */
  45704. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45705. const device = this.backend.device;
  45706. const textureData = this.backend.get( texture );
  45707. const textureGPU = textureData.texture;
  45708. const format = textureData.textureDescriptorGPU.format;
  45709. const bytesPerTexel = this._getBytesPerTexel( format );
  45710. let bytesPerRow = width * bytesPerTexel;
  45711. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  45712. const readBuffer = device.createBuffer(
  45713. {
  45714. size: width * height * bytesPerTexel,
  45715. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45716. }
  45717. );
  45718. const encoder = device.createCommandEncoder();
  45719. encoder.copyTextureToBuffer(
  45720. {
  45721. texture: textureGPU,
  45722. origin: { x, y, z: faceIndex },
  45723. },
  45724. {
  45725. buffer: readBuffer,
  45726. bytesPerRow: bytesPerRow
  45727. },
  45728. {
  45729. width: width,
  45730. height: height
  45731. }
  45732. );
  45733. const typedArrayType = this._getTypedArrayType( format );
  45734. device.queue.submit( [ encoder.finish() ] );
  45735. await readBuffer.mapAsync( GPUMapMode.READ );
  45736. const buffer = readBuffer.getMappedRange();
  45737. return new typedArrayType( buffer );
  45738. }
  45739. /**
  45740. * Returns `true` if the given texture is an environment map.
  45741. *
  45742. * @private
  45743. * @param {Texture} texture - The texture.
  45744. * @return {boolean} Whether the given texture is an environment map or not.
  45745. */
  45746. _isEnvironmentTexture( texture ) {
  45747. const mapping = texture.mapping;
  45748. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  45749. }
  45750. /**
  45751. * Returns the default GPU texture for the given format.
  45752. *
  45753. * @private
  45754. * @param {string} format - The GPU format.
  45755. * @return {GPUTexture} The GPU texture.
  45756. */
  45757. _getDefaultTextureGPU( format ) {
  45758. let defaultTexture = this.defaultTexture[ format ];
  45759. if ( defaultTexture === undefined ) {
  45760. const texture = new Texture();
  45761. texture.minFilter = NearestFilter;
  45762. texture.magFilter = NearestFilter;
  45763. this.createTexture( texture, { width: 1, height: 1, format } );
  45764. this.defaultTexture[ format ] = defaultTexture = texture;
  45765. }
  45766. return this.backend.get( defaultTexture ).texture;
  45767. }
  45768. /**
  45769. * Returns the default GPU cube texture for the given format.
  45770. *
  45771. * @private
  45772. * @param {string} format - The GPU format.
  45773. * @return {GPUTexture} The GPU texture.
  45774. */
  45775. _getDefaultCubeTextureGPU( format ) {
  45776. let defaultCubeTexture = this.defaultTexture[ format ];
  45777. if ( defaultCubeTexture === undefined ) {
  45778. const texture = new CubeTexture();
  45779. texture.minFilter = NearestFilter;
  45780. texture.magFilter = NearestFilter;
  45781. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  45782. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  45783. }
  45784. return this.backend.get( defaultCubeTexture ).texture;
  45785. }
  45786. /**
  45787. * Returns the default video frame used as default data in context of video textures.
  45788. *
  45789. * @private
  45790. * @return {VideoFrame} The video frame.
  45791. */
  45792. _getDefaultVideoFrame() {
  45793. let defaultVideoFrame = this.defaultVideoFrame;
  45794. if ( defaultVideoFrame === null ) {
  45795. const init = {
  45796. timestamp: 0,
  45797. codedWidth: 1,
  45798. codedHeight: 1,
  45799. format: 'RGBA',
  45800. };
  45801. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  45802. }
  45803. return defaultVideoFrame;
  45804. }
  45805. /**
  45806. * Uploads cube texture image data to the GPU memory.
  45807. *
  45808. * @private
  45809. * @param {Array} images - The cube image data.
  45810. * @param {GPUTexture} textureGPU - The GPU texture.
  45811. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  45812. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  45813. */
  45814. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  45815. for ( let i = 0; i < 6; i ++ ) {
  45816. const image = images[ i ];
  45817. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  45818. if ( image.isDataTexture ) {
  45819. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  45820. } else {
  45821. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  45822. }
  45823. }
  45824. }
  45825. /**
  45826. * Uploads texture image data to the GPU memory.
  45827. *
  45828. * @private
  45829. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  45830. * @param {GPUTexture} textureGPU - The GPU texture.
  45831. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  45832. * @param {number} originDepth - The origin depth.
  45833. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  45834. */
  45835. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  45836. const device = this.backend.device;
  45837. device.queue.copyExternalImageToTexture(
  45838. {
  45839. source: image,
  45840. flipY: flipY
  45841. }, {
  45842. texture: textureGPU,
  45843. mipLevel: 0,
  45844. origin: { x: 0, y: 0, z: originDepth }
  45845. }, {
  45846. width: image.width,
  45847. height: image.height,
  45848. depthOrArrayLayers: 1
  45849. }
  45850. );
  45851. }
  45852. /**
  45853. * Returns the pass utils singleton.
  45854. *
  45855. * @private
  45856. * @return {WebGPUTexturePassUtils} The utils instance.
  45857. */
  45858. _getPassUtils() {
  45859. let passUtils = this._passUtils;
  45860. if ( passUtils === null ) {
  45861. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  45862. }
  45863. return passUtils;
  45864. }
  45865. /**
  45866. * Generates mipmaps for the given GPU texture.
  45867. *
  45868. * @private
  45869. * @param {GPUTexture} textureGPU - The GPU texture object.
  45870. * @param {Object} textureDescriptorGPU - The texture descriptor.
  45871. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45872. */
  45873. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  45874. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  45875. }
  45876. /**
  45877. * Flip the contents of the given GPU texture along its vertical axis.
  45878. *
  45879. * @private
  45880. * @param {GPUTexture} textureGPU - The GPU texture object.
  45881. * @param {Object} textureDescriptorGPU - The texture descriptor.
  45882. * @param {number} [originDepth=0] - The origin depth.
  45883. */
  45884. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  45885. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  45886. }
  45887. /**
  45888. * Uploads texture buffer data to the GPU memory.
  45889. *
  45890. * @private
  45891. * @param {Object} image - An object defining the image buffer data.
  45892. * @param {GPUTexture} textureGPU - The GPU texture.
  45893. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  45894. * @param {number} originDepth - The origin depth.
  45895. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  45896. * @param {number} [depth=0] - TODO.
  45897. */
  45898. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  45899. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  45900. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  45901. const device = this.backend.device;
  45902. const data = image.data;
  45903. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  45904. const bytesPerRow = image.width * bytesPerTexel;
  45905. device.queue.writeTexture(
  45906. {
  45907. texture: textureGPU,
  45908. mipLevel: 0,
  45909. origin: { x: 0, y: 0, z: originDepth }
  45910. },
  45911. data,
  45912. {
  45913. offset: image.width * image.height * bytesPerTexel * depth,
  45914. bytesPerRow
  45915. },
  45916. {
  45917. width: image.width,
  45918. height: image.height,
  45919. depthOrArrayLayers: 1
  45920. } );
  45921. if ( flipY === true ) {
  45922. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  45923. }
  45924. }
  45925. /**
  45926. * Uploads compressed texture data to the GPU memory.
  45927. *
  45928. * @private
  45929. * @param {Array<Object>} mipmaps - An array with mipmap data.
  45930. * @param {GPUTexture} textureGPU - The GPU texture.
  45931. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  45932. */
  45933. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  45934. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  45935. const device = this.backend.device;
  45936. const blockData = this._getBlockData( textureDescriptorGPU.format );
  45937. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  45938. for ( let i = 0; i < mipmaps.length; i ++ ) {
  45939. const mipmap = mipmaps[ i ];
  45940. const width = mipmap.width;
  45941. const height = mipmap.height;
  45942. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  45943. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  45944. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  45945. for ( let j = 0; j < depth; j ++ ) {
  45946. device.queue.writeTexture(
  45947. {
  45948. texture: textureGPU,
  45949. mipLevel: i,
  45950. origin: { x: 0, y: 0, z: j }
  45951. },
  45952. mipmap.data,
  45953. {
  45954. offset: j * bytesPerImage,
  45955. bytesPerRow,
  45956. rowsPerImage: Math.ceil( height / blockData.height )
  45957. },
  45958. {
  45959. width: Math.ceil( width / blockData.width ) * blockData.width,
  45960. height: Math.ceil( height / blockData.height ) * blockData.height,
  45961. depthOrArrayLayers: 1
  45962. }
  45963. );
  45964. }
  45965. }
  45966. }
  45967. /**
  45968. * This method is only relevant for compressed texture formats. It returns a block
  45969. * data descriptor for the given GPU compressed texture format.
  45970. *
  45971. * @private
  45972. * @param {string} format - The GPU compressed texture format.
  45973. * @return {Object} The block data descriptor.
  45974. */
  45975. _getBlockData( format ) {
  45976. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  45977. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  45978. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  45979. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  45980. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  45981. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  45982. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  45983. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  45984. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  45985. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  45986. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  45987. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  45988. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  45989. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  45990. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  45991. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  45992. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  45993. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  45994. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  45995. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  45996. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  45997. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  45998. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  45999. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  46000. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  46001. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  46002. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  46003. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  46004. }
  46005. /**
  46006. * Converts the three.js uv wrapping constants to GPU address mode constants.
  46007. *
  46008. * @private
  46009. * @param {number} value - The three.js constant defining a uv wrapping mode.
  46010. * @return {string} The GPU address mode.
  46011. */
  46012. _convertAddressMode( value ) {
  46013. let addressMode = GPUAddressMode.ClampToEdge;
  46014. if ( value === RepeatWrapping ) {
  46015. addressMode = GPUAddressMode.Repeat;
  46016. } else if ( value === MirroredRepeatWrapping ) {
  46017. addressMode = GPUAddressMode.MirrorRepeat;
  46018. }
  46019. return addressMode;
  46020. }
  46021. /**
  46022. * Converts the three.js filter constants to GPU filter constants.
  46023. *
  46024. * @private
  46025. * @param {number} value - The three.js constant defining a filter mode.
  46026. * @return {string} The GPU filter mode.
  46027. */
  46028. _convertFilterMode( value ) {
  46029. let filterMode = GPUFilterMode.Linear;
  46030. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  46031. filterMode = GPUFilterMode.Nearest;
  46032. }
  46033. return filterMode;
  46034. }
  46035. /**
  46036. * Returns the bytes-per-texel value for the given GPU texture format.
  46037. *
  46038. * @private
  46039. * @param {string} format - The GPU texture format.
  46040. * @return {number} The bytes-per-texel.
  46041. */
  46042. _getBytesPerTexel( format ) {
  46043. // 8-bit formats
  46044. if ( format === GPUTextureFormat.R8Unorm ||
  46045. format === GPUTextureFormat.R8Snorm ||
  46046. format === GPUTextureFormat.R8Uint ||
  46047. format === GPUTextureFormat.R8Sint ) return 1;
  46048. // 16-bit formats
  46049. if ( format === GPUTextureFormat.R16Uint ||
  46050. format === GPUTextureFormat.R16Sint ||
  46051. format === GPUTextureFormat.R16Float ||
  46052. format === GPUTextureFormat.RG8Unorm ||
  46053. format === GPUTextureFormat.RG8Snorm ||
  46054. format === GPUTextureFormat.RG8Uint ||
  46055. format === GPUTextureFormat.RG8Sint ) return 2;
  46056. // 32-bit formats
  46057. if ( format === GPUTextureFormat.R32Uint ||
  46058. format === GPUTextureFormat.R32Sint ||
  46059. format === GPUTextureFormat.R32Float ||
  46060. format === GPUTextureFormat.RG16Uint ||
  46061. format === GPUTextureFormat.RG16Sint ||
  46062. format === GPUTextureFormat.RG16Float ||
  46063. format === GPUTextureFormat.RGBA8Unorm ||
  46064. format === GPUTextureFormat.RGBA8UnormSRGB ||
  46065. format === GPUTextureFormat.RGBA8Snorm ||
  46066. format === GPUTextureFormat.RGBA8Uint ||
  46067. format === GPUTextureFormat.RGBA8Sint ||
  46068. format === GPUTextureFormat.BGRA8Unorm ||
  46069. format === GPUTextureFormat.BGRA8UnormSRGB ||
  46070. // Packed 32-bit formats
  46071. format === GPUTextureFormat.RGB9E5UFloat ||
  46072. format === GPUTextureFormat.RGB10A2Unorm ||
  46073. format === GPUTextureFormat.RG11B10UFloat ||
  46074. format === GPUTextureFormat.Depth32Float ||
  46075. format === GPUTextureFormat.Depth24Plus ||
  46076. format === GPUTextureFormat.Depth24PlusStencil8 ||
  46077. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  46078. // 64-bit formats
  46079. if ( format === GPUTextureFormat.RG32Uint ||
  46080. format === GPUTextureFormat.RG32Sint ||
  46081. format === GPUTextureFormat.RG32Float ||
  46082. format === GPUTextureFormat.RGBA16Uint ||
  46083. format === GPUTextureFormat.RGBA16Sint ||
  46084. format === GPUTextureFormat.RGBA16Float ) return 8;
  46085. // 128-bit formats
  46086. if ( format === GPUTextureFormat.RGBA32Uint ||
  46087. format === GPUTextureFormat.RGBA32Sint ||
  46088. format === GPUTextureFormat.RGBA32Float ) return 16;
  46089. }
  46090. /**
  46091. * Returns the corresponding typed array type for the given GPU texture format.
  46092. *
  46093. * @private
  46094. * @param {string} format - The GPU texture format.
  46095. * @return {TypedArray.constructor} The typed array type.
  46096. */
  46097. _getTypedArrayType( format ) {
  46098. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  46099. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  46100. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  46101. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  46102. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  46103. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  46104. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  46105. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  46106. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  46107. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  46108. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  46109. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  46110. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  46111. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  46112. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  46113. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  46114. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  46115. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  46116. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  46117. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  46118. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  46119. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  46120. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  46121. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  46122. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  46123. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  46124. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  46125. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  46126. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  46127. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  46128. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  46129. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  46130. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  46131. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  46132. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  46133. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  46134. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  46135. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  46136. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  46137. }
  46138. /**
  46139. * Returns the GPU dimensions for the given texture.
  46140. *
  46141. * @private
  46142. * @param {Texture} texture - The texture.
  46143. * @return {string} The GPU dimension.
  46144. */
  46145. _getDimension( texture ) {
  46146. let dimension;
  46147. if ( texture.isData3DTexture ) {
  46148. dimension = GPUTextureDimension.ThreeD;
  46149. } else {
  46150. dimension = GPUTextureDimension.TwoD;
  46151. }
  46152. return dimension;
  46153. }
  46154. }
  46155. /**
  46156. * Returns the GPU format for the given texture.
  46157. *
  46158. * @param {Texture} texture - The texture.
  46159. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  46160. * It is not necessary to apply the device for most formats.
  46161. * @return {string} The GPU format.
  46162. */
  46163. function getFormat( texture, device = null ) {
  46164. const format = texture.format;
  46165. const type = texture.type;
  46166. const colorSpace = texture.colorSpace;
  46167. let formatGPU;
  46168. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  46169. switch ( format ) {
  46170. case RGBA_S3TC_DXT1_Format:
  46171. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  46172. break;
  46173. case RGBA_S3TC_DXT3_Format:
  46174. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  46175. break;
  46176. case RGBA_S3TC_DXT5_Format:
  46177. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  46178. break;
  46179. case RGB_ETC2_Format:
  46180. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  46181. break;
  46182. case RGBA_ETC2_EAC_Format:
  46183. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  46184. break;
  46185. case RGBA_ASTC_4x4_Format:
  46186. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  46187. break;
  46188. case RGBA_ASTC_5x4_Format:
  46189. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  46190. break;
  46191. case RGBA_ASTC_5x5_Format:
  46192. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  46193. break;
  46194. case RGBA_ASTC_6x5_Format:
  46195. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  46196. break;
  46197. case RGBA_ASTC_6x6_Format:
  46198. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  46199. break;
  46200. case RGBA_ASTC_8x5_Format:
  46201. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  46202. break;
  46203. case RGBA_ASTC_8x6_Format:
  46204. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  46205. break;
  46206. case RGBA_ASTC_8x8_Format:
  46207. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  46208. break;
  46209. case RGBA_ASTC_10x5_Format:
  46210. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  46211. break;
  46212. case RGBA_ASTC_10x6_Format:
  46213. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  46214. break;
  46215. case RGBA_ASTC_10x8_Format:
  46216. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  46217. break;
  46218. case RGBA_ASTC_10x10_Format:
  46219. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  46220. break;
  46221. case RGBA_ASTC_12x10_Format:
  46222. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  46223. break;
  46224. case RGBA_ASTC_12x12_Format:
  46225. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  46226. break;
  46227. case RGBAFormat:
  46228. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46229. break;
  46230. default:
  46231. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46232. }
  46233. } else {
  46234. switch ( format ) {
  46235. case RGBAFormat:
  46236. switch ( type ) {
  46237. case ByteType:
  46238. formatGPU = GPUTextureFormat.RGBA8Snorm;
  46239. break;
  46240. case ShortType:
  46241. formatGPU = GPUTextureFormat.RGBA16Sint;
  46242. break;
  46243. case UnsignedShortType:
  46244. formatGPU = GPUTextureFormat.RGBA16Uint;
  46245. break;
  46246. case UnsignedIntType:
  46247. formatGPU = GPUTextureFormat.RGBA32Uint;
  46248. break;
  46249. case IntType:
  46250. formatGPU = GPUTextureFormat.RGBA32Sint;
  46251. break;
  46252. case UnsignedByteType:
  46253. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46254. break;
  46255. case HalfFloatType:
  46256. formatGPU = GPUTextureFormat.RGBA16Float;
  46257. break;
  46258. case FloatType:
  46259. formatGPU = GPUTextureFormat.RGBA32Float;
  46260. break;
  46261. default:
  46262. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  46263. }
  46264. break;
  46265. case RGBFormat:
  46266. switch ( type ) {
  46267. case UnsignedInt5999Type:
  46268. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  46269. break;
  46270. default:
  46271. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  46272. }
  46273. break;
  46274. case RedFormat:
  46275. switch ( type ) {
  46276. case ByteType:
  46277. formatGPU = GPUTextureFormat.R8Snorm;
  46278. break;
  46279. case ShortType:
  46280. formatGPU = GPUTextureFormat.R16Sint;
  46281. break;
  46282. case UnsignedShortType:
  46283. formatGPU = GPUTextureFormat.R16Uint;
  46284. break;
  46285. case UnsignedIntType:
  46286. formatGPU = GPUTextureFormat.R32Uint;
  46287. break;
  46288. case IntType:
  46289. formatGPU = GPUTextureFormat.R32Sint;
  46290. break;
  46291. case UnsignedByteType:
  46292. formatGPU = GPUTextureFormat.R8Unorm;
  46293. break;
  46294. case HalfFloatType:
  46295. formatGPU = GPUTextureFormat.R16Float;
  46296. break;
  46297. case FloatType:
  46298. formatGPU = GPUTextureFormat.R32Float;
  46299. break;
  46300. default:
  46301. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  46302. }
  46303. break;
  46304. case RGFormat:
  46305. switch ( type ) {
  46306. case ByteType:
  46307. formatGPU = GPUTextureFormat.RG8Snorm;
  46308. break;
  46309. case ShortType:
  46310. formatGPU = GPUTextureFormat.RG16Sint;
  46311. break;
  46312. case UnsignedShortType:
  46313. formatGPU = GPUTextureFormat.RG16Uint;
  46314. break;
  46315. case UnsignedIntType:
  46316. formatGPU = GPUTextureFormat.RG32Uint;
  46317. break;
  46318. case IntType:
  46319. formatGPU = GPUTextureFormat.RG32Sint;
  46320. break;
  46321. case UnsignedByteType:
  46322. formatGPU = GPUTextureFormat.RG8Unorm;
  46323. break;
  46324. case HalfFloatType:
  46325. formatGPU = GPUTextureFormat.RG16Float;
  46326. break;
  46327. case FloatType:
  46328. formatGPU = GPUTextureFormat.RG32Float;
  46329. break;
  46330. default:
  46331. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  46332. }
  46333. break;
  46334. case DepthFormat:
  46335. switch ( type ) {
  46336. case UnsignedShortType:
  46337. formatGPU = GPUTextureFormat.Depth16Unorm;
  46338. break;
  46339. case UnsignedIntType:
  46340. formatGPU = GPUTextureFormat.Depth24Plus;
  46341. break;
  46342. case FloatType:
  46343. formatGPU = GPUTextureFormat.Depth32Float;
  46344. break;
  46345. default:
  46346. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  46347. }
  46348. break;
  46349. case DepthStencilFormat:
  46350. switch ( type ) {
  46351. case UnsignedInt248Type:
  46352. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  46353. break;
  46354. case FloatType:
  46355. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  46356. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  46357. }
  46358. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  46359. break;
  46360. default:
  46361. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  46362. }
  46363. break;
  46364. case RedIntegerFormat:
  46365. switch ( type ) {
  46366. case IntType:
  46367. formatGPU = GPUTextureFormat.R32Sint;
  46368. break;
  46369. case UnsignedIntType:
  46370. formatGPU = GPUTextureFormat.R32Uint;
  46371. break;
  46372. default:
  46373. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  46374. }
  46375. break;
  46376. case RGIntegerFormat:
  46377. switch ( type ) {
  46378. case IntType:
  46379. formatGPU = GPUTextureFormat.RG32Sint;
  46380. break;
  46381. case UnsignedIntType:
  46382. formatGPU = GPUTextureFormat.RG32Uint;
  46383. break;
  46384. default:
  46385. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  46386. }
  46387. break;
  46388. case RGBAIntegerFormat:
  46389. switch ( type ) {
  46390. case IntType:
  46391. formatGPU = GPUTextureFormat.RGBA32Sint;
  46392. break;
  46393. case UnsignedIntType:
  46394. formatGPU = GPUTextureFormat.RGBA32Uint;
  46395. break;
  46396. default:
  46397. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  46398. }
  46399. break;
  46400. default:
  46401. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46402. }
  46403. }
  46404. return formatGPU;
  46405. }
  46406. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  46407. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  46408. const wgslTypeLib$1 = {
  46409. 'f32': 'float',
  46410. 'i32': 'int',
  46411. 'u32': 'uint',
  46412. 'bool': 'bool',
  46413. 'vec2<f32>': 'vec2',
  46414. 'vec2<i32>': 'ivec2',
  46415. 'vec2<u32>': 'uvec2',
  46416. 'vec2<bool>': 'bvec2',
  46417. 'vec2f': 'vec2',
  46418. 'vec2i': 'ivec2',
  46419. 'vec2u': 'uvec2',
  46420. 'vec2b': 'bvec2',
  46421. 'vec3<f32>': 'vec3',
  46422. 'vec3<i32>': 'ivec3',
  46423. 'vec3<u32>': 'uvec3',
  46424. 'vec3<bool>': 'bvec3',
  46425. 'vec3f': 'vec3',
  46426. 'vec3i': 'ivec3',
  46427. 'vec3u': 'uvec3',
  46428. 'vec3b': 'bvec3',
  46429. 'vec4<f32>': 'vec4',
  46430. 'vec4<i32>': 'ivec4',
  46431. 'vec4<u32>': 'uvec4',
  46432. 'vec4<bool>': 'bvec4',
  46433. 'vec4f': 'vec4',
  46434. 'vec4i': 'ivec4',
  46435. 'vec4u': 'uvec4',
  46436. 'vec4b': 'bvec4',
  46437. 'mat2x2<f32>': 'mat2',
  46438. 'mat2x2f': 'mat2',
  46439. 'mat3x3<f32>': 'mat3',
  46440. 'mat3x3f': 'mat3',
  46441. 'mat4x4<f32>': 'mat4',
  46442. 'mat4x4f': 'mat4',
  46443. 'sampler': 'sampler',
  46444. 'texture_1d': 'texture',
  46445. 'texture_2d': 'texture',
  46446. 'texture_2d_array': 'texture',
  46447. 'texture_multisampled_2d': 'cubeTexture',
  46448. 'texture_depth_2d': 'depthTexture',
  46449. 'texture_depth_2d_array': 'depthTexture',
  46450. 'texture_depth_multisampled_2d': 'depthTexture',
  46451. 'texture_depth_cube': 'depthTexture',
  46452. 'texture_depth_cube_array': 'depthTexture',
  46453. 'texture_3d': 'texture3D',
  46454. 'texture_cube': 'cubeTexture',
  46455. 'texture_cube_array': 'cubeTexture',
  46456. 'texture_storage_1d': 'storageTexture',
  46457. 'texture_storage_2d': 'storageTexture',
  46458. 'texture_storage_2d_array': 'storageTexture',
  46459. 'texture_storage_3d': 'storageTexture'
  46460. };
  46461. const parse = ( source ) => {
  46462. source = source.trim();
  46463. const declaration = source.match( declarationRegexp );
  46464. if ( declaration !== null && declaration.length === 4 ) {
  46465. const inputsCode = declaration[ 2 ];
  46466. const propsMatches = [];
  46467. let match = null;
  46468. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  46469. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  46470. }
  46471. // Process matches to correctly pair names and types
  46472. const inputs = [];
  46473. for ( let i = 0; i < propsMatches.length; i ++ ) {
  46474. const { name, type } = propsMatches[ i ];
  46475. let resolvedType = type;
  46476. if ( resolvedType.startsWith( 'ptr' ) ) {
  46477. resolvedType = 'pointer';
  46478. } else {
  46479. if ( resolvedType.startsWith( 'texture' ) ) {
  46480. resolvedType = type.split( '<' )[ 0 ];
  46481. }
  46482. resolvedType = wgslTypeLib$1[ resolvedType ];
  46483. }
  46484. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  46485. }
  46486. const blockCode = source.substring( declaration[ 0 ].length );
  46487. const outputType = declaration[ 3 ] || 'void';
  46488. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  46489. const type = wgslTypeLib$1[ outputType ] || outputType;
  46490. return {
  46491. type,
  46492. inputs,
  46493. name,
  46494. inputsCode,
  46495. blockCode,
  46496. outputType
  46497. };
  46498. } else {
  46499. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  46500. }
  46501. };
  46502. /**
  46503. * This class represents a WSL node function.
  46504. *
  46505. * @augments NodeFunction
  46506. */
  46507. class WGSLNodeFunction extends NodeFunction {
  46508. /**
  46509. * Constructs a new WGSL node function.
  46510. *
  46511. * @param {string} source - The WGSL source.
  46512. */
  46513. constructor( source ) {
  46514. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  46515. super( type, inputs, name );
  46516. this.inputsCode = inputsCode;
  46517. this.blockCode = blockCode;
  46518. this.outputType = outputType;
  46519. }
  46520. /**
  46521. * This method returns the WGSL code of the node function.
  46522. *
  46523. * @param {string} [name=this.name] - The function's name.
  46524. * @return {string} The shader code.
  46525. */
  46526. getCode( name = this.name ) {
  46527. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  46528. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  46529. }
  46530. }
  46531. /**
  46532. * A WGSL node parser.
  46533. *
  46534. * @augments NodeParser
  46535. */
  46536. class WGSLNodeParser extends NodeParser {
  46537. /**
  46538. * The method parses the given WGSL code an returns a node function.
  46539. *
  46540. * @param {string} source - The WGSL code.
  46541. * @return {WGSLNodeFunction} A node function.
  46542. */
  46543. parseFunction( source ) {
  46544. return new WGSLNodeFunction( source );
  46545. }
  46546. }
  46547. // GPUShaderStage is not defined in browsers not supporting WebGPU
  46548. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  46549. const accessNames = {
  46550. [ NodeAccess.READ_ONLY ]: 'read',
  46551. [ NodeAccess.WRITE_ONLY ]: 'write',
  46552. [ NodeAccess.READ_WRITE ]: 'read_write'
  46553. };
  46554. const wrapNames = {
  46555. [ RepeatWrapping ]: 'repeat',
  46556. [ ClampToEdgeWrapping ]: 'clamp',
  46557. [ MirroredRepeatWrapping ]: 'mirror'
  46558. };
  46559. const gpuShaderStageLib = {
  46560. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  46561. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  46562. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  46563. };
  46564. const supports = {
  46565. instance: true,
  46566. swizzleAssign: false,
  46567. storageBuffer: true
  46568. };
  46569. const wgslFnOpLib = {
  46570. '^^': 'tsl_xor'
  46571. };
  46572. const wgslTypeLib = {
  46573. float: 'f32',
  46574. int: 'i32',
  46575. uint: 'u32',
  46576. bool: 'bool',
  46577. color: 'vec3<f32>',
  46578. vec2: 'vec2<f32>',
  46579. ivec2: 'vec2<i32>',
  46580. uvec2: 'vec2<u32>',
  46581. bvec2: 'vec2<bool>',
  46582. vec3: 'vec3<f32>',
  46583. ivec3: 'vec3<i32>',
  46584. uvec3: 'vec3<u32>',
  46585. bvec3: 'vec3<bool>',
  46586. vec4: 'vec4<f32>',
  46587. ivec4: 'vec4<i32>',
  46588. uvec4: 'vec4<u32>',
  46589. bvec4: 'vec4<bool>',
  46590. mat2: 'mat2x2<f32>',
  46591. mat3: 'mat3x3<f32>',
  46592. mat4: 'mat4x4<f32>'
  46593. };
  46594. const wgslCodeCache = {};
  46595. const wgslPolyfill = {
  46596. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  46597. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  46598. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  46599. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  46600. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  46601. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  46602. 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 ); }' ),
  46603. 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 ); }' ),
  46604. 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 ); }' ),
  46605. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  46606. 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 ); }' ),
  46607. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  46608. biquadraticTexture: new CodeNode( /* wgsl */`
  46609. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  46610. let res = vec2f( iRes );
  46611. let uvScaled = coord * res;
  46612. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  46613. // https://www.shadertoy.com/view/WtyXRy
  46614. let uv = uvWrapping - 0.5;
  46615. let iuv = floor( uv );
  46616. let f = fract( uv );
  46617. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  46618. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  46619. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  46620. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  46621. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  46622. }
  46623. ` )
  46624. };
  46625. const wgslMethods = {
  46626. dFdx: 'dpdx',
  46627. dFdy: '- dpdy',
  46628. mod_float: 'tsl_mod_float',
  46629. mod_vec2: 'tsl_mod_vec2',
  46630. mod_vec3: 'tsl_mod_vec3',
  46631. mod_vec4: 'tsl_mod_vec4',
  46632. equals_bool: 'tsl_equals_bool',
  46633. equals_bvec2: 'tsl_equals_bvec2',
  46634. equals_bvec3: 'tsl_equals_bvec3',
  46635. equals_bvec4: 'tsl_equals_bvec4',
  46636. inversesqrt: 'inverseSqrt',
  46637. bitcast: 'bitcast<f32>'
  46638. };
  46639. // WebGPU issue: does not support pow() with negative base on Windows
  46640. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  46641. 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 ); }' );
  46642. 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 ] );
  46643. 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 ] );
  46644. 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 ] );
  46645. wgslMethods.pow_float = 'tsl_pow_float';
  46646. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  46647. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  46648. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  46649. }
  46650. //
  46651. let diagnostics = '';
  46652. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  46653. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  46654. }
  46655. /**
  46656. * A node builder targeting WGSL.
  46657. *
  46658. * This module generates WGSL shader code from node materials and also
  46659. * generates the respective bindings and vertex buffer definitions. These
  46660. * data are later used by the renderer to create render and compute pipelines
  46661. * for render objects.
  46662. *
  46663. * @augments NodeBuilder
  46664. */
  46665. class WGSLNodeBuilder extends NodeBuilder {
  46666. /**
  46667. * Constructs a new WGSL node builder renderer.
  46668. *
  46669. * @param {Object3D} object - The 3D object.
  46670. * @param {Renderer} renderer - The renderer.
  46671. */
  46672. constructor( object, renderer ) {
  46673. super( object, renderer, new WGSLNodeParser() );
  46674. /**
  46675. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  46676. * another dictionary which manages UBOs per group ('render','frame','object').
  46677. *
  46678. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  46679. */
  46680. this.uniformGroups = {};
  46681. /**
  46682. * A dictionary that holds for each shader stage a Map of builtins.
  46683. *
  46684. * @type {Object<string,Map<string,Object>>}
  46685. */
  46686. this.builtins = {};
  46687. /**
  46688. * A dictionary that holds for each shader stage a Set of directives.
  46689. *
  46690. * @type {Object<string,Set<string>>}
  46691. */
  46692. this.directives = {};
  46693. /**
  46694. * A map for managing scope arrays. Only relevant for when using
  46695. * {@link WorkgroupInfoNode} in context of compute shaders.
  46696. *
  46697. * @type {Map<string,Object>}
  46698. */
  46699. this.scopedArrays = new Map();
  46700. }
  46701. /**
  46702. * Checks if the given texture requires a manual conversion to the working color space.
  46703. *
  46704. * @param {Texture} texture - The texture to check.
  46705. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  46706. */
  46707. needsToWorkingColorSpace( texture ) {
  46708. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  46709. }
  46710. /**
  46711. * Generates the WGSL snippet for sampled textures.
  46712. *
  46713. * @private
  46714. * @param {Texture} texture - The texture.
  46715. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46716. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46717. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46718. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46719. * @return {string} The WGSL snippet.
  46720. */
  46721. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46722. if ( shaderStage === 'fragment' ) {
  46723. if ( depthSnippet ) {
  46724. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  46725. } else {
  46726. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  46727. }
  46728. } else if ( this.isFilteredTexture( texture ) ) {
  46729. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  46730. } else {
  46731. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  46732. }
  46733. }
  46734. /**
  46735. * Generates the WGSL snippet when sampling video textures.
  46736. *
  46737. * @private
  46738. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  46739. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46740. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46741. * @return {string} The WGSL snippet.
  46742. */
  46743. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  46744. if ( shaderStage === 'fragment' ) {
  46745. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  46746. } else {
  46747. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  46748. }
  46749. }
  46750. /**
  46751. * Generates the WGSL snippet when sampling textures with explicit mip level.
  46752. *
  46753. * @private
  46754. * @param {Texture} texture - The texture.
  46755. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46756. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46757. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46758. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46759. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46760. * @return {string} The WGSL snippet.
  46761. */
  46762. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46763. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  46764. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  46765. } else if ( this.isFilteredTexture( texture ) ) {
  46766. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  46767. } else {
  46768. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  46769. }
  46770. }
  46771. /**
  46772. * Generates a wrap function used in context of textures.
  46773. *
  46774. * @param {Texture} texture - The texture to generate the function for.
  46775. * @return {string} The name of the generated function.
  46776. */
  46777. generateWrapFunction( texture ) {
  46778. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  46779. let nodeCode = wgslCodeCache[ functionName ];
  46780. if ( nodeCode === undefined ) {
  46781. const includes = [];
  46782. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  46783. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  46784. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  46785. const addWrapSnippet = ( wrap, axis ) => {
  46786. if ( wrap === RepeatWrapping ) {
  46787. includes.push( wgslPolyfill.repeatWrapping_float );
  46788. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  46789. } else if ( wrap === ClampToEdgeWrapping ) {
  46790. includes.push( wgslPolyfill.clampWrapping_float );
  46791. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  46792. } else if ( wrap === MirroredRepeatWrapping ) {
  46793. includes.push( wgslPolyfill.mirrorWrapping_float );
  46794. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  46795. } else {
  46796. code += `\t\tcoord.${ axis }`;
  46797. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  46798. }
  46799. };
  46800. addWrapSnippet( texture.wrapS, 'x' );
  46801. code += ',\n';
  46802. addWrapSnippet( texture.wrapT, 'y' );
  46803. if ( texture.isData3DTexture ) {
  46804. code += ',\n';
  46805. addWrapSnippet( texture.wrapR, 'z' );
  46806. }
  46807. code += '\n\t);\n\n}\n';
  46808. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  46809. }
  46810. nodeCode.build( this );
  46811. return functionName;
  46812. }
  46813. /**
  46814. * Generates the array declaration string.
  46815. *
  46816. * @param {string} type - The type.
  46817. * @param {?number} [count] - The count.
  46818. * @return {string} The generated value as a shader string.
  46819. */
  46820. generateArrayDeclaration( type, count ) {
  46821. return `array< ${ this.getType( type ) }, ${ count } >`;
  46822. }
  46823. /**
  46824. * Generates a WGSL variable that holds the texture dimension of the given texture.
  46825. * It also returns information about the number of layers (elements) of an arrayed
  46826. * texture as well as the cube face count of cube textures.
  46827. *
  46828. * @param {Texture} texture - The texture to generate the function for.
  46829. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  46830. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46831. * @return {string} The name of the dimension variable.
  46832. */
  46833. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  46834. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  46835. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  46836. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  46837. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  46838. let textureDimensionsParams;
  46839. let dimensionType;
  46840. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  46841. const isMultisampled = primarySamples > 1;
  46842. if ( texture.isData3DTexture ) {
  46843. dimensionType = 'vec3<u32>';
  46844. } else {
  46845. // Regular 2D textures, depth textures, etc.
  46846. dimensionType = 'vec2<u32>';
  46847. }
  46848. // Build parameters string based on texture type and multisampling
  46849. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  46850. textureDimensionsParams = textureProperty;
  46851. } else {
  46852. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  46853. }
  46854. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  46855. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  46856. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  46857. textureData.arrayLayerCount = new VarNode(
  46858. new ExpressionNode(
  46859. `textureNumLayers(${textureProperty})`,
  46860. 'u32'
  46861. )
  46862. );
  46863. }
  46864. // For cube textures, we know it's always 6 faces
  46865. if ( texture.isTextureCube ) {
  46866. textureData.cubeFaceCount = new VarNode(
  46867. new ExpressionNode( '6u', 'u32' )
  46868. );
  46869. }
  46870. }
  46871. return textureDimensionNode.build( this );
  46872. }
  46873. /**
  46874. * Generates the WGSL snippet for a manual filtered texture.
  46875. *
  46876. * @param {Texture} texture - The texture.
  46877. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46878. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46879. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46880. * @return {string} The WGSL snippet.
  46881. */
  46882. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  46883. this._include( 'biquadraticTexture' );
  46884. const wrapFunction = this.generateWrapFunction( texture );
  46885. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  46886. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  46887. }
  46888. /**
  46889. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  46890. * Since it's a lookup, no sampling or filtering is applied.
  46891. *
  46892. * @param {Texture} texture - The texture.
  46893. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46894. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46895. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46896. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46897. * @return {string} The WGSL snippet.
  46898. */
  46899. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  46900. const wrapFunction = this.generateWrapFunction( texture );
  46901. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  46902. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  46903. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  46904. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  46905. }
  46906. /**
  46907. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  46908. *
  46909. * @param {Texture} texture - The texture.
  46910. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46911. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46912. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46913. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46914. * @return {string} The WGSL snippet.
  46915. */
  46916. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  46917. let snippet;
  46918. if ( texture.isVideoTexture === true ) {
  46919. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  46920. } else if ( depthSnippet ) {
  46921. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  46922. } else {
  46923. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  46924. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  46925. snippet += '.x';
  46926. }
  46927. }
  46928. return snippet;
  46929. }
  46930. /**
  46931. * Generates the WGSL snippet that writes a single texel to a texture.
  46932. *
  46933. * @param {Texture} texture - The texture.
  46934. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46935. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46936. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46937. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  46938. * @return {string} The WGSL snippet.
  46939. */
  46940. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  46941. let snippet;
  46942. if ( depthSnippet ) {
  46943. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  46944. } else {
  46945. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  46946. }
  46947. return snippet;
  46948. }
  46949. /**
  46950. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  46951. *
  46952. * @param {Texture} texture - The texture.
  46953. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  46954. */
  46955. isSampleCompare( texture ) {
  46956. return texture.isDepthTexture === true && texture.compareFunction !== null;
  46957. }
  46958. /**
  46959. * Returns `true` if the given texture is unfilterable.
  46960. *
  46961. * @param {Texture} texture - The texture.
  46962. * @return {boolean} Whether the given texture is unfilterable or not.
  46963. */
  46964. isUnfilterable( texture ) {
  46965. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  46966. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  46967. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  46968. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  46969. }
  46970. /**
  46971. * Generates the WGSL snippet for sampling/loading the given texture.
  46972. *
  46973. * @param {Texture} texture - The texture.
  46974. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46975. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46976. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46977. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46978. * @return {string} The WGSL snippet.
  46979. */
  46980. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46981. let snippet = null;
  46982. if ( texture.isVideoTexture === true ) {
  46983. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  46984. } else if ( this.isUnfilterable( texture ) ) {
  46985. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  46986. } else {
  46987. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  46988. }
  46989. return snippet;
  46990. }
  46991. /**
  46992. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  46993. *
  46994. * @param {Texture} texture - The texture.
  46995. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46996. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46997. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  46998. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46999. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47000. * @return {string} The WGSL snippet.
  47001. */
  47002. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47003. if ( shaderStage === 'fragment' ) {
  47004. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  47005. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  47006. } else {
  47007. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  47008. }
  47009. }
  47010. /**
  47011. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  47012. * against a reference value.
  47013. *
  47014. * @param {Texture} texture - The texture.
  47015. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47016. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47017. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  47018. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47019. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47020. * @return {string} The WGSL snippet.
  47021. */
  47022. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47023. if ( shaderStage === 'fragment' ) {
  47024. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  47025. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  47026. }
  47027. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  47028. } else {
  47029. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  47030. }
  47031. }
  47032. /**
  47033. * Generates the WGSL snippet when sampling textures with explicit mip level.
  47034. *
  47035. * @param {Texture} texture - The texture.
  47036. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47037. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47038. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47039. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47040. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47041. * @return {string} The WGSL snippet.
  47042. */
  47043. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47044. let snippet = null;
  47045. if ( texture.isVideoTexture === true ) {
  47046. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  47047. } else {
  47048. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  47049. }
  47050. return snippet;
  47051. }
  47052. /**
  47053. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  47054. *
  47055. * @param {Texture} texture - The texture.
  47056. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47057. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47058. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  47059. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47060. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47061. * @return {string} The WGSL snippet.
  47062. */
  47063. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47064. if ( shaderStage === 'fragment' ) {
  47065. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  47066. } else {
  47067. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  47068. }
  47069. }
  47070. /**
  47071. * Returns a WGSL snippet that represents the property name of the given node.
  47072. *
  47073. * @param {Node} node - The node.
  47074. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47075. * @return {string} The property name.
  47076. */
  47077. getPropertyName( node, shaderStage = this.shaderStage ) {
  47078. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  47079. if ( shaderStage === 'vertex' ) {
  47080. return `varyings.${ node.name }`;
  47081. }
  47082. } else if ( node.isNodeUniform === true ) {
  47083. const name = node.name;
  47084. const type = node.type;
  47085. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47086. return name;
  47087. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47088. if ( this.isCustomStruct( node ) ) {
  47089. return name;
  47090. }
  47091. return name + '.value';
  47092. } else {
  47093. return node.groupNode.name + '.' + name;
  47094. }
  47095. }
  47096. return super.getPropertyName( node );
  47097. }
  47098. /**
  47099. * Returns the output struct name.
  47100. *
  47101. * @return {string} The name of the output struct.
  47102. */
  47103. getOutputStructName() {
  47104. return 'output';
  47105. }
  47106. /**
  47107. * Returns the native shader operator name for a given generic name.
  47108. *
  47109. * @param {string} op - The operator name to resolve.
  47110. * @return {?string} The resolved operator name.
  47111. */
  47112. getFunctionOperator( op ) {
  47113. const fnOp = wgslFnOpLib[ op ];
  47114. if ( fnOp !== undefined ) {
  47115. this._include( fnOp );
  47116. return fnOp;
  47117. }
  47118. return null;
  47119. }
  47120. /**
  47121. * Returns the node access for the given node and shader stage.
  47122. *
  47123. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47124. * @param {string} shaderStage - The shader stage.
  47125. * @return {string} The node access.
  47126. */
  47127. getNodeAccess( node, shaderStage ) {
  47128. if ( shaderStage !== 'compute' )
  47129. return NodeAccess.READ_ONLY;
  47130. return node.access;
  47131. }
  47132. /**
  47133. * Returns A WGSL snippet representing the storage access.
  47134. *
  47135. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47136. * @param {string} shaderStage - The shader stage.
  47137. * @return {string} The WGSL snippet representing the storage access.
  47138. */
  47139. getStorageAccess( node, shaderStage ) {
  47140. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  47141. }
  47142. /**
  47143. * This method is one of the more important ones since it's responsible
  47144. * for generating a matching binding instance for the given uniform node.
  47145. *
  47146. * These bindings are later used in the renderer to create bind groups
  47147. * and layouts.
  47148. *
  47149. * @param {UniformNode} node - The uniform node.
  47150. * @param {string} type - The node data type.
  47151. * @param {string} shaderStage - The shader stage.
  47152. * @param {?string} [name=null] - An optional uniform name.
  47153. * @return {NodeUniform} The node uniform object.
  47154. */
  47155. getUniformFromNode( node, type, shaderStage, name = null ) {
  47156. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  47157. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  47158. if ( nodeData.uniformGPU === undefined ) {
  47159. let uniformGPU;
  47160. const group = node.groupNode;
  47161. const groupName = group.name;
  47162. const bindings = this.getBindGroupArray( groupName, shaderStage );
  47163. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47164. let texture = null;
  47165. const access = this.getNodeAccess( node, shaderStage );
  47166. if ( type === 'texture' || type === 'storageTexture' ) {
  47167. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  47168. } else if ( type === 'cubeTexture' ) {
  47169. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  47170. } else if ( type === 'texture3D' ) {
  47171. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  47172. }
  47173. texture.store = node.isStorageTextureNode === true;
  47174. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47175. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  47176. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  47177. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47178. bindings.push( sampler, texture );
  47179. uniformGPU = [ sampler, texture ];
  47180. } else {
  47181. bindings.push( texture );
  47182. uniformGPU = [ texture ];
  47183. }
  47184. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47185. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  47186. const buffer = new bufferClass( node, group );
  47187. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47188. bindings.push( buffer );
  47189. uniformGPU = buffer;
  47190. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  47191. } else {
  47192. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  47193. let uniformsGroup = uniformsStage[ groupName ];
  47194. if ( uniformsGroup === undefined ) {
  47195. uniformsGroup = new NodeUniformsGroup( groupName, group );
  47196. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47197. uniformsStage[ groupName ] = uniformsGroup;
  47198. bindings.push( uniformsGroup );
  47199. }
  47200. uniformGPU = this.getNodeUniform( uniformNode, type );
  47201. uniformsGroup.addUniform( uniformGPU );
  47202. }
  47203. nodeData.uniformGPU = uniformGPU;
  47204. }
  47205. return uniformNode;
  47206. }
  47207. /**
  47208. * This method should be used whenever builtins are required in nodes.
  47209. * The internal builtins data structure will make sure builtins are
  47210. * defined in the WGSL source.
  47211. *
  47212. * @param {string} name - The builtin name.
  47213. * @param {string} property - The property name.
  47214. * @param {string} type - The node data type.
  47215. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47216. * @return {string} The property name.
  47217. */
  47218. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  47219. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  47220. if ( map.has( name ) === false ) {
  47221. map.set( name, {
  47222. name,
  47223. property,
  47224. type
  47225. } );
  47226. }
  47227. return property;
  47228. }
  47229. /**
  47230. * Returns `true` if the given builtin is defined in the given shader stage.
  47231. *
  47232. * @param {string} name - The builtin name.
  47233. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47234. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  47235. */
  47236. hasBuiltin( name, shaderStage = this.shaderStage ) {
  47237. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  47238. }
  47239. /**
  47240. * Returns the vertex index builtin.
  47241. *
  47242. * @return {string} The vertex index.
  47243. */
  47244. getVertexIndex() {
  47245. if ( this.shaderStage === 'vertex' ) {
  47246. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  47247. }
  47248. return 'vertexIndex';
  47249. }
  47250. /**
  47251. * Builds the given shader node.
  47252. *
  47253. * @param {ShaderNodeInternal} shaderNode - The shader node.
  47254. * @return {string} The WGSL function code.
  47255. */
  47256. buildFunctionCode( shaderNode ) {
  47257. const layout = shaderNode.layout;
  47258. const flowData = this.flowShaderNode( shaderNode );
  47259. const parameters = [];
  47260. for ( const input of layout.inputs ) {
  47261. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  47262. }
  47263. //
  47264. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  47265. ${ flowData.vars }
  47266. ${ flowData.code }
  47267. `;
  47268. if ( flowData.result ) {
  47269. code += `\treturn ${ flowData.result };\n`;
  47270. }
  47271. code += '\n}\n';
  47272. //
  47273. return code;
  47274. }
  47275. /**
  47276. * Returns the instance index builtin.
  47277. *
  47278. * @return {string} The instance index.
  47279. */
  47280. getInstanceIndex() {
  47281. if ( this.shaderStage === 'vertex' ) {
  47282. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  47283. }
  47284. return 'instanceIndex';
  47285. }
  47286. /**
  47287. * Returns the invocation local index builtin.
  47288. *
  47289. * @return {string} The invocation local index.
  47290. */
  47291. getInvocationLocalIndex() {
  47292. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  47293. }
  47294. /**
  47295. * Returns the subgroup size builtin.
  47296. *
  47297. * @return {string} The subgroup size.
  47298. */
  47299. getSubgroupSize() {
  47300. this.enableSubGroups();
  47301. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  47302. }
  47303. /**
  47304. * Returns the invocation subgroup index builtin.
  47305. *
  47306. * @return {string} The invocation subgroup index.
  47307. */
  47308. getInvocationSubgroupIndex() {
  47309. this.enableSubGroups();
  47310. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  47311. }
  47312. /**
  47313. * Returns the subgroup index builtin.
  47314. *
  47315. * @return {string} The subgroup index.
  47316. */
  47317. getSubgroupIndex() {
  47318. this.enableSubGroups();
  47319. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  47320. }
  47321. /**
  47322. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  47323. *
  47324. * @return {null} Null.
  47325. */
  47326. getDrawIndex() {
  47327. return null;
  47328. }
  47329. /**
  47330. * Returns the front facing builtin.
  47331. *
  47332. * @return {string} The front facing builtin.
  47333. */
  47334. getFrontFacing() {
  47335. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  47336. }
  47337. /**
  47338. * Returns the frag coord builtin.
  47339. *
  47340. * @return {string} The frag coord builtin.
  47341. */
  47342. getFragCoord() {
  47343. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  47344. }
  47345. /**
  47346. * Returns the frag depth builtin.
  47347. *
  47348. * @return {string} The frag depth builtin.
  47349. */
  47350. getFragDepth() {
  47351. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  47352. }
  47353. /**
  47354. * Returns the clip distances builtin.
  47355. *
  47356. * @return {string} The clip distances builtin.
  47357. */
  47358. getClipDistance() {
  47359. return 'varyings.hw_clip_distances';
  47360. }
  47361. /**
  47362. * Whether to flip texture data along its vertical axis or not.
  47363. *
  47364. * @return {boolean} Returns always `false` in context of WGSL.
  47365. */
  47366. isFlipY() {
  47367. return false;
  47368. }
  47369. /**
  47370. * Enables the given directive for the given shader stage.
  47371. *
  47372. * @param {string} name - The directive name.
  47373. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  47374. */
  47375. enableDirective( name, shaderStage = this.shaderStage ) {
  47376. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  47377. stage.add( name );
  47378. }
  47379. /**
  47380. * Returns the directives of the given shader stage as a WGSL string.
  47381. *
  47382. * @param {string} shaderStage - The shader stage.
  47383. * @return {string} A WGSL snippet that enables the directives of the given stage.
  47384. */
  47385. getDirectives( shaderStage ) {
  47386. const snippets = [];
  47387. const directives = this.directives[ shaderStage ];
  47388. if ( directives !== undefined ) {
  47389. for ( const directive of directives ) {
  47390. snippets.push( `enable ${directive};` );
  47391. }
  47392. }
  47393. return snippets.join( '\n' );
  47394. }
  47395. /**
  47396. * Enables the 'subgroups' directive.
  47397. */
  47398. enableSubGroups() {
  47399. this.enableDirective( 'subgroups' );
  47400. }
  47401. /**
  47402. * Enables the 'subgroups-f16' directive.
  47403. */
  47404. enableSubgroupsF16() {
  47405. this.enableDirective( 'subgroups-f16' );
  47406. }
  47407. /**
  47408. * Enables the 'clip_distances' directive.
  47409. */
  47410. enableClipDistances() {
  47411. this.enableDirective( 'clip_distances' );
  47412. }
  47413. /**
  47414. * Enables the 'f16' directive.
  47415. */
  47416. enableShaderF16() {
  47417. this.enableDirective( 'f16' );
  47418. }
  47419. /**
  47420. * Enables the 'dual_source_blending' directive.
  47421. */
  47422. enableDualSourceBlending() {
  47423. this.enableDirective( 'dual_source_blending' );
  47424. }
  47425. /**
  47426. * Enables hardware clipping.
  47427. *
  47428. * @param {string} planeCount - The clipping plane count.
  47429. */
  47430. enableHardwareClipping( planeCount ) {
  47431. this.enableClipDistances();
  47432. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  47433. }
  47434. /**
  47435. * Returns the builtins of the given shader stage as a WGSL string.
  47436. *
  47437. * @param {string} shaderStage - The shader stage.
  47438. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  47439. */
  47440. getBuiltins( shaderStage ) {
  47441. const snippets = [];
  47442. const builtins = this.builtins[ shaderStage ];
  47443. if ( builtins !== undefined ) {
  47444. for ( const { name, property, type } of builtins.values() ) {
  47445. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  47446. }
  47447. }
  47448. return snippets.join( ',\n\t' );
  47449. }
  47450. /**
  47451. * This method should be used when a new scoped buffer is used in context of
  47452. * compute shaders. It adds the array to the internal data structure which is
  47453. * later used to generate the respective WGSL.
  47454. *
  47455. * @param {string} name - The array name.
  47456. * @param {string} scope - The scope.
  47457. * @param {string} bufferType - The buffer type.
  47458. * @param {string} bufferCount - The buffer count.
  47459. * @return {string} The array name.
  47460. */
  47461. getScopedArray( name, scope, bufferType, bufferCount ) {
  47462. if ( this.scopedArrays.has( name ) === false ) {
  47463. this.scopedArrays.set( name, {
  47464. name,
  47465. scope,
  47466. bufferType,
  47467. bufferCount
  47468. } );
  47469. }
  47470. return name;
  47471. }
  47472. /**
  47473. * Returns the scoped arrays of the given shader stage as a WGSL string.
  47474. *
  47475. * @param {string} shaderStage - The shader stage.
  47476. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  47477. * Returns `undefined` when used in the vertex or fragment stage.
  47478. */
  47479. getScopedArrays( shaderStage ) {
  47480. if ( shaderStage !== 'compute' ) {
  47481. return;
  47482. }
  47483. const snippets = [];
  47484. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  47485. const type = this.getType( bufferType );
  47486. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  47487. }
  47488. return snippets.join( '\n' );
  47489. }
  47490. /**
  47491. * Returns the shader attributes of the given shader stage as a WGSL string.
  47492. *
  47493. * @param {string} shaderStage - The shader stage.
  47494. * @return {string} The WGSL snippet that defines the shader attributes.
  47495. */
  47496. getAttributes( shaderStage ) {
  47497. const snippets = [];
  47498. if ( shaderStage === 'compute' ) {
  47499. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  47500. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  47501. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  47502. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  47503. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  47504. this.enableDirective( 'subgroups', shaderStage );
  47505. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  47506. }
  47507. }
  47508. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  47509. const builtins = this.getBuiltins( 'attribute' );
  47510. if ( builtins ) snippets.push( builtins );
  47511. const attributes = this.getAttributesArray();
  47512. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  47513. const attribute = attributes[ index ];
  47514. const name = attribute.name;
  47515. const type = this.getType( attribute.type );
  47516. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  47517. }
  47518. }
  47519. return snippets.join( ',\n\t' );
  47520. }
  47521. /**
  47522. * Returns the members of the given struct type node as a WGSL string.
  47523. *
  47524. * @param {StructTypeNode} struct - The struct type node.
  47525. * @return {string} The WGSL snippet that defines the struct members.
  47526. */
  47527. getStructMembers( struct ) {
  47528. const snippets = [];
  47529. for ( const member of struct.members ) {
  47530. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  47531. let type = this.getType( member.type );
  47532. if ( member.atomic ) {
  47533. type = 'atomic< ' + type + ' >';
  47534. }
  47535. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  47536. }
  47537. if ( struct.output ) {
  47538. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  47539. }
  47540. return snippets.join( ',\n' );
  47541. }
  47542. /**
  47543. * Returns the structs of the given shader stage as a WGSL string.
  47544. *
  47545. * @param {string} shaderStage - The shader stage.
  47546. * @return {string} The WGSL snippet that defines the structs.
  47547. */
  47548. getStructs( shaderStage ) {
  47549. let result = '';
  47550. const structs = this.structs[ shaderStage ];
  47551. if ( structs.length > 0 ) {
  47552. const snippets = [];
  47553. for ( const struct of structs ) {
  47554. let snippet = `struct ${ struct.name } {\n`;
  47555. snippet += this.getStructMembers( struct );
  47556. snippet += '\n};';
  47557. snippets.push( snippet );
  47558. }
  47559. result = '\n' + snippets.join( '\n\n' ) + '\n';
  47560. }
  47561. return result;
  47562. }
  47563. /**
  47564. * Returns a WGSL string representing a variable.
  47565. *
  47566. * @param {string} type - The variable's type.
  47567. * @param {string} name - The variable's name.
  47568. * @param {?number} [count=null] - The array length.
  47569. * @return {string} The WGSL snippet that defines a variable.
  47570. */
  47571. getVar( type, name, count = null ) {
  47572. let snippet = `var ${ name } : `;
  47573. if ( count !== null ) {
  47574. snippet += this.generateArrayDeclaration( type, count );
  47575. } else {
  47576. snippet += this.getType( type );
  47577. }
  47578. return snippet;
  47579. }
  47580. /**
  47581. * Returns the variables of the given shader stage as a WGSL string.
  47582. *
  47583. * @param {string} shaderStage - The shader stage.
  47584. * @return {string} The WGSL snippet that defines the variables.
  47585. */
  47586. getVars( shaderStage ) {
  47587. const snippets = [];
  47588. const vars = this.vars[ shaderStage ];
  47589. if ( vars !== undefined ) {
  47590. for ( const variable of vars ) {
  47591. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  47592. }
  47593. }
  47594. return `\n${ snippets.join( '\n' ) }\n`;
  47595. }
  47596. /**
  47597. * Returns the varyings of the given shader stage as a WGSL string.
  47598. *
  47599. * @param {string} shaderStage - The shader stage.
  47600. * @return {string} The WGSL snippet that defines the varyings.
  47601. */
  47602. getVaryings( shaderStage ) {
  47603. const snippets = [];
  47604. if ( shaderStage === 'vertex' ) {
  47605. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  47606. }
  47607. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  47608. const varyings = this.varyings;
  47609. const vars = this.vars[ shaderStage ];
  47610. for ( let index = 0; index < varyings.length; index ++ ) {
  47611. const varying = varyings[ index ];
  47612. if ( varying.needsInterpolation ) {
  47613. let attributesSnippet = `@location( ${index} )`;
  47614. if ( varying.interpolationType ) {
  47615. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  47616. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  47617. // Otherwise, optimize interpolation when sensible
  47618. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  47619. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  47620. }
  47621. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  47622. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  47623. vars.push( varying );
  47624. }
  47625. }
  47626. }
  47627. const builtins = this.getBuiltins( shaderStage );
  47628. if ( builtins ) snippets.push( builtins );
  47629. const code = snippets.join( ',\n\t' );
  47630. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  47631. }
  47632. isCustomStruct( nodeUniform ) {
  47633. const attribute = nodeUniform.value;
  47634. const bufferNode = nodeUniform.node;
  47635. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  47636. const isStructArray =
  47637. ( bufferNode.value && bufferNode.value.array ) &&
  47638. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  47639. return isAttributeStructType && ! isStructArray;
  47640. }
  47641. /**
  47642. * Returns the uniforms of the given shader stage as a WGSL string.
  47643. *
  47644. * @param {string} shaderStage - The shader stage.
  47645. * @return {string} The WGSL snippet that defines the uniforms.
  47646. */
  47647. getUniforms( shaderStage ) {
  47648. const uniforms = this.uniforms[ shaderStage ];
  47649. const bindingSnippets = [];
  47650. const bufferSnippets = [];
  47651. const structSnippets = [];
  47652. const uniformGroups = {};
  47653. for ( const uniform of uniforms ) {
  47654. const groupName = uniform.groupNode.name;
  47655. const uniformIndexes = this.bindingsIndexes[ groupName ];
  47656. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  47657. const texture = uniform.node.value;
  47658. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  47659. if ( this.isSampleCompare( texture ) ) {
  47660. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  47661. } else {
  47662. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  47663. }
  47664. }
  47665. let textureType;
  47666. let multisampled = '';
  47667. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  47668. if ( primarySamples > 1 ) {
  47669. multisampled = '_multisampled';
  47670. }
  47671. if ( texture.isCubeTexture === true ) {
  47672. textureType = 'texture_cube<f32>';
  47673. } else if ( texture.isDepthTexture === true ) {
  47674. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  47675. textureType = `texture${ multisampled }_2d<f32>`;
  47676. } else {
  47677. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  47678. }
  47679. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  47680. textureType = 'texture_2d_array<f32>';
  47681. } else if ( texture.isVideoTexture === true ) {
  47682. textureType = 'texture_external';
  47683. } else if ( texture.isData3DTexture === true ) {
  47684. textureType = 'texture_3d<f32>';
  47685. } else if ( uniform.node.isStorageTextureNode === true ) {
  47686. const format = getFormat( texture );
  47687. const access = this.getStorageAccess( uniform.node, shaderStage );
  47688. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  47689. } else {
  47690. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  47691. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  47692. }
  47693. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  47694. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  47695. const bufferNode = uniform.node;
  47696. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  47697. const bufferCount = bufferNode.bufferCount;
  47698. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  47699. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  47700. if ( this.isCustomStruct( uniform ) ) {
  47701. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  47702. } else {
  47703. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  47704. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  47705. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  47706. }
  47707. } else {
  47708. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  47709. const groupName = uniform.groupNode.name;
  47710. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  47711. index: uniformIndexes.binding ++,
  47712. id: uniformIndexes.group,
  47713. snippets: []
  47714. } );
  47715. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  47716. }
  47717. }
  47718. for ( const name in uniformGroups ) {
  47719. const group = uniformGroups[ name ];
  47720. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  47721. }
  47722. let code = bindingSnippets.join( '\n' );
  47723. code += bufferSnippets.join( '\n' );
  47724. code += structSnippets.join( '\n' );
  47725. return code;
  47726. }
  47727. /**
  47728. * Controls the code build of the shader stages.
  47729. */
  47730. buildCode() {
  47731. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  47732. this.sortBindingGroups();
  47733. for ( const shaderStage in shadersData ) {
  47734. this.shaderStage = shaderStage;
  47735. const stageData = shadersData[ shaderStage ];
  47736. stageData.uniforms = this.getUniforms( shaderStage );
  47737. stageData.attributes = this.getAttributes( shaderStage );
  47738. stageData.varyings = this.getVaryings( shaderStage );
  47739. stageData.structs = this.getStructs( shaderStage );
  47740. stageData.vars = this.getVars( shaderStage );
  47741. stageData.codes = this.getCodes( shaderStage );
  47742. stageData.directives = this.getDirectives( shaderStage );
  47743. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  47744. //
  47745. let flow = '// code\n\n';
  47746. flow += this.flowCode[ shaderStage ];
  47747. const flowNodes = this.flowNodes[ shaderStage ];
  47748. const mainNode = flowNodes[ flowNodes.length - 1 ];
  47749. const outputNode = mainNode.outputNode;
  47750. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  47751. for ( const node of flowNodes ) {
  47752. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  47753. const slotName = node.name;
  47754. if ( slotName ) {
  47755. if ( flow.length > 0 ) flow += '\n';
  47756. flow += `\t// flow -> ${ slotName }\n`;
  47757. }
  47758. flow += `${ flowSlotData.code }\n\t`;
  47759. if ( node === mainNode && shaderStage !== 'compute' ) {
  47760. flow += '// result\n\n\t';
  47761. if ( shaderStage === 'vertex' ) {
  47762. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  47763. } else if ( shaderStage === 'fragment' ) {
  47764. if ( isOutputStruct ) {
  47765. stageData.returnType = outputNode.getNodeType( this );
  47766. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  47767. flow += `return ${ flowSlotData.result };`;
  47768. } else {
  47769. let structSnippet = '\t@location(0) color: vec4<f32>';
  47770. const builtins = this.getBuiltins( 'output' );
  47771. if ( builtins ) structSnippet += ',\n\t' + builtins;
  47772. stageData.returnType = 'OutputStruct';
  47773. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  47774. stageData.structs += '\nvar<private> output : OutputStruct;';
  47775. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  47776. }
  47777. }
  47778. }
  47779. }
  47780. stageData.flow = flow;
  47781. }
  47782. this.shaderStage = null;
  47783. if ( this.material !== null ) {
  47784. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  47785. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  47786. } else {
  47787. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  47788. }
  47789. }
  47790. /**
  47791. * Returns the native shader method name for a given generic name.
  47792. *
  47793. * @param {string} method - The method name to resolve.
  47794. * @param {?string} [output=null] - An optional output.
  47795. * @return {string} The resolved WGSL method name.
  47796. */
  47797. getMethod( method, output = null ) {
  47798. let wgslMethod;
  47799. if ( output !== null ) {
  47800. wgslMethod = this._getWGSLMethod( method + '_' + output );
  47801. }
  47802. if ( wgslMethod === undefined ) {
  47803. wgslMethod = this._getWGSLMethod( method );
  47804. }
  47805. return wgslMethod || method;
  47806. }
  47807. /**
  47808. * Returns the WGSL type of the given node data type.
  47809. *
  47810. * @param {string} type - The node data type.
  47811. * @return {string} The WGSL type.
  47812. */
  47813. getType( type ) {
  47814. return wgslTypeLib[ type ] || type;
  47815. }
  47816. /**
  47817. * Whether the requested feature is available or not.
  47818. *
  47819. * @param {string} name - The requested feature.
  47820. * @return {boolean} Whether the requested feature is supported or not.
  47821. */
  47822. isAvailable( name ) {
  47823. let result = supports[ name ];
  47824. if ( result === undefined ) {
  47825. if ( name === 'float32Filterable' ) {
  47826. result = this.renderer.hasFeature( 'float32-filterable' );
  47827. } else if ( name === 'clipDistance' ) {
  47828. result = this.renderer.hasFeature( 'clip-distances' );
  47829. }
  47830. supports[ name ] = result;
  47831. }
  47832. return result;
  47833. }
  47834. /**
  47835. * Returns the native shader method name for a given generic name.
  47836. *
  47837. * @private
  47838. * @param {string} method - The method name to resolve.
  47839. * @return {string} The resolved WGSL method name.
  47840. */
  47841. _getWGSLMethod( method ) {
  47842. if ( wgslPolyfill[ method ] !== undefined ) {
  47843. this._include( method );
  47844. }
  47845. return wgslMethods[ method ];
  47846. }
  47847. /**
  47848. * Includes the given method name into the current
  47849. * function node.
  47850. *
  47851. * @private
  47852. * @param {string} name - The method name to include.
  47853. * @return {CodeNode} The respective code node.
  47854. */
  47855. _include( name ) {
  47856. const codeNode = wgslPolyfill[ name ];
  47857. codeNode.build( this );
  47858. if ( this.currentFunctionNode !== null ) {
  47859. this.currentFunctionNode.includes.push( codeNode );
  47860. }
  47861. return codeNode;
  47862. }
  47863. /**
  47864. * Returns a WGSL vertex shader based on the given shader data.
  47865. *
  47866. * @private
  47867. * @param {Object} shaderData - The shader data.
  47868. * @return {string} The vertex shader.
  47869. */
  47870. _getWGSLVertexCode( shaderData ) {
  47871. return `${ this.getSignature() }
  47872. // directives
  47873. ${shaderData.directives}
  47874. // structs
  47875. ${shaderData.structs}
  47876. // uniforms
  47877. ${shaderData.uniforms}
  47878. // varyings
  47879. ${shaderData.varyings}
  47880. var<private> varyings : VaryingsStruct;
  47881. // codes
  47882. ${shaderData.codes}
  47883. @vertex
  47884. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  47885. // vars
  47886. ${shaderData.vars}
  47887. // flow
  47888. ${shaderData.flow}
  47889. return varyings;
  47890. }
  47891. `;
  47892. }
  47893. /**
  47894. * Returns a WGSL fragment shader based on the given shader data.
  47895. *
  47896. * @private
  47897. * @param {Object} shaderData - The shader data.
  47898. * @return {string} The vertex shader.
  47899. */
  47900. _getWGSLFragmentCode( shaderData ) {
  47901. return `${ this.getSignature() }
  47902. // global
  47903. ${ diagnostics }
  47904. // structs
  47905. ${shaderData.structs}
  47906. // uniforms
  47907. ${shaderData.uniforms}
  47908. // codes
  47909. ${shaderData.codes}
  47910. @fragment
  47911. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  47912. // vars
  47913. ${shaderData.vars}
  47914. // flow
  47915. ${shaderData.flow}
  47916. }
  47917. `;
  47918. }
  47919. /**
  47920. * Returns a WGSL compute shader based on the given shader data.
  47921. *
  47922. * @private
  47923. * @param {Object} shaderData - The shader data.
  47924. * @param {string} workgroupSize - The workgroup size.
  47925. * @return {string} The vertex shader.
  47926. */
  47927. _getWGSLComputeCode( shaderData, workgroupSize ) {
  47928. return `${ this.getSignature() }
  47929. // directives
  47930. ${shaderData.directives}
  47931. // system
  47932. var<private> instanceIndex : u32;
  47933. // locals
  47934. ${shaderData.scopedArrays}
  47935. // structs
  47936. ${shaderData.structs}
  47937. // uniforms
  47938. ${shaderData.uniforms}
  47939. // codes
  47940. ${shaderData.codes}
  47941. @compute @workgroup_size( ${workgroupSize} )
  47942. fn main( ${shaderData.attributes} ) {
  47943. // system
  47944. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  47945. // vars
  47946. ${shaderData.vars}
  47947. // flow
  47948. ${shaderData.flow}
  47949. }
  47950. `;
  47951. }
  47952. /**
  47953. * Returns a WGSL struct based on the given name and variables.
  47954. *
  47955. * @private
  47956. * @param {string} name - The struct name.
  47957. * @param {string} vars - The struct variables.
  47958. * @return {string} The WGSL snippet representing a struct.
  47959. */
  47960. _getWGSLStruct( name, vars ) {
  47961. return `
  47962. struct ${name} {
  47963. ${vars}
  47964. };`;
  47965. }
  47966. /**
  47967. * Returns a WGSL struct binding.
  47968. *
  47969. * @private
  47970. * @param {string} name - The struct name.
  47971. * @param {string} vars - The struct variables.
  47972. * @param {string} access - The access.
  47973. * @param {number} [binding=0] - The binding index.
  47974. * @param {number} [group=0] - The group index.
  47975. * @return {string} The WGSL snippet representing a struct binding.
  47976. */
  47977. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  47978. const structName = name + 'Struct';
  47979. const structSnippet = this._getWGSLStruct( structName, vars );
  47980. return `${structSnippet}
  47981. @binding( ${ binding } ) @group( ${ group } )
  47982. var<${access}> ${ name } : ${ structName };`;
  47983. }
  47984. }
  47985. /**
  47986. * A WebGPU backend utility module with common helpers.
  47987. *
  47988. * @private
  47989. */
  47990. class WebGPUUtils {
  47991. /**
  47992. * Constructs a new utility object.
  47993. *
  47994. * @param {WebGPUBackend} backend - The WebGPU backend.
  47995. */
  47996. constructor( backend ) {
  47997. /**
  47998. * A reference to the WebGPU backend.
  47999. *
  48000. * @type {WebGPUBackend}
  48001. */
  48002. this.backend = backend;
  48003. }
  48004. /**
  48005. * Returns the depth/stencil GPU format for the given render context.
  48006. *
  48007. * @param {RenderContext} renderContext - The render context.
  48008. * @return {string} The depth/stencil GPU texture format.
  48009. */
  48010. getCurrentDepthStencilFormat( renderContext ) {
  48011. let format;
  48012. if ( renderContext.depthTexture !== null ) {
  48013. format = this.getTextureFormatGPU( renderContext.depthTexture );
  48014. } else if ( renderContext.depth && renderContext.stencil ) {
  48015. format = GPUTextureFormat.Depth24PlusStencil8;
  48016. } else if ( renderContext.depth ) {
  48017. format = GPUTextureFormat.Depth24Plus;
  48018. }
  48019. return format;
  48020. }
  48021. /**
  48022. * Returns the GPU format for the given texture.
  48023. *
  48024. * @param {Texture} texture - The texture.
  48025. * @return {string} The GPU texture format.
  48026. */
  48027. getTextureFormatGPU( texture ) {
  48028. return this.backend.get( texture ).format;
  48029. }
  48030. /**
  48031. * Returns an object that defines the multi-sampling state of the given texture.
  48032. *
  48033. * @param {Texture} texture - The texture.
  48034. * @return {Object} The multi-sampling state.
  48035. */
  48036. getTextureSampleData( texture ) {
  48037. let samples;
  48038. if ( texture.isFramebufferTexture ) {
  48039. samples = 1;
  48040. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  48041. const renderer = this.backend.renderer;
  48042. const renderTarget = renderer.getRenderTarget();
  48043. samples = renderTarget ? renderTarget.samples : renderer.samples;
  48044. } else if ( texture.renderTarget ) {
  48045. samples = texture.renderTarget.samples;
  48046. }
  48047. samples = samples || 1;
  48048. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  48049. const primarySamples = isMSAA ? 1 : samples;
  48050. return { samples, primarySamples, isMSAA };
  48051. }
  48052. /**
  48053. * Returns the default color attachment's GPU format of the current render context.
  48054. *
  48055. * @param {RenderContext} renderContext - The render context.
  48056. * @return {string} The GPU texture format of the default color attachment.
  48057. */
  48058. getCurrentColorFormat( renderContext ) {
  48059. let format;
  48060. if ( renderContext.textures !== null ) {
  48061. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  48062. } else {
  48063. format = this.getPreferredCanvasFormat(); // default context format
  48064. }
  48065. return format;
  48066. }
  48067. /**
  48068. * Returns the output color space of the current render context.
  48069. *
  48070. * @param {RenderContext} renderContext - The render context.
  48071. * @return {string} The output color space.
  48072. */
  48073. getCurrentColorSpace( renderContext ) {
  48074. if ( renderContext.textures !== null ) {
  48075. return renderContext.textures[ 0 ].colorSpace;
  48076. }
  48077. return this.backend.renderer.outputColorSpace;
  48078. }
  48079. /**
  48080. * Returns GPU primitive topology for the given object and material.
  48081. *
  48082. * @param {Object3D} object - The 3D object.
  48083. * @param {Material} material - The material.
  48084. * @return {string} The GPU primitive topology.
  48085. */
  48086. getPrimitiveTopology( object, material ) {
  48087. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  48088. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  48089. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  48090. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  48091. }
  48092. /**
  48093. * Returns a modified sample count from the given sample count value.
  48094. *
  48095. * That is required since WebGPU does not support arbitrary sample counts.
  48096. *
  48097. * @param {number} sampleCount - The input sample count.
  48098. * @return {number} The (potentially updated) output sample count.
  48099. */
  48100. getSampleCount( sampleCount ) {
  48101. let count = 1;
  48102. if ( sampleCount > 1 ) {
  48103. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  48104. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  48105. if ( count === 2 ) {
  48106. count = 4;
  48107. }
  48108. }
  48109. return count;
  48110. }
  48111. /**
  48112. * Returns the sample count of the given render context.
  48113. *
  48114. * @param {RenderContext} renderContext - The render context.
  48115. * @return {number} The sample count.
  48116. */
  48117. getSampleCountRenderContext( renderContext ) {
  48118. if ( renderContext.textures !== null ) {
  48119. return this.getSampleCount( renderContext.sampleCount );
  48120. }
  48121. return this.getSampleCount( this.backend.renderer.samples );
  48122. }
  48123. /**
  48124. * Returns the preferred canvas format.
  48125. *
  48126. * There is a separate method for this so it's possible to
  48127. * honor edge cases for specific devices.
  48128. *
  48129. * @return {string} The GPU texture format of the canvas.
  48130. */
  48131. getPreferredCanvasFormat() {
  48132. const outputType = this.backend.parameters.outputType;
  48133. if ( outputType === undefined ) {
  48134. return navigator.gpu.getPreferredCanvasFormat();
  48135. } else if ( outputType === UnsignedByteType ) {
  48136. return GPUTextureFormat.BGRA8Unorm;
  48137. } else if ( outputType === HalfFloatType ) {
  48138. return GPUTextureFormat.RGBA16Float;
  48139. } else {
  48140. throw new Error( 'Unsupported outputType' );
  48141. }
  48142. }
  48143. }
  48144. const typedArraysToVertexFormatPrefix = new Map( [
  48145. [ Int8Array, [ 'sint8', 'snorm8' ]],
  48146. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  48147. [ Int16Array, [ 'sint16', 'snorm16' ]],
  48148. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  48149. [ Int32Array, [ 'sint32', 'snorm32' ]],
  48150. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  48151. [ Float32Array, [ 'float32', ]],
  48152. ] );
  48153. const typedAttributeToVertexFormatPrefix = new Map( [
  48154. [ Float16BufferAttribute, [ 'float16', ]],
  48155. ] );
  48156. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  48157. [ Int32Array, 'sint32' ],
  48158. [ Int16Array, 'sint32' ], // patch for INT16
  48159. [ Uint32Array, 'uint32' ],
  48160. [ Uint16Array, 'uint32' ], // patch for UINT16
  48161. [ Float32Array, 'float32' ]
  48162. ] );
  48163. /**
  48164. * A WebGPU backend utility module for managing shader attributes.
  48165. *
  48166. * @private
  48167. */
  48168. class WebGPUAttributeUtils {
  48169. /**
  48170. * Constructs a new utility object.
  48171. *
  48172. * @param {WebGPUBackend} backend - The WebGPU backend.
  48173. */
  48174. constructor( backend ) {
  48175. /**
  48176. * A reference to the WebGPU backend.
  48177. *
  48178. * @type {WebGPUBackend}
  48179. */
  48180. this.backend = backend;
  48181. }
  48182. /**
  48183. * Creates the GPU buffer for the given buffer attribute.
  48184. *
  48185. * @param {BufferAttribute} attribute - The buffer attribute.
  48186. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  48187. */
  48188. createAttribute( attribute, usage ) {
  48189. const bufferAttribute = this._getBufferAttribute( attribute );
  48190. const backend = this.backend;
  48191. const bufferData = backend.get( bufferAttribute );
  48192. let buffer = bufferData.buffer;
  48193. if ( buffer === undefined ) {
  48194. const device = backend.device;
  48195. let array = bufferAttribute.array;
  48196. // patch for INT16 and UINT16
  48197. if ( attribute.normalized === false ) {
  48198. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  48199. array = new Int32Array( array );
  48200. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  48201. array = new Uint32Array( array );
  48202. if ( usage & GPUBufferUsage.INDEX ) {
  48203. for ( let i = 0; i < array.length; i ++ ) {
  48204. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  48205. }
  48206. }
  48207. }
  48208. }
  48209. bufferAttribute.array = array;
  48210. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  48211. array = new array.constructor( bufferAttribute.count * 4 );
  48212. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48213. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48214. }
  48215. // Update BufferAttribute
  48216. bufferAttribute.itemSize = 4;
  48217. bufferAttribute.array = array;
  48218. bufferData._force3to4BytesAlignment = true;
  48219. }
  48220. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  48221. buffer = device.createBuffer( {
  48222. label: bufferAttribute.name,
  48223. size: size,
  48224. usage: usage,
  48225. mappedAtCreation: true
  48226. } );
  48227. new array.constructor( buffer.getMappedRange() ).set( array );
  48228. buffer.unmap();
  48229. bufferData.buffer = buffer;
  48230. }
  48231. }
  48232. /**
  48233. * Updates the GPU buffer of the given buffer attribute.
  48234. *
  48235. * @param {BufferAttribute} attribute - The buffer attribute.
  48236. */
  48237. updateAttribute( attribute ) {
  48238. const bufferAttribute = this._getBufferAttribute( attribute );
  48239. const backend = this.backend;
  48240. const device = backend.device;
  48241. const bufferData = backend.get( bufferAttribute );
  48242. const buffer = backend.get( bufferAttribute ).buffer;
  48243. let array = bufferAttribute.array;
  48244. // if storage buffer ensure 4 byte alignment
  48245. if ( bufferData._force3to4BytesAlignment === true ) {
  48246. array = new array.constructor( bufferAttribute.count * 4 );
  48247. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48248. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48249. }
  48250. bufferAttribute.array = array;
  48251. }
  48252. const isTypedArray = this._isTypedArray( array );
  48253. const updateRanges = bufferAttribute.updateRanges;
  48254. if ( updateRanges.length === 0 ) {
  48255. // Not using update ranges
  48256. device.queue.writeBuffer(
  48257. buffer,
  48258. 0,
  48259. array,
  48260. 0
  48261. );
  48262. } else {
  48263. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  48264. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  48265. const range = updateRanges[ i ];
  48266. let dataOffset, size;
  48267. if ( bufferData._force3to4BytesAlignment === true ) {
  48268. const vertexStart = Math.floor( range.start / 3 );
  48269. const vertexCount = Math.ceil( range.count / 3 );
  48270. dataOffset = vertexStart * 4 * byteOffsetFactor;
  48271. size = vertexCount * 4 * byteOffsetFactor;
  48272. } else {
  48273. dataOffset = range.start * byteOffsetFactor;
  48274. size = range.count * byteOffsetFactor;
  48275. }
  48276. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  48277. device.queue.writeBuffer(
  48278. buffer,
  48279. bufferOffset,
  48280. array,
  48281. dataOffset,
  48282. size
  48283. );
  48284. }
  48285. bufferAttribute.clearUpdateRanges();
  48286. }
  48287. }
  48288. /**
  48289. * This method creates the vertex buffer layout data which are
  48290. * require when creating a render pipeline for the given render object.
  48291. *
  48292. * @param {RenderObject} renderObject - The render object.
  48293. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  48294. */
  48295. createShaderVertexBuffers( renderObject ) {
  48296. const attributes = renderObject.getAttributes();
  48297. const vertexBuffers = new Map();
  48298. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  48299. const geometryAttribute = attributes[ slot ];
  48300. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  48301. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  48302. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  48303. if ( vertexBufferLayout === undefined ) {
  48304. let arrayStride, stepMode;
  48305. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  48306. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  48307. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48308. } else {
  48309. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  48310. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48311. }
  48312. // patch for INT16 and UINT16
  48313. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  48314. arrayStride = 4;
  48315. }
  48316. vertexBufferLayout = {
  48317. arrayStride,
  48318. attributes: [],
  48319. stepMode
  48320. };
  48321. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  48322. }
  48323. const format = this._getVertexFormat( geometryAttribute );
  48324. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  48325. vertexBufferLayout.attributes.push( {
  48326. shaderLocation: slot,
  48327. offset,
  48328. format
  48329. } );
  48330. }
  48331. return Array.from( vertexBuffers.values() );
  48332. }
  48333. /**
  48334. * Destroys the GPU buffer of the given buffer attribute.
  48335. *
  48336. * @param {BufferAttribute} attribute - The buffer attribute.
  48337. */
  48338. destroyAttribute( attribute ) {
  48339. const backend = this.backend;
  48340. const data = backend.get( this._getBufferAttribute( attribute ) );
  48341. data.buffer.destroy();
  48342. backend.delete( attribute );
  48343. }
  48344. /**
  48345. * This method performs a readback operation by moving buffer data from
  48346. * a storage buffer attribute from the GPU to the CPU.
  48347. *
  48348. * @async
  48349. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48350. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48351. */
  48352. async getArrayBufferAsync( attribute ) {
  48353. const backend = this.backend;
  48354. const device = backend.device;
  48355. const data = backend.get( this._getBufferAttribute( attribute ) );
  48356. const bufferGPU = data.buffer;
  48357. const size = bufferGPU.size;
  48358. const readBufferGPU = device.createBuffer( {
  48359. label: `${ attribute.name }_readback`,
  48360. size,
  48361. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48362. } );
  48363. const cmdEncoder = device.createCommandEncoder( {
  48364. label: `readback_encoder_${ attribute.name }`
  48365. } );
  48366. cmdEncoder.copyBufferToBuffer(
  48367. bufferGPU,
  48368. 0,
  48369. readBufferGPU,
  48370. 0,
  48371. size
  48372. );
  48373. const gpuCommands = cmdEncoder.finish();
  48374. device.queue.submit( [ gpuCommands ] );
  48375. await readBufferGPU.mapAsync( GPUMapMode.READ );
  48376. const arrayBuffer = readBufferGPU.getMappedRange();
  48377. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  48378. readBufferGPU.unmap();
  48379. return dstBuffer.buffer;
  48380. }
  48381. /**
  48382. * Returns the vertex format of the given buffer attribute.
  48383. *
  48384. * @private
  48385. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  48386. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  48387. */
  48388. _getVertexFormat( geometryAttribute ) {
  48389. const { itemSize, normalized } = geometryAttribute;
  48390. const ArrayType = geometryAttribute.array.constructor;
  48391. const AttributeType = geometryAttribute.constructor;
  48392. let format;
  48393. if ( itemSize === 1 ) {
  48394. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  48395. } else {
  48396. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  48397. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  48398. if ( prefix ) {
  48399. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  48400. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  48401. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  48402. if ( paddedItemSize % 1 ) {
  48403. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  48404. }
  48405. format = `${prefix}x${paddedItemSize}`;
  48406. }
  48407. }
  48408. if ( ! format ) {
  48409. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  48410. }
  48411. return format;
  48412. }
  48413. /**
  48414. * Returns `true` if the given array is a typed array.
  48415. *
  48416. * @private
  48417. * @param {any} array - The array.
  48418. * @return {boolean} Whether the given array is a typed array or not.
  48419. */
  48420. _isTypedArray( array ) {
  48421. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  48422. }
  48423. /**
  48424. * Utility method for handling interleaved buffer attributes correctly.
  48425. * To process them, their `InterleavedBuffer` is returned.
  48426. *
  48427. * @private
  48428. * @param {BufferAttribute} attribute - The attribute.
  48429. * @return {BufferAttribute|InterleavedBuffer}
  48430. */
  48431. _getBufferAttribute( attribute ) {
  48432. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  48433. return attribute;
  48434. }
  48435. }
  48436. /**
  48437. * A WebGPU backend utility module for managing bindings.
  48438. *
  48439. * When reading the documentation it's helpful to keep in mind that
  48440. * all class definitions starting with 'GPU*' are modules from the
  48441. * WebGPU API. So for example `BindGroup` is a class from the engine
  48442. * whereas `GPUBindGroup` is a class from WebGPU.
  48443. *
  48444. * @private
  48445. */
  48446. class WebGPUBindingUtils {
  48447. /**
  48448. * Constructs a new utility object.
  48449. *
  48450. * @param {WebGPUBackend} backend - The WebGPU backend.
  48451. */
  48452. constructor( backend ) {
  48453. /**
  48454. * A reference to the WebGPU backend.
  48455. *
  48456. * @type {WebGPUBackend}
  48457. */
  48458. this.backend = backend;
  48459. /**
  48460. * A cache for managing bind group layouts.
  48461. *
  48462. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  48463. */
  48464. this.bindGroupLayoutCache = new WeakMap();
  48465. }
  48466. /**
  48467. * Creates a GPU bind group layout for the given bind group.
  48468. *
  48469. * @param {BindGroup} bindGroup - The bind group.
  48470. * @return {GPUBindGroupLayout} The GPU bind group layout.
  48471. */
  48472. createBindingsLayout( bindGroup ) {
  48473. const backend = this.backend;
  48474. const device = backend.device;
  48475. const entries = [];
  48476. let index = 0;
  48477. for ( const binding of bindGroup.bindings ) {
  48478. const bindingGPU = {
  48479. binding: index ++,
  48480. visibility: binding.visibility
  48481. };
  48482. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  48483. const buffer = {}; // GPUBufferBindingLayout
  48484. if ( binding.isStorageBuffer ) {
  48485. if ( binding.visibility & 4 ) {
  48486. // compute
  48487. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  48488. buffer.type = GPUBufferBindingType.Storage;
  48489. } else {
  48490. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  48491. }
  48492. } else {
  48493. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  48494. }
  48495. }
  48496. bindingGPU.buffer = buffer;
  48497. } else if ( binding.isSampler ) {
  48498. const sampler = {}; // GPUSamplerBindingLayout
  48499. if ( binding.texture.isDepthTexture ) {
  48500. if ( binding.texture.compareFunction !== null ) {
  48501. sampler.type = GPUSamplerBindingType.Comparison;
  48502. } else if ( backend.compatibilityMode ) {
  48503. sampler.type = GPUSamplerBindingType.NonFiltering;
  48504. }
  48505. }
  48506. bindingGPU.sampler = sampler;
  48507. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  48508. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  48509. } else if ( binding.isSampledTexture && binding.store ) {
  48510. const storageTexture = {}; // GPUStorageTextureBindingLayout
  48511. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  48512. const access = binding.access;
  48513. if ( access === NodeAccess.READ_WRITE ) {
  48514. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  48515. } else if ( access === NodeAccess.WRITE_ONLY ) {
  48516. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  48517. } else {
  48518. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  48519. }
  48520. bindingGPU.storageTexture = storageTexture;
  48521. } else if ( binding.isSampledTexture ) {
  48522. const texture = {}; // GPUTextureBindingLayout
  48523. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  48524. if ( primarySamples > 1 ) {
  48525. texture.multisampled = true;
  48526. if ( ! binding.texture.isDepthTexture ) {
  48527. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48528. }
  48529. }
  48530. if ( binding.texture.isDepthTexture ) {
  48531. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  48532. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48533. } else {
  48534. texture.sampleType = GPUTextureSampleType.Depth;
  48535. }
  48536. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  48537. const type = binding.texture.type;
  48538. if ( type === IntType ) {
  48539. texture.sampleType = GPUTextureSampleType.SInt;
  48540. } else if ( type === UnsignedIntType ) {
  48541. texture.sampleType = GPUTextureSampleType.UInt;
  48542. } else if ( type === FloatType ) {
  48543. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  48544. texture.sampleType = GPUTextureSampleType.Float;
  48545. } else {
  48546. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48547. }
  48548. }
  48549. }
  48550. if ( binding.isSampledCubeTexture ) {
  48551. texture.viewDimension = GPUTextureViewDimension.Cube;
  48552. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  48553. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  48554. } else if ( binding.isSampledTexture3D ) {
  48555. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  48556. }
  48557. bindingGPU.texture = texture;
  48558. } else {
  48559. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  48560. }
  48561. entries.push( bindingGPU );
  48562. }
  48563. return device.createBindGroupLayout( { entries } );
  48564. }
  48565. /**
  48566. * Creates bindings from the given bind group definition.
  48567. *
  48568. * @param {BindGroup} bindGroup - The bind group.
  48569. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48570. * @param {number} cacheIndex - The cache index.
  48571. * @param {number} version - The version.
  48572. */
  48573. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  48574. const { backend, bindGroupLayoutCache } = this;
  48575. const bindingsData = backend.get( bindGroup );
  48576. // setup (static) binding layout and (dynamic) binding group
  48577. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  48578. if ( bindLayoutGPU === undefined ) {
  48579. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  48580. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  48581. }
  48582. let bindGroupGPU;
  48583. if ( cacheIndex > 0 ) {
  48584. if ( bindingsData.groups === undefined ) {
  48585. bindingsData.groups = [];
  48586. bindingsData.versions = [];
  48587. }
  48588. if ( bindingsData.versions[ cacheIndex ] === version ) {
  48589. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  48590. }
  48591. }
  48592. if ( bindGroupGPU === undefined ) {
  48593. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  48594. if ( cacheIndex > 0 ) {
  48595. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  48596. bindingsData.versions[ cacheIndex ] = version;
  48597. }
  48598. }
  48599. bindingsData.group = bindGroupGPU;
  48600. bindingsData.layout = bindLayoutGPU;
  48601. }
  48602. /**
  48603. * Updates a buffer binding.
  48604. *
  48605. * @param {Buffer} binding - The buffer binding to update.
  48606. */
  48607. updateBinding( binding ) {
  48608. const backend = this.backend;
  48609. const device = backend.device;
  48610. const buffer = binding.buffer;
  48611. const bufferGPU = backend.get( binding ).buffer;
  48612. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  48613. }
  48614. /**
  48615. * Creates a GPU bind group for the camera index.
  48616. *
  48617. * @param {Uint32Array} data - The index data.
  48618. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  48619. * @return {GPUBindGroup} The GPU bind group.
  48620. */
  48621. createBindGroupIndex( data, layout ) {
  48622. const backend = this.backend;
  48623. const device = backend.device;
  48624. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  48625. const index = data[ 0 ];
  48626. const buffer = device.createBuffer( {
  48627. label: 'bindingCameraIndex_' + index,
  48628. size: 16, // uint(4) * 4
  48629. usage: usage
  48630. } );
  48631. device.queue.writeBuffer( buffer, 0, data, 0 );
  48632. const entries = [ { binding: 0, resource: { buffer } } ];
  48633. return device.createBindGroup( {
  48634. label: 'bindGroupCameraIndex_' + index,
  48635. layout,
  48636. entries
  48637. } );
  48638. }
  48639. /**
  48640. * Creates a GPU bind group for the given bind group and GPU layout.
  48641. *
  48642. * @param {BindGroup} bindGroup - The bind group.
  48643. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  48644. * @return {GPUBindGroup} The GPU bind group.
  48645. */
  48646. createBindGroup( bindGroup, layoutGPU ) {
  48647. const backend = this.backend;
  48648. const device = backend.device;
  48649. let bindingPoint = 0;
  48650. const entriesGPU = [];
  48651. for ( const binding of bindGroup.bindings ) {
  48652. if ( binding.isUniformBuffer ) {
  48653. const bindingData = backend.get( binding );
  48654. if ( bindingData.buffer === undefined ) {
  48655. const byteLength = binding.byteLength;
  48656. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  48657. const bufferGPU = device.createBuffer( {
  48658. label: 'bindingBuffer_' + binding.name,
  48659. size: byteLength,
  48660. usage: usage
  48661. } );
  48662. bindingData.buffer = bufferGPU;
  48663. }
  48664. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  48665. } else if ( binding.isStorageBuffer ) {
  48666. const bindingData = backend.get( binding );
  48667. if ( bindingData.buffer === undefined ) {
  48668. const attribute = binding.attribute;
  48669. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  48670. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  48671. bindingData.buffer = backend.get( attribute ).buffer;
  48672. }
  48673. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  48674. } else if ( binding.isSampler ) {
  48675. const textureGPU = backend.get( binding.texture );
  48676. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  48677. } else if ( binding.isSampledTexture ) {
  48678. const textureData = backend.get( binding.texture );
  48679. let resourceGPU;
  48680. if ( textureData.externalTexture !== undefined ) {
  48681. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  48682. } else {
  48683. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  48684. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  48685. resourceGPU = textureData[ propertyName ];
  48686. if ( resourceGPU === undefined ) {
  48687. const aspectGPU = GPUTextureAspect.All;
  48688. let dimensionViewGPU;
  48689. if ( binding.isSampledCubeTexture ) {
  48690. dimensionViewGPU = GPUTextureViewDimension.Cube;
  48691. } else if ( binding.isSampledTexture3D ) {
  48692. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  48693. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  48694. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  48695. } else {
  48696. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  48697. }
  48698. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  48699. }
  48700. }
  48701. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  48702. }
  48703. bindingPoint ++;
  48704. }
  48705. return device.createBindGroup( {
  48706. label: 'bindGroup_' + bindGroup.name,
  48707. layout: layoutGPU,
  48708. entries: entriesGPU
  48709. } );
  48710. }
  48711. }
  48712. /**
  48713. * A WebGPU backend utility module for managing pipelines.
  48714. *
  48715. * @private
  48716. */
  48717. class WebGPUPipelineUtils {
  48718. /**
  48719. * Constructs a new utility object.
  48720. *
  48721. * @param {WebGPUBackend} backend - The WebGPU backend.
  48722. */
  48723. constructor( backend ) {
  48724. /**
  48725. * A reference to the WebGPU backend.
  48726. *
  48727. * @type {WebGPUBackend}
  48728. */
  48729. this.backend = backend;
  48730. }
  48731. /**
  48732. * Returns the sample count derived from the given render context.
  48733. *
  48734. * @private
  48735. * @param {RenderContext} renderContext - The render context.
  48736. * @return {number} The sample count.
  48737. */
  48738. _getSampleCount( renderContext ) {
  48739. return this.backend.utils.getSampleCountRenderContext( renderContext );
  48740. }
  48741. /**
  48742. * Creates a render pipeline for the given render object.
  48743. *
  48744. * @param {RenderObject} renderObject - The render object.
  48745. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  48746. */
  48747. createRenderPipeline( renderObject, promises ) {
  48748. const { object, material, geometry, pipeline } = renderObject;
  48749. const { vertexProgram, fragmentProgram } = pipeline;
  48750. const backend = this.backend;
  48751. const device = backend.device;
  48752. const utils = backend.utils;
  48753. const pipelineData = backend.get( pipeline );
  48754. // bind group layouts
  48755. const bindGroupLayouts = [];
  48756. for ( const bindGroup of renderObject.getBindings() ) {
  48757. const bindingsData = backend.get( bindGroup );
  48758. bindGroupLayouts.push( bindingsData.layout );
  48759. }
  48760. // vertex buffers
  48761. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  48762. // blending
  48763. let blending;
  48764. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  48765. blending = this._getBlending( material );
  48766. }
  48767. // stencil
  48768. let stencilFront = {};
  48769. if ( material.stencilWrite === true ) {
  48770. stencilFront = {
  48771. compare: this._getStencilCompare( material ),
  48772. failOp: this._getStencilOperation( material.stencilFail ),
  48773. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  48774. passOp: this._getStencilOperation( material.stencilZPass )
  48775. };
  48776. }
  48777. const colorWriteMask = this._getColorWriteMask( material );
  48778. const targets = [];
  48779. if ( renderObject.context.textures !== null ) {
  48780. const textures = renderObject.context.textures;
  48781. for ( let i = 0; i < textures.length; i ++ ) {
  48782. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  48783. targets.push( {
  48784. format: colorFormat,
  48785. blend: blending,
  48786. writeMask: colorWriteMask
  48787. } );
  48788. }
  48789. } else {
  48790. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  48791. targets.push( {
  48792. format: colorFormat,
  48793. blend: blending,
  48794. writeMask: colorWriteMask
  48795. } );
  48796. }
  48797. const vertexModule = backend.get( vertexProgram ).module;
  48798. const fragmentModule = backend.get( fragmentProgram ).module;
  48799. const primitiveState = this._getPrimitiveState( object, geometry, material );
  48800. const depthCompare = this._getDepthCompare( material );
  48801. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  48802. const sampleCount = this._getSampleCount( renderObject.context );
  48803. const pipelineDescriptor = {
  48804. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  48805. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  48806. fragment: Object.assign( {}, fragmentModule, { targets } ),
  48807. primitive: primitiveState,
  48808. multisample: {
  48809. count: sampleCount,
  48810. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  48811. },
  48812. layout: device.createPipelineLayout( {
  48813. bindGroupLayouts
  48814. } )
  48815. };
  48816. const depthStencil = {};
  48817. const renderDepth = renderObject.context.depth;
  48818. const renderStencil = renderObject.context.stencil;
  48819. if ( renderDepth === true || renderStencil === true ) {
  48820. if ( renderDepth === true ) {
  48821. depthStencil.format = depthStencilFormat;
  48822. depthStencil.depthWriteEnabled = material.depthWrite;
  48823. depthStencil.depthCompare = depthCompare;
  48824. }
  48825. if ( renderStencil === true ) {
  48826. depthStencil.stencilFront = stencilFront;
  48827. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  48828. depthStencil.stencilReadMask = material.stencilFuncMask;
  48829. depthStencil.stencilWriteMask = material.stencilWriteMask;
  48830. }
  48831. if ( material.polygonOffset === true ) {
  48832. depthStencil.depthBias = material.polygonOffsetUnits;
  48833. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  48834. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  48835. }
  48836. pipelineDescriptor.depthStencil = depthStencil;
  48837. }
  48838. if ( promises === null ) {
  48839. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  48840. } else {
  48841. const p = new Promise( ( resolve /*, reject*/ ) => {
  48842. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  48843. pipelineData.pipeline = pipeline;
  48844. resolve();
  48845. } );
  48846. } );
  48847. promises.push( p );
  48848. }
  48849. }
  48850. /**
  48851. * Creates GPU render bundle encoder for the given render context.
  48852. *
  48853. * @param {RenderContext} renderContext - The render context.
  48854. * @param {?string} [label='renderBundleEncoder'] - The label.
  48855. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  48856. */
  48857. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  48858. const backend = this.backend;
  48859. const { utils, device } = backend;
  48860. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  48861. const colorFormat = utils.getCurrentColorFormat( renderContext );
  48862. const sampleCount = this._getSampleCount( renderContext );
  48863. const descriptor = {
  48864. label: label,
  48865. colorFormats: [ colorFormat ],
  48866. depthStencilFormat,
  48867. sampleCount
  48868. };
  48869. return device.createRenderBundleEncoder( descriptor );
  48870. }
  48871. /**
  48872. * Creates a compute pipeline for the given compute node.
  48873. *
  48874. * @param {ComputePipeline} pipeline - The compute pipeline.
  48875. * @param {Array<BindGroup>} bindings - The bindings.
  48876. */
  48877. createComputePipeline( pipeline, bindings ) {
  48878. const backend = this.backend;
  48879. const device = backend.device;
  48880. const computeProgram = backend.get( pipeline.computeProgram ).module;
  48881. const pipelineGPU = backend.get( pipeline );
  48882. // bind group layouts
  48883. const bindGroupLayouts = [];
  48884. for ( const bindingsGroup of bindings ) {
  48885. const bindingsData = backend.get( bindingsGroup );
  48886. bindGroupLayouts.push( bindingsData.layout );
  48887. }
  48888. pipelineGPU.pipeline = device.createComputePipeline( {
  48889. compute: computeProgram,
  48890. layout: device.createPipelineLayout( {
  48891. bindGroupLayouts
  48892. } )
  48893. } );
  48894. }
  48895. /**
  48896. * Returns the blending state as a descriptor object required
  48897. * for the pipeline creation.
  48898. *
  48899. * @private
  48900. * @param {Material} material - The material.
  48901. * @return {Object} The blending state.
  48902. */
  48903. _getBlending( material ) {
  48904. let color, alpha;
  48905. const blending = material.blending;
  48906. const blendSrc = material.blendSrc;
  48907. const blendDst = material.blendDst;
  48908. const blendEquation = material.blendEquation;
  48909. if ( blending === CustomBlending ) {
  48910. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  48911. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  48912. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  48913. color = {
  48914. srcFactor: this._getBlendFactor( blendSrc ),
  48915. dstFactor: this._getBlendFactor( blendDst ),
  48916. operation: this._getBlendOperation( blendEquation )
  48917. };
  48918. alpha = {
  48919. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  48920. dstFactor: this._getBlendFactor( blendDstAlpha ),
  48921. operation: this._getBlendOperation( blendEquationAlpha )
  48922. };
  48923. } else {
  48924. const premultipliedAlpha = material.premultipliedAlpha;
  48925. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  48926. color = {
  48927. srcFactor: srcRGB,
  48928. dstFactor: dstRGB,
  48929. operation: GPUBlendOperation.Add
  48930. };
  48931. alpha = {
  48932. srcFactor: srcAlpha,
  48933. dstFactor: dstAlpha,
  48934. operation: GPUBlendOperation.Add
  48935. };
  48936. };
  48937. if ( premultipliedAlpha ) {
  48938. switch ( blending ) {
  48939. case NormalBlending:
  48940. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  48941. break;
  48942. case AdditiveBlending:
  48943. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  48944. break;
  48945. case SubtractiveBlending:
  48946. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  48947. break;
  48948. case MultiplyBlending:
  48949. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  48950. break;
  48951. }
  48952. } else {
  48953. switch ( blending ) {
  48954. case NormalBlending:
  48955. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  48956. break;
  48957. case AdditiveBlending:
  48958. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  48959. break;
  48960. case SubtractiveBlending:
  48961. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  48962. break;
  48963. case MultiplyBlending:
  48964. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  48965. break;
  48966. }
  48967. }
  48968. }
  48969. if ( color !== undefined && alpha !== undefined ) {
  48970. return { color, alpha };
  48971. } else {
  48972. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  48973. }
  48974. }
  48975. /**
  48976. * Returns the GPU blend factor which is required for the pipeline creation.
  48977. *
  48978. * @private
  48979. * @param {number} blend - The blend factor as a three.js constant.
  48980. * @return {string} The GPU blend factor.
  48981. */
  48982. _getBlendFactor( blend ) {
  48983. let blendFactor;
  48984. switch ( blend ) {
  48985. case ZeroFactor:
  48986. blendFactor = GPUBlendFactor.Zero;
  48987. break;
  48988. case OneFactor:
  48989. blendFactor = GPUBlendFactor.One;
  48990. break;
  48991. case SrcColorFactor:
  48992. blendFactor = GPUBlendFactor.Src;
  48993. break;
  48994. case OneMinusSrcColorFactor:
  48995. blendFactor = GPUBlendFactor.OneMinusSrc;
  48996. break;
  48997. case SrcAlphaFactor:
  48998. blendFactor = GPUBlendFactor.SrcAlpha;
  48999. break;
  49000. case OneMinusSrcAlphaFactor:
  49001. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  49002. break;
  49003. case DstColorFactor:
  49004. blendFactor = GPUBlendFactor.Dst;
  49005. break;
  49006. case OneMinusDstColorFactor:
  49007. blendFactor = GPUBlendFactor.OneMinusDstColor;
  49008. break;
  49009. case DstAlphaFactor:
  49010. blendFactor = GPUBlendFactor.DstAlpha;
  49011. break;
  49012. case OneMinusDstAlphaFactor:
  49013. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  49014. break;
  49015. case SrcAlphaSaturateFactor:
  49016. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  49017. break;
  49018. case BlendColorFactor:
  49019. blendFactor = GPUBlendFactor.Constant;
  49020. break;
  49021. case OneMinusBlendColorFactor:
  49022. blendFactor = GPUBlendFactor.OneMinusConstant;
  49023. break;
  49024. default:
  49025. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  49026. }
  49027. return blendFactor;
  49028. }
  49029. /**
  49030. * Returns the GPU stencil compare function which is required for the pipeline creation.
  49031. *
  49032. * @private
  49033. * @param {Material} material - The material.
  49034. * @return {string} The GPU stencil compare function.
  49035. */
  49036. _getStencilCompare( material ) {
  49037. let stencilCompare;
  49038. const stencilFunc = material.stencilFunc;
  49039. switch ( stencilFunc ) {
  49040. case NeverStencilFunc:
  49041. stencilCompare = GPUCompareFunction.Never;
  49042. break;
  49043. case AlwaysStencilFunc:
  49044. stencilCompare = GPUCompareFunction.Always;
  49045. break;
  49046. case LessStencilFunc:
  49047. stencilCompare = GPUCompareFunction.Less;
  49048. break;
  49049. case LessEqualStencilFunc:
  49050. stencilCompare = GPUCompareFunction.LessEqual;
  49051. break;
  49052. case EqualStencilFunc:
  49053. stencilCompare = GPUCompareFunction.Equal;
  49054. break;
  49055. case GreaterEqualStencilFunc:
  49056. stencilCompare = GPUCompareFunction.GreaterEqual;
  49057. break;
  49058. case GreaterStencilFunc:
  49059. stencilCompare = GPUCompareFunction.Greater;
  49060. break;
  49061. case NotEqualStencilFunc:
  49062. stencilCompare = GPUCompareFunction.NotEqual;
  49063. break;
  49064. default:
  49065. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  49066. }
  49067. return stencilCompare;
  49068. }
  49069. /**
  49070. * Returns the GPU stencil operation which is required for the pipeline creation.
  49071. *
  49072. * @private
  49073. * @param {number} op - A three.js constant defining the stencil operation.
  49074. * @return {string} The GPU stencil operation.
  49075. */
  49076. _getStencilOperation( op ) {
  49077. let stencilOperation;
  49078. switch ( op ) {
  49079. case KeepStencilOp:
  49080. stencilOperation = GPUStencilOperation.Keep;
  49081. break;
  49082. case ZeroStencilOp:
  49083. stencilOperation = GPUStencilOperation.Zero;
  49084. break;
  49085. case ReplaceStencilOp:
  49086. stencilOperation = GPUStencilOperation.Replace;
  49087. break;
  49088. case InvertStencilOp:
  49089. stencilOperation = GPUStencilOperation.Invert;
  49090. break;
  49091. case IncrementStencilOp:
  49092. stencilOperation = GPUStencilOperation.IncrementClamp;
  49093. break;
  49094. case DecrementStencilOp:
  49095. stencilOperation = GPUStencilOperation.DecrementClamp;
  49096. break;
  49097. case IncrementWrapStencilOp:
  49098. stencilOperation = GPUStencilOperation.IncrementWrap;
  49099. break;
  49100. case DecrementWrapStencilOp:
  49101. stencilOperation = GPUStencilOperation.DecrementWrap;
  49102. break;
  49103. default:
  49104. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  49105. }
  49106. return stencilOperation;
  49107. }
  49108. /**
  49109. * Returns the GPU blend operation which is required for the pipeline creation.
  49110. *
  49111. * @private
  49112. * @param {number} blendEquation - A three.js constant defining the blend equation.
  49113. * @return {string} The GPU blend operation.
  49114. */
  49115. _getBlendOperation( blendEquation ) {
  49116. let blendOperation;
  49117. switch ( blendEquation ) {
  49118. case AddEquation:
  49119. blendOperation = GPUBlendOperation.Add;
  49120. break;
  49121. case SubtractEquation:
  49122. blendOperation = GPUBlendOperation.Subtract;
  49123. break;
  49124. case ReverseSubtractEquation:
  49125. blendOperation = GPUBlendOperation.ReverseSubtract;
  49126. break;
  49127. case MinEquation:
  49128. blendOperation = GPUBlendOperation.Min;
  49129. break;
  49130. case MaxEquation:
  49131. blendOperation = GPUBlendOperation.Max;
  49132. break;
  49133. default:
  49134. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  49135. }
  49136. return blendOperation;
  49137. }
  49138. /**
  49139. * Returns the primitive state as a descriptor object required
  49140. * for the pipeline creation.
  49141. *
  49142. * @private
  49143. * @param {Object3D} object - The 3D object.
  49144. * @param {BufferGeometry} geometry - The geometry.
  49145. * @param {Material} material - The material.
  49146. * @return {Object} The primitive state.
  49147. */
  49148. _getPrimitiveState( object, geometry, material ) {
  49149. const descriptor = {};
  49150. const utils = this.backend.utils;
  49151. descriptor.topology = utils.getPrimitiveTopology( object, material );
  49152. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  49153. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  49154. }
  49155. switch ( material.side ) {
  49156. case FrontSide:
  49157. descriptor.frontFace = GPUFrontFace.CCW;
  49158. descriptor.cullMode = GPUCullMode.Back;
  49159. break;
  49160. case BackSide:
  49161. descriptor.frontFace = GPUFrontFace.CCW;
  49162. descriptor.cullMode = GPUCullMode.Front;
  49163. break;
  49164. case DoubleSide:
  49165. descriptor.frontFace = GPUFrontFace.CCW;
  49166. descriptor.cullMode = GPUCullMode.None;
  49167. break;
  49168. default:
  49169. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  49170. break;
  49171. }
  49172. return descriptor;
  49173. }
  49174. /**
  49175. * Returns the GPU color write mask which is required for the pipeline creation.
  49176. *
  49177. * @private
  49178. * @param {Material} material - The material.
  49179. * @return {string} The GPU color write mask.
  49180. */
  49181. _getColorWriteMask( material ) {
  49182. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  49183. }
  49184. /**
  49185. * Returns the GPU depth compare function which is required for the pipeline creation.
  49186. *
  49187. * @private
  49188. * @param {Material} material - The material.
  49189. * @return {string} The GPU depth compare function.
  49190. */
  49191. _getDepthCompare( material ) {
  49192. let depthCompare;
  49193. if ( material.depthTest === false ) {
  49194. depthCompare = GPUCompareFunction.Always;
  49195. } else {
  49196. const depthFunc = material.depthFunc;
  49197. switch ( depthFunc ) {
  49198. case NeverDepth:
  49199. depthCompare = GPUCompareFunction.Never;
  49200. break;
  49201. case AlwaysDepth:
  49202. depthCompare = GPUCompareFunction.Always;
  49203. break;
  49204. case LessDepth:
  49205. depthCompare = GPUCompareFunction.Less;
  49206. break;
  49207. case LessEqualDepth:
  49208. depthCompare = GPUCompareFunction.LessEqual;
  49209. break;
  49210. case EqualDepth:
  49211. depthCompare = GPUCompareFunction.Equal;
  49212. break;
  49213. case GreaterEqualDepth:
  49214. depthCompare = GPUCompareFunction.GreaterEqual;
  49215. break;
  49216. case GreaterDepth:
  49217. depthCompare = GPUCompareFunction.Greater;
  49218. break;
  49219. case NotEqualDepth:
  49220. depthCompare = GPUCompareFunction.NotEqual;
  49221. break;
  49222. default:
  49223. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  49224. }
  49225. }
  49226. return depthCompare;
  49227. }
  49228. }
  49229. /**
  49230. * Manages a pool of WebGPU timestamp queries for performance measurement.
  49231. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  49232. *
  49233. * @augments TimestampQueryPool
  49234. */
  49235. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  49236. /**
  49237. * Creates a new WebGPU timestamp query pool.
  49238. *
  49239. * @param {GPUDevice} device - The WebGPU device to create queries on.
  49240. * @param {string} type - The type identifier for this query pool.
  49241. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  49242. */
  49243. constructor( device, type, maxQueries = 2048 ) {
  49244. super( maxQueries );
  49245. this.device = device;
  49246. this.type = type;
  49247. this.querySet = this.device.createQuerySet( {
  49248. type: 'timestamp',
  49249. count: this.maxQueries,
  49250. label: `queryset_global_timestamp_${type}`
  49251. } );
  49252. const bufferSize = this.maxQueries * 8;
  49253. this.resolveBuffer = this.device.createBuffer( {
  49254. label: `buffer_timestamp_resolve_${type}`,
  49255. size: bufferSize,
  49256. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  49257. } );
  49258. this.resultBuffer = this.device.createBuffer( {
  49259. label: `buffer_timestamp_result_${type}`,
  49260. size: bufferSize,
  49261. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49262. } );
  49263. }
  49264. /**
  49265. * Allocates a pair of queries for a given render context.
  49266. *
  49267. * @param {Object} renderContext - The render context to allocate queries for.
  49268. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  49269. */
  49270. allocateQueriesForContext( renderContext ) {
  49271. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  49272. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  49273. 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() } ).` );
  49274. return null;
  49275. }
  49276. const baseOffset = this.currentQueryIndex;
  49277. this.currentQueryIndex += 2;
  49278. this.queryOffsets.set( renderContext.id, baseOffset );
  49279. return baseOffset;
  49280. }
  49281. /**
  49282. * Asynchronously resolves all pending queries and returns the total duration.
  49283. * If there's already a pending resolve operation, returns that promise instead.
  49284. *
  49285. * @async
  49286. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  49287. */
  49288. async resolveQueriesAsync() {
  49289. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  49290. return this.lastValue;
  49291. }
  49292. if ( this.pendingResolve ) {
  49293. return this.pendingResolve;
  49294. }
  49295. this.pendingResolve = this._resolveQueries();
  49296. try {
  49297. const result = await this.pendingResolve;
  49298. return result;
  49299. } finally {
  49300. this.pendingResolve = null;
  49301. }
  49302. }
  49303. /**
  49304. * Internal method to resolve queries and calculate total duration.
  49305. *
  49306. * @async
  49307. * @private
  49308. * @returns {Promise<number>} The total duration in milliseconds.
  49309. */
  49310. async _resolveQueries() {
  49311. if ( this.isDisposed ) {
  49312. return this.lastValue;
  49313. }
  49314. try {
  49315. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49316. return this.lastValue;
  49317. }
  49318. const currentOffsets = new Map( this.queryOffsets );
  49319. const queryCount = this.currentQueryIndex;
  49320. const bytesUsed = queryCount * 8;
  49321. // Reset state before GPU work
  49322. this.currentQueryIndex = 0;
  49323. this.queryOffsets.clear();
  49324. const commandEncoder = this.device.createCommandEncoder();
  49325. commandEncoder.resolveQuerySet(
  49326. this.querySet,
  49327. 0,
  49328. queryCount,
  49329. this.resolveBuffer,
  49330. 0
  49331. );
  49332. commandEncoder.copyBufferToBuffer(
  49333. this.resolveBuffer,
  49334. 0,
  49335. this.resultBuffer,
  49336. 0,
  49337. bytesUsed
  49338. );
  49339. const commandBuffer = commandEncoder.finish();
  49340. this.device.queue.submit( [ commandBuffer ] );
  49341. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49342. return this.lastValue;
  49343. }
  49344. // Create and track the mapping operation
  49345. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  49346. if ( this.isDisposed ) {
  49347. if ( this.resultBuffer.mapState === 'mapped' ) {
  49348. this.resultBuffer.unmap();
  49349. }
  49350. return this.lastValue;
  49351. }
  49352. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  49353. let totalDuration = 0;
  49354. for ( const [ , baseOffset ] of currentOffsets ) {
  49355. const startTime = times[ baseOffset ];
  49356. const endTime = times[ baseOffset + 1 ];
  49357. const duration = Number( endTime - startTime ) / 1e6;
  49358. totalDuration += duration;
  49359. }
  49360. this.resultBuffer.unmap();
  49361. this.lastValue = totalDuration;
  49362. return totalDuration;
  49363. } catch ( error ) {
  49364. console.error( 'Error resolving queries:', error );
  49365. if ( this.resultBuffer.mapState === 'mapped' ) {
  49366. this.resultBuffer.unmap();
  49367. }
  49368. return this.lastValue;
  49369. }
  49370. }
  49371. /**
  49372. * Dispose of the query pool.
  49373. *
  49374. * @async
  49375. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  49376. */
  49377. async dispose() {
  49378. if ( this.isDisposed ) {
  49379. return;
  49380. }
  49381. this.isDisposed = true;
  49382. // Wait for pending resolve operation
  49383. if ( this.pendingResolve ) {
  49384. try {
  49385. await this.pendingResolve;
  49386. } catch ( error ) {
  49387. console.error( 'Error waiting for pending resolve:', error );
  49388. }
  49389. }
  49390. // Ensure buffer is unmapped before destroying
  49391. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  49392. try {
  49393. this.resultBuffer.unmap();
  49394. } catch ( error ) {
  49395. console.error( 'Error unmapping buffer:', error );
  49396. }
  49397. }
  49398. // Destroy resources
  49399. if ( this.querySet ) {
  49400. this.querySet.destroy();
  49401. this.querySet = null;
  49402. }
  49403. if ( this.resolveBuffer ) {
  49404. this.resolveBuffer.destroy();
  49405. this.resolveBuffer = null;
  49406. }
  49407. if ( this.resultBuffer ) {
  49408. this.resultBuffer.destroy();
  49409. this.resultBuffer = null;
  49410. }
  49411. this.queryOffsets.clear();
  49412. this.pendingResolve = null;
  49413. }
  49414. }
  49415. /*// debugger tools
  49416. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  49417. //*/
  49418. /**
  49419. * A backend implementation targeting WebGPU.
  49420. *
  49421. * @private
  49422. * @augments Backend
  49423. */
  49424. class WebGPUBackend extends Backend {
  49425. /**
  49426. * WebGPUBackend options.
  49427. *
  49428. * @typedef {Object} WebGPUBackend~Options
  49429. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49430. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49431. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  49432. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49433. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49434. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49435. * @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.
  49436. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  49437. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  49438. * @property {string} [powerPreference=undefined] - The power preference.
  49439. * @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.
  49440. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  49441. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  49442. */
  49443. /**
  49444. * Constructs a new WebGPU backend.
  49445. *
  49446. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  49447. */
  49448. constructor( parameters = {} ) {
  49449. super( parameters );
  49450. /**
  49451. * This flag can be used for type testing.
  49452. *
  49453. * @type {boolean}
  49454. * @readonly
  49455. * @default true
  49456. */
  49457. this.isWebGPUBackend = true;
  49458. // some parameters require default values other than "undefined"
  49459. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  49460. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  49461. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  49462. /**
  49463. * Indicates whether the backend is in compatibility mode or not.
  49464. * @type {boolean}
  49465. * @default false
  49466. */
  49467. this.compatibilityMode = this.parameters.compatibilityMode;
  49468. /**
  49469. * A reference to the device.
  49470. *
  49471. * @type {?GPUDevice}
  49472. * @default null
  49473. */
  49474. this.device = null;
  49475. /**
  49476. * A reference to the context.
  49477. *
  49478. * @type {?GPUCanvasContext}
  49479. * @default null
  49480. */
  49481. this.context = null;
  49482. /**
  49483. * A reference to the color attachment of the default framebuffer.
  49484. *
  49485. * @type {?GPUTexture}
  49486. * @default null
  49487. */
  49488. this.colorBuffer = null;
  49489. /**
  49490. * A reference to the default render pass descriptor.
  49491. *
  49492. * @type {?Object}
  49493. * @default null
  49494. */
  49495. this.defaultRenderPassdescriptor = null;
  49496. /**
  49497. * A reference to a backend module holding common utility functions.
  49498. *
  49499. * @type {WebGPUUtils}
  49500. */
  49501. this.utils = new WebGPUUtils( this );
  49502. /**
  49503. * A reference to a backend module holding shader attribute-related
  49504. * utility functions.
  49505. *
  49506. * @type {WebGPUAttributeUtils}
  49507. */
  49508. this.attributeUtils = new WebGPUAttributeUtils( this );
  49509. /**
  49510. * A reference to a backend module holding shader binding-related
  49511. * utility functions.
  49512. *
  49513. * @type {WebGPUBindingUtils}
  49514. */
  49515. this.bindingUtils = new WebGPUBindingUtils( this );
  49516. /**
  49517. * A reference to a backend module holding shader pipeline-related
  49518. * utility functions.
  49519. *
  49520. * @type {WebGPUPipelineUtils}
  49521. */
  49522. this.pipelineUtils = new WebGPUPipelineUtils( this );
  49523. /**
  49524. * A reference to a backend module holding shader texture-related
  49525. * utility functions.
  49526. *
  49527. * @type {WebGPUTextureUtils}
  49528. */
  49529. this.textureUtils = new WebGPUTextureUtils( this );
  49530. /**
  49531. * A map that manages the resolve buffers for occlusion queries.
  49532. *
  49533. * @type {Map<number,GPUBuffer>}
  49534. */
  49535. this.occludedResolveCache = new Map();
  49536. }
  49537. /**
  49538. * Initializes the backend so it is ready for usage.
  49539. *
  49540. * @async
  49541. * @param {Renderer} renderer - The renderer.
  49542. * @return {Promise} A Promise that resolves when the backend has been initialized.
  49543. */
  49544. async init( renderer ) {
  49545. await super.init( renderer );
  49546. //
  49547. const parameters = this.parameters;
  49548. // create the device if it is not passed with parameters
  49549. let device;
  49550. if ( parameters.device === undefined ) {
  49551. const adapterOptions = {
  49552. powerPreference: parameters.powerPreference,
  49553. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  49554. };
  49555. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  49556. if ( adapter === null ) {
  49557. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  49558. }
  49559. // feature support
  49560. const features = Object.values( GPUFeatureName );
  49561. const supportedFeatures = [];
  49562. for ( const name of features ) {
  49563. if ( adapter.features.has( name ) ) {
  49564. supportedFeatures.push( name );
  49565. }
  49566. }
  49567. const deviceDescriptor = {
  49568. requiredFeatures: supportedFeatures,
  49569. requiredLimits: parameters.requiredLimits
  49570. };
  49571. device = await adapter.requestDevice( deviceDescriptor );
  49572. } else {
  49573. device = parameters.device;
  49574. }
  49575. device.lost.then( ( info ) => {
  49576. const deviceLossInfo = {
  49577. api: 'WebGPU',
  49578. message: info.message || 'Unknown reason',
  49579. reason: info.reason || null,
  49580. originalEvent: info
  49581. };
  49582. renderer.onDeviceLost( deviceLossInfo );
  49583. } );
  49584. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  49585. this.device = device;
  49586. this.context = context;
  49587. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  49588. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  49589. this.context.configure( {
  49590. device: this.device,
  49591. format: this.utils.getPreferredCanvasFormat(),
  49592. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  49593. alphaMode: alphaMode
  49594. } );
  49595. this.updateSize();
  49596. }
  49597. /**
  49598. * The coordinate system of the backend.
  49599. *
  49600. * @type {number}
  49601. * @readonly
  49602. */
  49603. get coordinateSystem() {
  49604. return WebGPUCoordinateSystem;
  49605. }
  49606. /**
  49607. * This method performs a readback operation by moving buffer data from
  49608. * a storage buffer attribute from the GPU to the CPU.
  49609. *
  49610. * @async
  49611. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  49612. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  49613. */
  49614. async getArrayBufferAsync( attribute ) {
  49615. return await this.attributeUtils.getArrayBufferAsync( attribute );
  49616. }
  49617. /**
  49618. * Returns the backend's rendering context.
  49619. *
  49620. * @return {GPUCanvasContext} The rendering context.
  49621. */
  49622. getContext() {
  49623. return this.context;
  49624. }
  49625. /**
  49626. * Returns the default render pass descriptor.
  49627. *
  49628. * In WebGPU, the default framebuffer must be configured
  49629. * like custom framebuffers so the backend needs a render
  49630. * pass descriptor even when rendering directly to screen.
  49631. *
  49632. * @private
  49633. * @return {Object} The render pass descriptor.
  49634. */
  49635. _getDefaultRenderPassDescriptor() {
  49636. let descriptor = this.defaultRenderPassdescriptor;
  49637. if ( descriptor === null ) {
  49638. const renderer = this.renderer;
  49639. descriptor = {
  49640. colorAttachments: [ {
  49641. view: null
  49642. } ],
  49643. };
  49644. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  49645. descriptor.depthStencilAttachment = {
  49646. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  49647. };
  49648. }
  49649. const colorAttachment = descriptor.colorAttachments[ 0 ];
  49650. if ( this.renderer.samples > 0 ) {
  49651. colorAttachment.view = this.colorBuffer.createView();
  49652. } else {
  49653. colorAttachment.resolveTarget = undefined;
  49654. }
  49655. this.defaultRenderPassdescriptor = descriptor;
  49656. }
  49657. const colorAttachment = descriptor.colorAttachments[ 0 ];
  49658. if ( this.renderer.samples > 0 ) {
  49659. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  49660. } else {
  49661. colorAttachment.view = this.context.getCurrentTexture().createView();
  49662. }
  49663. return descriptor;
  49664. }
  49665. /**
  49666. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  49667. *
  49668. * @param {RenderContext} renderContext - The render context.
  49669. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  49670. *
  49671. * @private
  49672. */
  49673. _isRenderCameraDepthArray( renderContext ) {
  49674. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  49675. }
  49676. /**
  49677. * Returns the render pass descriptor for the given render context.
  49678. *
  49679. * @private
  49680. * @param {RenderContext} renderContext - The render context.
  49681. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  49682. * @return {Object} The render pass descriptor.
  49683. */
  49684. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  49685. const renderTarget = renderContext.renderTarget;
  49686. const renderTargetData = this.get( renderTarget );
  49687. let descriptors = renderTargetData.descriptors;
  49688. if ( descriptors === undefined ||
  49689. renderTargetData.width !== renderTarget.width ||
  49690. renderTargetData.height !== renderTarget.height ||
  49691. renderTargetData.dimensions !== renderTarget.dimensions ||
  49692. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  49693. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  49694. renderTargetData.samples !== renderTarget.samples
  49695. ) {
  49696. descriptors = {};
  49697. renderTargetData.descriptors = descriptors;
  49698. // dispose
  49699. const onDispose = () => {
  49700. renderTarget.removeEventListener( 'dispose', onDispose );
  49701. this.delete( renderTarget );
  49702. };
  49703. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  49704. renderTarget.addEventListener( 'dispose', onDispose );
  49705. }
  49706. }
  49707. const cacheKey = renderContext.getCacheKey();
  49708. let descriptorBase = descriptors[ cacheKey ];
  49709. if ( descriptorBase === undefined ) {
  49710. const textures = renderContext.textures;
  49711. const textureViews = [];
  49712. let sliceIndex;
  49713. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  49714. for ( let i = 0; i < textures.length; i ++ ) {
  49715. const textureData = this.get( textures[ i ] );
  49716. const viewDescriptor = {
  49717. label: `colorAttachment_${ i }`,
  49718. baseMipLevel: renderContext.activeMipmapLevel,
  49719. mipLevelCount: 1,
  49720. baseArrayLayer: renderContext.activeCubeFace,
  49721. arrayLayerCount: 1,
  49722. dimension: GPUTextureViewDimension.TwoD
  49723. };
  49724. if ( renderTarget.isRenderTarget3D ) {
  49725. sliceIndex = renderContext.activeCubeFace;
  49726. viewDescriptor.baseArrayLayer = 0;
  49727. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  49728. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  49729. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  49730. if ( isRenderCameraDepthArray === true ) {
  49731. const cameras = renderContext.camera.cameras;
  49732. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  49733. const layerViewDescriptor = {
  49734. ...viewDescriptor,
  49735. baseArrayLayer: layer,
  49736. arrayLayerCount: 1,
  49737. dimension: GPUTextureViewDimension.TwoD
  49738. };
  49739. const textureView = textureData.texture.createView( layerViewDescriptor );
  49740. textureViews.push( {
  49741. view: textureView,
  49742. resolveTarget: undefined,
  49743. depthSlice: undefined
  49744. } );
  49745. }
  49746. } else {
  49747. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  49748. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  49749. }
  49750. }
  49751. if ( isRenderCameraDepthArray !== true ) {
  49752. const textureView = textureData.texture.createView( viewDescriptor );
  49753. let view, resolveTarget;
  49754. if ( textureData.msaaTexture !== undefined ) {
  49755. view = textureData.msaaTexture.createView();
  49756. resolveTarget = textureView;
  49757. } else {
  49758. view = textureView;
  49759. resolveTarget = undefined;
  49760. }
  49761. textureViews.push( {
  49762. view,
  49763. resolveTarget,
  49764. depthSlice: sliceIndex
  49765. } );
  49766. }
  49767. }
  49768. descriptorBase = { textureViews };
  49769. if ( renderContext.depth ) {
  49770. const depthTextureData = this.get( renderContext.depthTexture );
  49771. const options = {};
  49772. if ( renderContext.depthTexture.isArrayTexture ) {
  49773. options.dimension = GPUTextureViewDimension.TwoD;
  49774. options.arrayLayerCount = 1;
  49775. options.baseArrayLayer = renderContext.activeCubeFace;
  49776. }
  49777. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  49778. }
  49779. descriptors[ cacheKey ] = descriptorBase;
  49780. renderTargetData.width = renderTarget.width;
  49781. renderTargetData.height = renderTarget.height;
  49782. renderTargetData.samples = renderTarget.samples;
  49783. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  49784. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  49785. renderTargetData.dimensions = renderTarget.dimensions;
  49786. }
  49787. const descriptor = {
  49788. colorAttachments: []
  49789. };
  49790. // Apply dynamic properties to cached views
  49791. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  49792. const viewInfo = descriptorBase.textureViews[ i ];
  49793. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  49794. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  49795. clearValue = colorAttachmentsConfig.clearValue;
  49796. }
  49797. descriptor.colorAttachments.push( {
  49798. view: viewInfo.view,
  49799. depthSlice: viewInfo.depthSlice,
  49800. resolveTarget: viewInfo.resolveTarget,
  49801. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  49802. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  49803. clearValue: clearValue
  49804. } );
  49805. }
  49806. if ( descriptorBase.depthStencilView ) {
  49807. descriptor.depthStencilAttachment = {
  49808. view: descriptorBase.depthStencilView
  49809. };
  49810. }
  49811. return descriptor;
  49812. }
  49813. /**
  49814. * This method is executed at the beginning of a render call and prepares
  49815. * the WebGPU state for upcoming render calls
  49816. *
  49817. * @param {RenderContext} renderContext - The render context.
  49818. */
  49819. beginRender( renderContext ) {
  49820. const renderContextData = this.get( renderContext );
  49821. const device = this.device;
  49822. const occlusionQueryCount = renderContext.occlusionQueryCount;
  49823. let occlusionQuerySet;
  49824. if ( occlusionQueryCount > 0 ) {
  49825. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  49826. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  49827. // Get a reference to the array of objects with queries. The renderContextData property
  49828. // can be changed by another render pass before the buffer.mapAsyc() completes.
  49829. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  49830. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  49831. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  49832. //
  49833. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  49834. renderContextData.occlusionQuerySet = occlusionQuerySet;
  49835. renderContextData.occlusionQueryIndex = 0;
  49836. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  49837. renderContextData.lastOcclusionObject = null;
  49838. }
  49839. let descriptor;
  49840. if ( renderContext.textures === null ) {
  49841. descriptor = this._getDefaultRenderPassDescriptor();
  49842. } else {
  49843. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  49844. }
  49845. this.initTimestampQuery( renderContext, descriptor );
  49846. descriptor.occlusionQuerySet = occlusionQuerySet;
  49847. const depthStencilAttachment = descriptor.depthStencilAttachment;
  49848. if ( renderContext.textures !== null ) {
  49849. const colorAttachments = descriptor.colorAttachments;
  49850. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  49851. const colorAttachment = colorAttachments[ i ];
  49852. if ( renderContext.clearColor ) {
  49853. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  49854. colorAttachment.loadOp = GPULoadOp.Clear;
  49855. } else {
  49856. colorAttachment.loadOp = GPULoadOp.Load;
  49857. }
  49858. colorAttachment.storeOp = GPUStoreOp.Store;
  49859. }
  49860. } else {
  49861. const colorAttachment = descriptor.colorAttachments[ 0 ];
  49862. if ( renderContext.clearColor ) {
  49863. colorAttachment.clearValue = renderContext.clearColorValue;
  49864. colorAttachment.loadOp = GPULoadOp.Clear;
  49865. } else {
  49866. colorAttachment.loadOp = GPULoadOp.Load;
  49867. }
  49868. colorAttachment.storeOp = GPUStoreOp.Store;
  49869. }
  49870. //
  49871. if ( renderContext.depth ) {
  49872. if ( renderContext.clearDepth ) {
  49873. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  49874. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  49875. } else {
  49876. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  49877. }
  49878. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  49879. }
  49880. if ( renderContext.stencil ) {
  49881. if ( renderContext.clearStencil ) {
  49882. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  49883. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  49884. } else {
  49885. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  49886. }
  49887. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  49888. }
  49889. //
  49890. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  49891. // shadow arrays - prepare bundle encoders for each camera in an array camera
  49892. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  49893. const cameras = renderContext.camera.cameras;
  49894. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  49895. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  49896. } else {
  49897. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  49898. }
  49899. // Create bundle encoders for each layer
  49900. renderContextData.bundleEncoders = [];
  49901. renderContextData.bundleSets = [];
  49902. // Create separate bundle encoders for each camera in the array
  49903. for ( let i = 0; i < cameras.length; i ++ ) {
  49904. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  49905. renderContext,
  49906. 'renderBundleArrayCamera_' + i
  49907. );
  49908. // Initialize state tracking for this bundle
  49909. const bundleSets = {
  49910. attributes: {},
  49911. bindingGroups: [],
  49912. pipeline: null,
  49913. index: null
  49914. };
  49915. renderContextData.bundleEncoders.push( bundleEncoder );
  49916. renderContextData.bundleSets.push( bundleSets );
  49917. }
  49918. // We'll complete the bundles in finishRender
  49919. renderContextData.currentPass = null;
  49920. } else {
  49921. const currentPass = encoder.beginRenderPass( descriptor );
  49922. renderContextData.currentPass = currentPass;
  49923. if ( renderContext.viewport ) {
  49924. this.updateViewport( renderContext );
  49925. }
  49926. if ( renderContext.scissor ) {
  49927. const { x, y, width, height } = renderContext.scissorValue;
  49928. currentPass.setScissorRect( x, y, width, height );
  49929. }
  49930. }
  49931. //
  49932. renderContextData.descriptor = descriptor;
  49933. renderContextData.encoder = encoder;
  49934. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  49935. renderContextData.renderBundles = [];
  49936. }
  49937. /**
  49938. * This method creates layer descriptors for each camera in an array camera
  49939. * to prepare for rendering to a depth array texture.
  49940. *
  49941. * @param {RenderContext} renderContext - The render context.
  49942. * @param {Object} renderContextData - The render context data.
  49943. * @param {Object} descriptor - The render pass descriptor.
  49944. * @param {ArrayCamera} cameras - The array camera.
  49945. *
  49946. * @private
  49947. */
  49948. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  49949. const depthStencilAttachment = descriptor.depthStencilAttachment;
  49950. renderContextData.layerDescriptors = [];
  49951. const depthTextureData = this.get( renderContext.depthTexture );
  49952. if ( ! depthTextureData.viewCache ) {
  49953. depthTextureData.viewCache = [];
  49954. }
  49955. for ( let i = 0; i < cameras.length; i ++ ) {
  49956. const layerDescriptor = {
  49957. ...descriptor,
  49958. colorAttachments: [ {
  49959. ...descriptor.colorAttachments[ 0 ],
  49960. view: descriptor.colorAttachments[ i ].view
  49961. } ]
  49962. };
  49963. if ( descriptor.depthStencilAttachment ) {
  49964. const layerIndex = i;
  49965. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  49966. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  49967. dimension: GPUTextureViewDimension.TwoD,
  49968. baseArrayLayer: i,
  49969. arrayLayerCount: 1
  49970. } );
  49971. }
  49972. layerDescriptor.depthStencilAttachment = {
  49973. view: depthTextureData.viewCache[ layerIndex ],
  49974. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  49975. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  49976. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  49977. };
  49978. if ( renderContext.stencil ) {
  49979. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  49980. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  49981. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  49982. }
  49983. } else {
  49984. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  49985. }
  49986. renderContextData.layerDescriptors.push( layerDescriptor );
  49987. }
  49988. }
  49989. /**
  49990. * This method updates the layer descriptors for each camera in an array camera
  49991. * to prepare for rendering to a depth array texture.
  49992. *
  49993. * @param {RenderContext} renderContext - The render context.
  49994. * @param {Object} renderContextData - The render context data.
  49995. * @param {ArrayCamera} cameras - The array camera.
  49996. *
  49997. */
  49998. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  49999. for ( let i = 0; i < cameras.length; i ++ ) {
  50000. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50001. if ( layerDescriptor.depthStencilAttachment ) {
  50002. const depthAttachment = layerDescriptor.depthStencilAttachment;
  50003. if ( renderContext.depth ) {
  50004. if ( renderContext.clearDepth ) {
  50005. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  50006. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  50007. } else {
  50008. depthAttachment.depthLoadOp = GPULoadOp.Load;
  50009. }
  50010. }
  50011. if ( renderContext.stencil ) {
  50012. if ( renderContext.clearStencil ) {
  50013. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  50014. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  50015. } else {
  50016. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  50017. }
  50018. }
  50019. }
  50020. }
  50021. }
  50022. /**
  50023. * This method is executed at the end of a render call and finalizes work
  50024. * after draw calls.
  50025. *
  50026. * @param {RenderContext} renderContext - The render context.
  50027. */
  50028. finishRender( renderContext ) {
  50029. const renderContextData = this.get( renderContext );
  50030. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50031. if ( renderContextData.renderBundles.length > 0 ) {
  50032. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  50033. }
  50034. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  50035. renderContextData.currentPass.endOcclusionQuery();
  50036. }
  50037. // shadow arrays - Execute bundles for each layer
  50038. const encoder = renderContextData.encoder;
  50039. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  50040. const bundles = [];
  50041. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  50042. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50043. bundles.push( bundleEncoder.finish() );
  50044. }
  50045. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  50046. if ( i < bundles.length ) {
  50047. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50048. const renderPass = encoder.beginRenderPass( layerDescriptor );
  50049. if ( renderContext.viewport ) {
  50050. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50051. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50052. }
  50053. if ( renderContext.scissor ) {
  50054. const { x, y, width, height } = renderContext.scissorValue;
  50055. renderPass.setScissorRect( x, y, width, height );
  50056. }
  50057. renderPass.executeBundles( [ bundles[ i ] ] );
  50058. renderPass.end();
  50059. }
  50060. }
  50061. } else if ( renderContextData.currentPass ) {
  50062. renderContextData.currentPass.end();
  50063. }
  50064. if ( occlusionQueryCount > 0 ) {
  50065. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  50066. //
  50067. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  50068. if ( queryResolveBuffer === undefined ) {
  50069. queryResolveBuffer = this.device.createBuffer(
  50070. {
  50071. size: bufferSize,
  50072. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  50073. }
  50074. );
  50075. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  50076. }
  50077. //
  50078. const readBuffer = this.device.createBuffer(
  50079. {
  50080. size: bufferSize,
  50081. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50082. }
  50083. );
  50084. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  50085. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  50086. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  50087. renderContextData.occlusionQueryBuffer = readBuffer;
  50088. //
  50089. this.resolveOccludedAsync( renderContext );
  50090. }
  50091. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  50092. //
  50093. if ( renderContext.textures !== null ) {
  50094. const textures = renderContext.textures;
  50095. for ( let i = 0; i < textures.length; i ++ ) {
  50096. const texture = textures[ i ];
  50097. if ( texture.generateMipmaps === true ) {
  50098. this.textureUtils.generateMipmaps( texture );
  50099. }
  50100. }
  50101. }
  50102. }
  50103. /**
  50104. * Returns `true` if the given 3D object is fully occluded by other
  50105. * 3D objects in the scene.
  50106. *
  50107. * @param {RenderContext} renderContext - The render context.
  50108. * @param {Object3D} object - The 3D object to test.
  50109. * @return {boolean} Whether the 3D object is fully occluded or not.
  50110. */
  50111. isOccluded( renderContext, object ) {
  50112. const renderContextData = this.get( renderContext );
  50113. return renderContextData.occluded && renderContextData.occluded.has( object );
  50114. }
  50115. /**
  50116. * This method processes the result of occlusion queries and writes it
  50117. * into render context data.
  50118. *
  50119. * @async
  50120. * @param {RenderContext} renderContext - The render context.
  50121. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  50122. */
  50123. async resolveOccludedAsync( renderContext ) {
  50124. const renderContextData = this.get( renderContext );
  50125. // handle occlusion query results
  50126. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  50127. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  50128. const occluded = new WeakSet();
  50129. renderContextData.currentOcclusionQueryObjects = null;
  50130. renderContextData.currentOcclusionQueryBuffer = null;
  50131. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  50132. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  50133. const results = new BigUint64Array( buffer );
  50134. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  50135. if ( results[ i ] === BigInt( 0 ) ) {
  50136. occluded.add( currentOcclusionQueryObjects[ i ] );
  50137. }
  50138. }
  50139. currentOcclusionQueryBuffer.destroy();
  50140. renderContextData.occluded = occluded;
  50141. }
  50142. }
  50143. /**
  50144. * Updates the viewport with the values from the given render context.
  50145. *
  50146. * @param {RenderContext} renderContext - The render context.
  50147. */
  50148. updateViewport( renderContext ) {
  50149. const { currentPass } = this.get( renderContext );
  50150. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50151. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50152. }
  50153. /**
  50154. * Returns the clear color and alpha into a single
  50155. * color object.
  50156. *
  50157. * @return {Color4} The clear color.
  50158. */
  50159. getClearColor() {
  50160. const clearColor = super.getClearColor();
  50161. // only premultiply alpha when alphaMode is "premultiplied"
  50162. if ( this.renderer.alpha === true ) {
  50163. clearColor.r *= clearColor.a;
  50164. clearColor.g *= clearColor.a;
  50165. clearColor.b *= clearColor.a;
  50166. }
  50167. return clearColor;
  50168. }
  50169. /**
  50170. * Performs a clear operation.
  50171. *
  50172. * @param {boolean} color - Whether the color buffer should be cleared or not.
  50173. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  50174. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  50175. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  50176. */
  50177. clear( color, depth, stencil, renderTargetContext = null ) {
  50178. const device = this.device;
  50179. const renderer = this.renderer;
  50180. let colorAttachments = [];
  50181. let depthStencilAttachment;
  50182. let clearValue;
  50183. let supportsDepth;
  50184. let supportsStencil;
  50185. if ( color ) {
  50186. const clearColor = this.getClearColor();
  50187. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  50188. }
  50189. if ( renderTargetContext === null ) {
  50190. supportsDepth = renderer.depth;
  50191. supportsStencil = renderer.stencil;
  50192. const descriptor = this._getDefaultRenderPassDescriptor();
  50193. if ( color ) {
  50194. colorAttachments = descriptor.colorAttachments;
  50195. const colorAttachment = colorAttachments[ 0 ];
  50196. colorAttachment.clearValue = clearValue;
  50197. colorAttachment.loadOp = GPULoadOp.Clear;
  50198. colorAttachment.storeOp = GPUStoreOp.Store;
  50199. }
  50200. if ( supportsDepth || supportsStencil ) {
  50201. depthStencilAttachment = descriptor.depthStencilAttachment;
  50202. }
  50203. } else {
  50204. supportsDepth = renderTargetContext.depth;
  50205. supportsStencil = renderTargetContext.stencil;
  50206. const clearConfig = {
  50207. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  50208. clearValue: color ? clearValue : undefined
  50209. };
  50210. if ( supportsDepth ) {
  50211. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  50212. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  50213. clearConfig.depthStoreOp = GPUStoreOp.Store;
  50214. }
  50215. if ( supportsStencil ) {
  50216. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  50217. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  50218. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  50219. }
  50220. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  50221. colorAttachments = descriptor.colorAttachments;
  50222. depthStencilAttachment = descriptor.depthStencilAttachment;
  50223. }
  50224. if ( supportsDepth && depthStencilAttachment && depthStencilAttachment.depthLoadOp === undefined ) {
  50225. if ( depth ) {
  50226. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  50227. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  50228. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50229. } else {
  50230. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50231. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50232. }
  50233. }
  50234. //
  50235. if ( supportsStencil && depthStencilAttachment && depthStencilAttachment.stencilLoadOp === undefined ) {
  50236. if ( stencil ) {
  50237. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  50238. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  50239. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50240. } else {
  50241. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50242. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50243. }
  50244. }
  50245. //
  50246. const encoder = device.createCommandEncoder( { label: 'clear' } );
  50247. const currentPass = encoder.beginRenderPass( {
  50248. colorAttachments,
  50249. depthStencilAttachment
  50250. } );
  50251. currentPass.end();
  50252. device.queue.submit( [ encoder.finish() ] );
  50253. }
  50254. // compute
  50255. /**
  50256. * This method is executed at the beginning of a compute call and
  50257. * prepares the state for upcoming compute tasks.
  50258. *
  50259. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50260. */
  50261. beginCompute( computeGroup ) {
  50262. const groupGPU = this.get( computeGroup );
  50263. const descriptor = {
  50264. label: 'computeGroup_' + computeGroup.id
  50265. };
  50266. this.initTimestampQuery( computeGroup, descriptor );
  50267. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  50268. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  50269. }
  50270. /**
  50271. * Executes a compute command for the given compute node.
  50272. *
  50273. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  50274. * @param {Node} computeNode - The compute node.
  50275. * @param {Array<BindGroup>} bindings - The bindings.
  50276. * @param {ComputePipeline} pipeline - The compute pipeline.
  50277. */
  50278. compute( computeGroup, computeNode, bindings, pipeline ) {
  50279. const { passEncoderGPU } = this.get( computeGroup );
  50280. // pipeline
  50281. const pipelineGPU = this.get( pipeline ).pipeline;
  50282. passEncoderGPU.setPipeline( pipelineGPU );
  50283. // bind groups
  50284. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50285. const bindGroup = bindings[ i ];
  50286. const bindingsData = this.get( bindGroup );
  50287. passEncoderGPU.setBindGroup( i, bindingsData.group );
  50288. }
  50289. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  50290. const computeNodeData = this.get( computeNode );
  50291. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  50292. const { dispatchSize } = computeNodeData;
  50293. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  50294. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  50295. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  50296. } else {
  50297. dispatchSize.x = computeNode.dispatchCount;
  50298. }
  50299. passEncoderGPU.dispatchWorkgroups(
  50300. dispatchSize.x,
  50301. dispatchSize.y,
  50302. dispatchSize.z
  50303. );
  50304. }
  50305. /**
  50306. * This method is executed at the end of a compute call and
  50307. * finalizes work after compute tasks.
  50308. *
  50309. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50310. */
  50311. finishCompute( computeGroup ) {
  50312. const groupData = this.get( computeGroup );
  50313. groupData.passEncoderGPU.end();
  50314. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  50315. }
  50316. /**
  50317. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  50318. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  50319. *
  50320. * @async
  50321. * @return {Promise} A Promise that resolves when synchronization has been finished.
  50322. */
  50323. async waitForGPU() {
  50324. await this.device.queue.onSubmittedWorkDone();
  50325. }
  50326. // render object
  50327. /**
  50328. * Executes a draw command for the given render object.
  50329. *
  50330. * @param {RenderObject} renderObject - The render object to draw.
  50331. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  50332. */
  50333. draw( renderObject, info ) {
  50334. const { object, material, context, pipeline } = renderObject;
  50335. const bindings = renderObject.getBindings();
  50336. const renderContextData = this.get( context );
  50337. const pipelineGPU = this.get( pipeline ).pipeline;
  50338. const index = renderObject.getIndex();
  50339. const hasIndex = ( index !== null );
  50340. const drawParams = renderObject.getDrawParameters();
  50341. if ( drawParams === null ) return;
  50342. // pipeline
  50343. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  50344. // pipeline
  50345. passEncoderGPU.setPipeline( pipelineGPU );
  50346. currentSets.pipeline = pipelineGPU;
  50347. // bind groups
  50348. const currentBindingGroups = currentSets.bindingGroups;
  50349. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50350. const bindGroup = bindings[ i ];
  50351. const bindingsData = this.get( bindGroup );
  50352. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  50353. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  50354. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  50355. }
  50356. }
  50357. // attributes
  50358. // index
  50359. if ( hasIndex === true ) {
  50360. if ( currentSets.index !== index ) {
  50361. const buffer = this.get( index ).buffer;
  50362. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  50363. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  50364. currentSets.index = index;
  50365. }
  50366. }
  50367. // vertex buffers
  50368. const vertexBuffers = renderObject.getVertexBuffers();
  50369. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  50370. const vertexBuffer = vertexBuffers[ i ];
  50371. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  50372. const buffer = this.get( vertexBuffer ).buffer;
  50373. passEncoderGPU.setVertexBuffer( i, buffer );
  50374. currentSets.attributes[ i ] = vertexBuffer;
  50375. }
  50376. }
  50377. // stencil
  50378. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  50379. passEncoderGPU.setStencilReference( material.stencilRef );
  50380. renderContextData.currentStencilRef = material.stencilRef;
  50381. }
  50382. };
  50383. // Define draw function
  50384. const draw = ( passEncoderGPU, currentSets ) => {
  50385. setPipelineAndBindings( passEncoderGPU, currentSets );
  50386. if ( object.isBatchedMesh === true ) {
  50387. const starts = object._multiDrawStarts;
  50388. const counts = object._multiDrawCounts;
  50389. const drawCount = object._multiDrawCount;
  50390. const drawInstances = object._multiDrawInstances;
  50391. if ( drawInstances !== null ) {
  50392. // @deprecated, r174
  50393. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  50394. }
  50395. for ( let i = 0; i < drawCount; i ++ ) {
  50396. const count = drawInstances ? drawInstances[ i ] : 1;
  50397. const firstInstance = count > 1 ? 0 : i;
  50398. if ( hasIndex === true ) {
  50399. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  50400. } else {
  50401. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  50402. }
  50403. info.update( object, counts[ i ], count );
  50404. }
  50405. } else if ( hasIndex === true ) {
  50406. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  50407. const indirect = renderObject.getIndirect();
  50408. if ( indirect !== null ) {
  50409. const buffer = this.get( indirect ).buffer;
  50410. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  50411. } else {
  50412. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  50413. }
  50414. info.update( object, indexCount, instanceCount );
  50415. } else {
  50416. const { vertexCount, instanceCount, firstVertex } = drawParams;
  50417. const indirect = renderObject.getIndirect();
  50418. if ( indirect !== null ) {
  50419. const buffer = this.get( indirect ).buffer;
  50420. passEncoderGPU.drawIndirect( buffer, 0 );
  50421. } else {
  50422. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  50423. }
  50424. info.update( object, vertexCount, instanceCount );
  50425. }
  50426. };
  50427. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  50428. const cameraData = this.get( renderObject.camera );
  50429. const cameras = renderObject.camera.cameras;
  50430. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  50431. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  50432. const bindingsData = this.get( cameraIndex );
  50433. const indexesGPU = [];
  50434. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  50435. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50436. data[ 0 ] = i;
  50437. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  50438. indexesGPU.push( bindGroupIndex );
  50439. }
  50440. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  50441. }
  50442. const pixelRatio = this.renderer.getPixelRatio();
  50443. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50444. const subCamera = cameras[ i ];
  50445. if ( object.layers.test( subCamera.layers ) ) {
  50446. const vp = subCamera.viewport;
  50447. let pass = renderContextData.currentPass;
  50448. let sets = renderContextData.currentSets;
  50449. if ( renderContextData.bundleEncoders ) {
  50450. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50451. const bundleSets = renderContextData.bundleSets[ i ];
  50452. pass = bundleEncoder;
  50453. sets = bundleSets;
  50454. }
  50455. if ( vp ) {
  50456. pass.setViewport(
  50457. Math.floor( vp.x * pixelRatio ),
  50458. Math.floor( vp.y * pixelRatio ),
  50459. Math.floor( vp.width * pixelRatio ),
  50460. Math.floor( vp.height * pixelRatio ),
  50461. context.viewportValue.minDepth,
  50462. context.viewportValue.maxDepth
  50463. );
  50464. }
  50465. // Set camera index binding for this layer
  50466. if ( cameraIndex && cameraData.indexesGPU ) {
  50467. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  50468. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  50469. }
  50470. draw( pass, sets );
  50471. }
  50472. }
  50473. } else {
  50474. // Regular single camera rendering
  50475. if ( renderContextData.currentPass ) {
  50476. // Handle occlusion queries
  50477. if ( renderContextData.occlusionQuerySet !== undefined ) {
  50478. const lastObject = renderContextData.lastOcclusionObject;
  50479. if ( lastObject !== object ) {
  50480. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  50481. renderContextData.currentPass.endOcclusionQuery();
  50482. renderContextData.occlusionQueryIndex ++;
  50483. }
  50484. if ( object.occlusionTest === true ) {
  50485. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  50486. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  50487. }
  50488. renderContextData.lastOcclusionObject = object;
  50489. }
  50490. }
  50491. draw( renderContextData.currentPass, renderContextData.currentSets );
  50492. }
  50493. }
  50494. }
  50495. // cache key
  50496. /**
  50497. * Returns `true` if the render pipeline requires an update.
  50498. *
  50499. * @param {RenderObject} renderObject - The render object.
  50500. * @return {boolean} Whether the render pipeline requires an update or not.
  50501. */
  50502. needsRenderUpdate( renderObject ) {
  50503. const data = this.get( renderObject );
  50504. const { object, material } = renderObject;
  50505. const utils = this.utils;
  50506. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  50507. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  50508. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  50509. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  50510. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  50511. let needsUpdate = false;
  50512. if ( data.material !== material || data.materialVersion !== material.version ||
  50513. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  50514. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  50515. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  50516. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  50517. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  50518. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  50519. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  50520. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  50521. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  50522. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  50523. data.primitiveTopology !== primitiveTopology ||
  50524. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  50525. ) {
  50526. data.material = material; data.materialVersion = material.version;
  50527. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  50528. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  50529. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  50530. data.colorWrite = material.colorWrite;
  50531. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  50532. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  50533. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  50534. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  50535. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  50536. data.sampleCount = sampleCount;
  50537. data.colorSpace = colorSpace;
  50538. data.colorFormat = colorFormat;
  50539. data.depthStencilFormat = depthStencilFormat;
  50540. data.primitiveTopology = primitiveTopology;
  50541. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  50542. needsUpdate = true;
  50543. }
  50544. return needsUpdate;
  50545. }
  50546. /**
  50547. * Returns a cache key that is used to identify render pipelines.
  50548. *
  50549. * @param {RenderObject} renderObject - The render object.
  50550. * @return {string} The cache key.
  50551. */
  50552. getRenderCacheKey( renderObject ) {
  50553. const { object, material } = renderObject;
  50554. const utils = this.utils;
  50555. const renderContext = renderObject.context;
  50556. return [
  50557. material.transparent, material.blending, material.premultipliedAlpha,
  50558. material.blendSrc, material.blendDst, material.blendEquation,
  50559. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  50560. material.colorWrite,
  50561. material.depthWrite, material.depthTest, material.depthFunc,
  50562. material.stencilWrite, material.stencilFunc,
  50563. material.stencilFail, material.stencilZFail, material.stencilZPass,
  50564. material.stencilFuncMask, material.stencilWriteMask,
  50565. material.side,
  50566. utils.getSampleCountRenderContext( renderContext ),
  50567. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  50568. utils.getPrimitiveTopology( object, material ),
  50569. renderObject.getGeometryCacheKey(),
  50570. renderObject.clippingContextCacheKey
  50571. ].join();
  50572. }
  50573. // textures
  50574. /**
  50575. * Creates a GPU sampler for the given texture.
  50576. *
  50577. * @param {Texture} texture - The texture to create the sampler for.
  50578. */
  50579. createSampler( texture ) {
  50580. this.textureUtils.createSampler( texture );
  50581. }
  50582. /**
  50583. * Destroys the GPU sampler for the given texture.
  50584. *
  50585. * @param {Texture} texture - The texture to destroy the sampler for.
  50586. */
  50587. destroySampler( texture ) {
  50588. this.textureUtils.destroySampler( texture );
  50589. }
  50590. /**
  50591. * Creates a default texture for the given texture that can be used
  50592. * as a placeholder until the actual texture is ready for usage.
  50593. *
  50594. * @param {Texture} texture - The texture to create a default texture for.
  50595. */
  50596. createDefaultTexture( texture ) {
  50597. this.textureUtils.createDefaultTexture( texture );
  50598. }
  50599. /**
  50600. * Defines a texture on the GPU for the given texture object.
  50601. *
  50602. * @param {Texture} texture - The texture.
  50603. * @param {Object} [options={}] - Optional configuration parameter.
  50604. */
  50605. createTexture( texture, options ) {
  50606. this.textureUtils.createTexture( texture, options );
  50607. }
  50608. /**
  50609. * Uploads the updated texture data to the GPU.
  50610. *
  50611. * @param {Texture} texture - The texture.
  50612. * @param {Object} [options={}] - Optional configuration parameter.
  50613. */
  50614. updateTexture( texture, options ) {
  50615. this.textureUtils.updateTexture( texture, options );
  50616. }
  50617. /**
  50618. * Generates mipmaps for the given texture.
  50619. *
  50620. * @param {Texture} texture - The texture.
  50621. */
  50622. generateMipmaps( texture ) {
  50623. this.textureUtils.generateMipmaps( texture );
  50624. }
  50625. /**
  50626. * Destroys the GPU data for the given texture object.
  50627. *
  50628. * @param {Texture} texture - The texture.
  50629. */
  50630. destroyTexture( texture ) {
  50631. this.textureUtils.destroyTexture( texture );
  50632. }
  50633. /**
  50634. * Returns texture data as a typed array.
  50635. *
  50636. * @async
  50637. * @param {Texture} texture - The texture to copy.
  50638. * @param {number} x - The x coordinate of the copy origin.
  50639. * @param {number} y - The y coordinate of the copy origin.
  50640. * @param {number} width - The width of the copy.
  50641. * @param {number} height - The height of the copy.
  50642. * @param {number} faceIndex - The face index.
  50643. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  50644. */
  50645. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  50646. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  50647. }
  50648. /**
  50649. * Inits a time stamp query for the given render context.
  50650. *
  50651. * @param {RenderContext} renderContext - The render context.
  50652. * @param {Object} descriptor - The query descriptor.
  50653. */
  50654. initTimestampQuery( renderContext, descriptor ) {
  50655. if ( ! this.trackTimestamp ) return;
  50656. const type = renderContext.isComputeNode ? 'compute' : 'render';
  50657. if ( ! this.timestampQueryPool[ type ] ) {
  50658. // TODO: Variable maxQueries?
  50659. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  50660. }
  50661. const timestampQueryPool = this.timestampQueryPool[ type ];
  50662. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  50663. descriptor.timestampWrites = {
  50664. querySet: timestampQueryPool.querySet,
  50665. beginningOfPassWriteIndex: baseOffset,
  50666. endOfPassWriteIndex: baseOffset + 1,
  50667. };
  50668. }
  50669. // node builder
  50670. /**
  50671. * Returns a node builder for the given render object.
  50672. *
  50673. * @param {RenderObject} object - The render object.
  50674. * @param {Renderer} renderer - The renderer.
  50675. * @return {WGSLNodeBuilder} The node builder.
  50676. */
  50677. createNodeBuilder( object, renderer ) {
  50678. return new WGSLNodeBuilder( object, renderer );
  50679. }
  50680. // program
  50681. /**
  50682. * Creates a shader program from the given programmable stage.
  50683. *
  50684. * @param {ProgrammableStage} program - The programmable stage.
  50685. */
  50686. createProgram( program ) {
  50687. const programGPU = this.get( program );
  50688. programGPU.module = {
  50689. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  50690. entryPoint: 'main'
  50691. };
  50692. }
  50693. /**
  50694. * Destroys the shader program of the given programmable stage.
  50695. *
  50696. * @param {ProgrammableStage} program - The programmable stage.
  50697. */
  50698. destroyProgram( program ) {
  50699. this.delete( program );
  50700. }
  50701. // pipelines
  50702. /**
  50703. * Creates a render pipeline for the given render object.
  50704. *
  50705. * @param {RenderObject} renderObject - The render object.
  50706. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  50707. */
  50708. createRenderPipeline( renderObject, promises ) {
  50709. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  50710. }
  50711. /**
  50712. * Creates a compute pipeline for the given compute node.
  50713. *
  50714. * @param {ComputePipeline} computePipeline - The compute pipeline.
  50715. * @param {Array<BindGroup>} bindings - The bindings.
  50716. */
  50717. createComputePipeline( computePipeline, bindings ) {
  50718. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  50719. }
  50720. /**
  50721. * Prepares the state for encoding render bundles.
  50722. *
  50723. * @param {RenderContext} renderContext - The render context.
  50724. */
  50725. beginBundle( renderContext ) {
  50726. const renderContextData = this.get( renderContext );
  50727. renderContextData._currentPass = renderContextData.currentPass;
  50728. renderContextData._currentSets = renderContextData.currentSets;
  50729. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  50730. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  50731. }
  50732. /**
  50733. * After processing render bundles this method finalizes related work.
  50734. *
  50735. * @param {RenderContext} renderContext - The render context.
  50736. * @param {RenderBundle} bundle - The render bundle.
  50737. */
  50738. finishBundle( renderContext, bundle ) {
  50739. const renderContextData = this.get( renderContext );
  50740. const bundleEncoder = renderContextData.currentPass;
  50741. const bundleGPU = bundleEncoder.finish();
  50742. this.get( bundle ).bundleGPU = bundleGPU;
  50743. // restore render pass state
  50744. renderContextData.currentSets = renderContextData._currentSets;
  50745. renderContextData.currentPass = renderContextData._currentPass;
  50746. }
  50747. /**
  50748. * Adds a render bundle to the render context data.
  50749. *
  50750. * @param {RenderContext} renderContext - The render context.
  50751. * @param {RenderBundle} bundle - The render bundle to add.
  50752. */
  50753. addBundle( renderContext, bundle ) {
  50754. const renderContextData = this.get( renderContext );
  50755. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  50756. }
  50757. // bindings
  50758. /**
  50759. * Creates bindings from the given bind group definition.
  50760. *
  50761. * @param {BindGroup} bindGroup - The bind group.
  50762. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50763. * @param {number} cacheIndex - The cache index.
  50764. * @param {number} version - The version.
  50765. */
  50766. createBindings( bindGroup, bindings, cacheIndex, version ) {
  50767. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  50768. }
  50769. /**
  50770. * Updates the given bind group definition.
  50771. *
  50772. * @param {BindGroup} bindGroup - The bind group.
  50773. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50774. * @param {number} cacheIndex - The cache index.
  50775. * @param {number} version - The version.
  50776. */
  50777. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  50778. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  50779. }
  50780. /**
  50781. * Updates a buffer binding.
  50782. *
  50783. * @param {Buffer} binding - The buffer binding to update.
  50784. */
  50785. updateBinding( binding ) {
  50786. this.bindingUtils.updateBinding( binding );
  50787. }
  50788. // attributes
  50789. /**
  50790. * Creates the buffer of an indexed shader attribute.
  50791. *
  50792. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  50793. */
  50794. createIndexAttribute( attribute ) {
  50795. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  50796. }
  50797. /**
  50798. * Creates the GPU buffer of a shader attribute.
  50799. *
  50800. * @param {BufferAttribute} attribute - The buffer attribute.
  50801. */
  50802. createAttribute( attribute ) {
  50803. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  50804. }
  50805. /**
  50806. * Creates the GPU buffer of a storage attribute.
  50807. *
  50808. * @param {BufferAttribute} attribute - The buffer attribute.
  50809. */
  50810. createStorageAttribute( attribute ) {
  50811. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  50812. }
  50813. /**
  50814. * Creates the GPU buffer of an indirect storage attribute.
  50815. *
  50816. * @param {BufferAttribute} attribute - The buffer attribute.
  50817. */
  50818. createIndirectStorageAttribute( attribute ) {
  50819. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  50820. }
  50821. /**
  50822. * Updates the GPU buffer of a shader attribute.
  50823. *
  50824. * @param {BufferAttribute} attribute - The buffer attribute to update.
  50825. */
  50826. updateAttribute( attribute ) {
  50827. this.attributeUtils.updateAttribute( attribute );
  50828. }
  50829. /**
  50830. * Destroys the GPU buffer of a shader attribute.
  50831. *
  50832. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  50833. */
  50834. destroyAttribute( attribute ) {
  50835. this.attributeUtils.destroyAttribute( attribute );
  50836. }
  50837. // canvas
  50838. /**
  50839. * Triggers an update of the default render pass descriptor.
  50840. */
  50841. updateSize() {
  50842. this.colorBuffer = this.textureUtils.getColorBuffer();
  50843. this.defaultRenderPassdescriptor = null;
  50844. }
  50845. // utils public
  50846. /**
  50847. * Returns the maximum anisotropy texture filtering value.
  50848. *
  50849. * @return {number} The maximum anisotropy texture filtering value.
  50850. */
  50851. getMaxAnisotropy() {
  50852. return 16;
  50853. }
  50854. /**
  50855. * Checks if the given feature is supported by the backend.
  50856. *
  50857. * @param {string} name - The feature's name.
  50858. * @return {boolean} Whether the feature is supported or not.
  50859. */
  50860. hasFeature( name ) {
  50861. return this.device.features.has( name );
  50862. }
  50863. /**
  50864. * Copies data of the given source texture to the given destination texture.
  50865. *
  50866. * @param {Texture} srcTexture - The source texture.
  50867. * @param {Texture} dstTexture - The destination texture.
  50868. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  50869. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  50870. * @param {number} [srcLevel=0] - The mipmap level to copy.
  50871. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  50872. */
  50873. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  50874. let dstX = 0;
  50875. let dstY = 0;
  50876. let dstZ = 0;
  50877. let srcX = 0;
  50878. let srcY = 0;
  50879. let srcZ = 0;
  50880. let srcWidth = srcTexture.image.width;
  50881. let srcHeight = srcTexture.image.height;
  50882. let srcDepth = 1;
  50883. if ( srcRegion !== null ) {
  50884. if ( srcRegion.isBox3 === true ) {
  50885. srcX = srcRegion.min.x;
  50886. srcY = srcRegion.min.y;
  50887. srcZ = srcRegion.min.z;
  50888. srcWidth = srcRegion.max.x - srcRegion.min.x;
  50889. srcHeight = srcRegion.max.y - srcRegion.min.y;
  50890. srcDepth = srcRegion.max.z - srcRegion.min.z;
  50891. } else {
  50892. // Assume it's a Box2
  50893. srcX = srcRegion.min.x;
  50894. srcY = srcRegion.min.y;
  50895. srcWidth = srcRegion.max.x - srcRegion.min.x;
  50896. srcHeight = srcRegion.max.y - srcRegion.min.y;
  50897. srcDepth = 1;
  50898. }
  50899. }
  50900. if ( dstPosition !== null ) {
  50901. dstX = dstPosition.x;
  50902. dstY = dstPosition.y;
  50903. dstZ = dstPosition.z || 0;
  50904. }
  50905. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  50906. const sourceGPU = this.get( srcTexture ).texture;
  50907. const destinationGPU = this.get( dstTexture ).texture;
  50908. encoder.copyTextureToTexture(
  50909. {
  50910. texture: sourceGPU,
  50911. mipLevel: srcLevel,
  50912. origin: { x: srcX, y: srcY, z: srcZ }
  50913. },
  50914. {
  50915. texture: destinationGPU,
  50916. mipLevel: dstLevel,
  50917. origin: { x: dstX, y: dstY, z: dstZ }
  50918. },
  50919. [
  50920. srcWidth,
  50921. srcHeight,
  50922. srcDepth
  50923. ]
  50924. );
  50925. this.device.queue.submit( [ encoder.finish() ] );
  50926. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  50927. this.textureUtils.generateMipmaps( dstTexture );
  50928. }
  50929. }
  50930. /**
  50931. * Copies the current bound framebuffer to the given texture.
  50932. *
  50933. * @param {Texture} texture - The destination texture.
  50934. * @param {RenderContext} renderContext - The render context.
  50935. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  50936. */
  50937. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  50938. const renderContextData = this.get( renderContext );
  50939. let sourceGPU = null;
  50940. if ( renderContext.renderTarget ) {
  50941. if ( texture.isDepthTexture ) {
  50942. sourceGPU = this.get( renderContext.depthTexture ).texture;
  50943. } else {
  50944. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  50945. }
  50946. } else {
  50947. if ( texture.isDepthTexture ) {
  50948. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  50949. } else {
  50950. sourceGPU = this.context.getCurrentTexture();
  50951. }
  50952. }
  50953. const destinationGPU = this.get( texture ).texture;
  50954. if ( sourceGPU.format !== destinationGPU.format ) {
  50955. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  50956. return;
  50957. }
  50958. let encoder;
  50959. if ( renderContextData.currentPass ) {
  50960. renderContextData.currentPass.end();
  50961. encoder = renderContextData.encoder;
  50962. } else {
  50963. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  50964. }
  50965. encoder.copyTextureToTexture(
  50966. {
  50967. texture: sourceGPU,
  50968. origin: [ rectangle.x, rectangle.y, 0 ],
  50969. },
  50970. {
  50971. texture: destinationGPU
  50972. },
  50973. [
  50974. rectangle.z,
  50975. rectangle.w
  50976. ]
  50977. );
  50978. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  50979. if ( renderContextData.currentPass ) {
  50980. const { descriptor } = renderContextData;
  50981. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  50982. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  50983. }
  50984. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50985. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50986. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  50987. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  50988. if ( renderContext.viewport ) {
  50989. this.updateViewport( renderContext );
  50990. }
  50991. if ( renderContext.scissor ) {
  50992. const { x, y, width, height } = renderContext.scissorValue;
  50993. renderContextData.currentPass.setScissorRect( x, y, width, height );
  50994. }
  50995. } else {
  50996. this.device.queue.submit( [ encoder.finish() ] );
  50997. }
  50998. }
  50999. }
  51000. /**
  51001. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51002. *
  51003. * @augments SpotLight
  51004. */
  51005. class IESSpotLight extends SpotLight {
  51006. /**
  51007. * Constructs a new IES spot light.
  51008. *
  51009. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51010. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51011. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51012. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51013. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51014. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51015. */
  51016. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51017. super( color, intensity, distance, angle, penumbra, decay );
  51018. /**
  51019. * TODO
  51020. *
  51021. * @type {?Texture}
  51022. * @default null
  51023. */
  51024. this.iesMap = null;
  51025. }
  51026. copy( source, recursive ) {
  51027. super.copy( source, recursive );
  51028. this.iesMap = source.iesMap;
  51029. return this;
  51030. }
  51031. }
  51032. /**
  51033. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51034. *
  51035. * @augments SpotLight
  51036. */
  51037. class ProjectorLight extends SpotLight {
  51038. /**
  51039. * Constructs a new projector light.
  51040. *
  51041. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51042. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51043. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51044. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51045. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51046. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51047. */
  51048. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51049. super( color, intensity, distance, angle, penumbra, decay );
  51050. /**
  51051. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  51052. *
  51053. * @type {number}
  51054. * @default null
  51055. */
  51056. this.aspect = null;
  51057. }
  51058. copy( source, recursive ) {
  51059. super.copy( source, recursive );
  51060. this.aspect = source.aspect;
  51061. return this;
  51062. }
  51063. }
  51064. /**
  51065. * This version of a node library represents the standard version
  51066. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  51067. * techniques and materials to node-based implementations.
  51068. *
  51069. * @private
  51070. * @augments NodeLibrary
  51071. */
  51072. class StandardNodeLibrary extends NodeLibrary {
  51073. /**
  51074. * Constructs a new standard node library.
  51075. */
  51076. constructor() {
  51077. super();
  51078. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  51079. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  51080. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  51081. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  51082. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  51083. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  51084. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  51085. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  51086. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  51087. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  51088. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  51089. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  51090. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  51091. this.addLight( PointLightNode, PointLight );
  51092. this.addLight( DirectionalLightNode, DirectionalLight );
  51093. this.addLight( RectAreaLightNode, RectAreaLight );
  51094. this.addLight( SpotLightNode, SpotLight );
  51095. this.addLight( AmbientLightNode, AmbientLight );
  51096. this.addLight( HemisphereLightNode, HemisphereLight );
  51097. this.addLight( LightProbeNode, LightProbe );
  51098. this.addLight( IESSpotLightNode, IESSpotLight );
  51099. this.addLight( ProjectorLightNode, ProjectorLight );
  51100. this.addToneMapping( linearToneMapping, LinearToneMapping );
  51101. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  51102. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  51103. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  51104. this.addToneMapping( agxToneMapping, AgXToneMapping );
  51105. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  51106. }
  51107. }
  51108. /*
  51109. const debugHandler = {
  51110. get: function ( target, name ) {
  51111. // Add |update
  51112. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  51113. return target[ name ];
  51114. }
  51115. };
  51116. */
  51117. /**
  51118. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  51119. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  51120. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  51121. *
  51122. * @augments Renderer
  51123. */
  51124. class WebGPURenderer extends Renderer {
  51125. /**
  51126. * WebGPURenderer options.
  51127. *
  51128. * @typedef {Object} WebGPURenderer~Options
  51129. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  51130. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  51131. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  51132. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  51133. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  51134. * @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.
  51135. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  51136. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  51137. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  51138. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  51139. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  51140. */
  51141. /**
  51142. * Constructs a new WebGPU renderer.
  51143. *
  51144. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  51145. */
  51146. constructor( parameters = {} ) {
  51147. let BackendClass;
  51148. if ( parameters.forceWebGL ) {
  51149. BackendClass = WebGLBackend;
  51150. } else {
  51151. BackendClass = WebGPUBackend;
  51152. parameters.getFallback = () => {
  51153. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  51154. return new WebGLBackend( parameters );
  51155. };
  51156. }
  51157. const backend = new BackendClass( parameters );
  51158. //super( new Proxy( backend, debugHandler ) );
  51159. super( backend, parameters );
  51160. /**
  51161. * The generic default value is overwritten with the
  51162. * standard node library for type mapping.
  51163. *
  51164. * @type {StandardNodeLibrary}
  51165. */
  51166. this.library = new StandardNodeLibrary();
  51167. /**
  51168. * This flag can be used for type testing.
  51169. *
  51170. * @type {boolean}
  51171. * @readonly
  51172. * @default true
  51173. */
  51174. this.isWebGPURenderer = true;
  51175. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  51176. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  51177. }
  51178. }
  51179. }
  51180. /**
  51181. * A specialized group which enables applications access to the
  51182. * Render Bundle API of WebGPU. The group with all its descendant nodes
  51183. * are considered as one render bundle and processed as such by
  51184. * the renderer.
  51185. *
  51186. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  51187. * With a WebGL backend, the group can technically be rendered but without
  51188. * any performance improvements.
  51189. *
  51190. * @augments Group
  51191. */
  51192. class BundleGroup extends Group {
  51193. /**
  51194. * Constructs a new bundle group.
  51195. */
  51196. constructor() {
  51197. super();
  51198. /**
  51199. * This flag can be used for type testing.
  51200. *
  51201. * @type {boolean}
  51202. * @readonly
  51203. * @default true
  51204. */
  51205. this.isBundleGroup = true;
  51206. /**
  51207. * This property is only relevant for detecting types
  51208. * during serialization/deserialization. It should always
  51209. * match the class name.
  51210. *
  51211. * @type {string}
  51212. * @readonly
  51213. * @default 'BundleGroup'
  51214. */
  51215. this.type = 'BundleGroup';
  51216. /**
  51217. * Whether the bundle is static or not. When set to `true`, the structure
  51218. * is assumed to be static and does not change. E.g. no new objects are
  51219. * added to the group
  51220. *
  51221. * If a change is required, an update can still be forced by setting the
  51222. * `needsUpdate` flag to `true`.
  51223. *
  51224. * @type {boolean}
  51225. * @default true
  51226. */
  51227. this.static = true;
  51228. /**
  51229. * The bundle group's version.
  51230. *
  51231. * @type {number}
  51232. * @readonly
  51233. * @default 0
  51234. */
  51235. this.version = 0;
  51236. }
  51237. /**
  51238. * Set this property to `true` when the bundle group has changed.
  51239. *
  51240. * @type {boolean}
  51241. * @default false
  51242. * @param {boolean} value
  51243. */
  51244. set needsUpdate( value ) {
  51245. if ( value === true ) this.version ++;
  51246. }
  51247. }
  51248. /**
  51249. * This module is responsible to manage the post processing setups in apps.
  51250. * You usually create a single instance of this class and use it to define
  51251. * the output of your post processing effect chain.
  51252. * ```js
  51253. * const postProcessing = new PostProcessing( renderer );
  51254. *
  51255. * const scenePass = pass( scene, camera );
  51256. *
  51257. * postProcessing.outputNode = scenePass;
  51258. * ```
  51259. *
  51260. * Note: This module can only be used with `WebGPURenderer`.
  51261. */
  51262. class PostProcessing {
  51263. /**
  51264. * Constructs a new post processing management module.
  51265. *
  51266. * @param {Renderer} renderer - A reference to the renderer.
  51267. * @param {Node<vec4>} outputNode - An optional output node.
  51268. */
  51269. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  51270. /**
  51271. * A reference to the renderer.
  51272. *
  51273. * @type {Renderer}
  51274. */
  51275. this.renderer = renderer;
  51276. /**
  51277. * A node which defines the final output of the post
  51278. * processing. This is usually the last node in a chain
  51279. * of effect nodes.
  51280. *
  51281. * @type {Node<vec4>}
  51282. */
  51283. this.outputNode = outputNode;
  51284. /**
  51285. * Whether the default output tone mapping and color
  51286. * space transformation should be enabled or not.
  51287. *
  51288. * It is enabled by default by it must be disabled when
  51289. * effects must be executed after tone mapping and color
  51290. * space conversion. A typical example is FXAA which
  51291. * requires sRGB input.
  51292. *
  51293. * When set to `false`, the app must control the output
  51294. * transformation with `RenderOutputNode`.
  51295. *
  51296. * ```js
  51297. * const outputPass = renderOutput( scenePass );
  51298. * ```
  51299. *
  51300. * @type {boolean}
  51301. */
  51302. this.outputColorTransform = true;
  51303. /**
  51304. * Must be set to `true` when the output node changes.
  51305. *
  51306. * @type {Node<vec4>}
  51307. */
  51308. this.needsUpdate = true;
  51309. const material = new NodeMaterial();
  51310. material.name = 'PostProcessing';
  51311. /**
  51312. * The full screen quad that is used to render
  51313. * the effects.
  51314. *
  51315. * @private
  51316. * @type {QuadMesh}
  51317. */
  51318. this._quadMesh = new QuadMesh( material );
  51319. }
  51320. /**
  51321. * When `PostProcessing` is used to apply post processing effects,
  51322. * the application must use this version of `render()` inside
  51323. * its animation loop (not the one from the renderer).
  51324. */
  51325. render() {
  51326. this._update();
  51327. const renderer = this.renderer;
  51328. const toneMapping = renderer.toneMapping;
  51329. const outputColorSpace = renderer.outputColorSpace;
  51330. renderer.toneMapping = NoToneMapping;
  51331. renderer.outputColorSpace = LinearSRGBColorSpace;
  51332. //
  51333. const currentXR = renderer.xr.enabled;
  51334. renderer.xr.enabled = false;
  51335. this._quadMesh.render( renderer );
  51336. renderer.xr.enabled = currentXR;
  51337. //
  51338. renderer.toneMapping = toneMapping;
  51339. renderer.outputColorSpace = outputColorSpace;
  51340. }
  51341. /**
  51342. * Frees internal resources.
  51343. */
  51344. dispose() {
  51345. this._quadMesh.material.dispose();
  51346. }
  51347. /**
  51348. * Updates the state of the module.
  51349. *
  51350. * @private
  51351. */
  51352. _update() {
  51353. if ( this.needsUpdate === true ) {
  51354. const renderer = this.renderer;
  51355. const toneMapping = renderer.toneMapping;
  51356. const outputColorSpace = renderer.outputColorSpace;
  51357. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  51358. this._quadMesh.material.needsUpdate = true;
  51359. this.needsUpdate = false;
  51360. }
  51361. }
  51362. /**
  51363. * When `PostProcessing` is used to apply post processing effects,
  51364. * the application must use this version of `renderAsync()` inside
  51365. * its animation loop (not the one from the renderer).
  51366. *
  51367. * @async
  51368. * @return {Promise} A Promise that resolves when the render has been finished.
  51369. */
  51370. async renderAsync() {
  51371. this._update();
  51372. const renderer = this.renderer;
  51373. const toneMapping = renderer.toneMapping;
  51374. const outputColorSpace = renderer.outputColorSpace;
  51375. renderer.toneMapping = NoToneMapping;
  51376. renderer.outputColorSpace = LinearSRGBColorSpace;
  51377. //
  51378. const currentXR = renderer.xr.enabled;
  51379. renderer.xr.enabled = false;
  51380. await this._quadMesh.renderAsync( renderer );
  51381. renderer.xr.enabled = currentXR;
  51382. //
  51383. renderer.toneMapping = toneMapping;
  51384. renderer.outputColorSpace = outputColorSpace;
  51385. }
  51386. }
  51387. /**
  51388. * This special type of texture is intended for compute shaders.
  51389. * It can be used to compute the data of a texture with a compute shader.
  51390. *
  51391. * Note: This type of texture can only be used with `WebGPURenderer`
  51392. * and a WebGPU backend.
  51393. *
  51394. * @augments Texture
  51395. */
  51396. class StorageTexture extends Texture {
  51397. /**
  51398. * Constructs a new storage texture.
  51399. *
  51400. * @param {number} [width=1] - The storage texture's width.
  51401. * @param {number} [height=1] - The storage texture's height.
  51402. */
  51403. constructor( width = 1, height = 1 ) {
  51404. super();
  51405. /**
  51406. * The image object which just represents the texture's dimension.
  51407. *
  51408. * @type {{width: number, height: number}}
  51409. */
  51410. this.image = { width, height };
  51411. /**
  51412. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  51413. *
  51414. * @type {number}
  51415. */
  51416. this.magFilter = LinearFilter;
  51417. /**
  51418. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  51419. *
  51420. * @type {number}
  51421. */
  51422. this.minFilter = LinearFilter;
  51423. /**
  51424. * This flag can be used for type testing.
  51425. *
  51426. * @type {boolean}
  51427. * @readonly
  51428. * @default true
  51429. */
  51430. this.isStorageTexture = true;
  51431. }
  51432. }
  51433. /**
  51434. * This special type of buffer attribute is intended for compute shaders.
  51435. * It can be used to encode draw parameters for indirect draw calls.
  51436. *
  51437. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  51438. * and a WebGPU backend.
  51439. *
  51440. * @augments StorageBufferAttribute
  51441. */
  51442. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  51443. /**
  51444. * Constructs a new storage buffer attribute.
  51445. *
  51446. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  51447. * The subsequent parameter is then obsolete.
  51448. * @param {number} itemSize - The item size.
  51449. */
  51450. constructor( count, itemSize ) {
  51451. super( count, itemSize, Uint32Array );
  51452. /**
  51453. * This flag can be used for type testing.
  51454. *
  51455. * @type {boolean}
  51456. * @readonly
  51457. * @default true
  51458. */
  51459. this.isIndirectStorageBufferAttribute = true;
  51460. }
  51461. }
  51462. /**
  51463. * A loader for loading node objects in the three.js JSON Object/Scene format.
  51464. *
  51465. * @augments Loader
  51466. */
  51467. class NodeLoader extends Loader {
  51468. /**
  51469. * Constructs a new node loader.
  51470. *
  51471. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51472. */
  51473. constructor( manager ) {
  51474. super( manager );
  51475. /**
  51476. * Represents a dictionary of textures.
  51477. *
  51478. * @type {Object<string,Texture>}
  51479. */
  51480. this.textures = {};
  51481. /**
  51482. * Represents a dictionary of node types.
  51483. *
  51484. * @type {Object<string,Node.constructor>}
  51485. */
  51486. this.nodes = {};
  51487. }
  51488. /**
  51489. * Loads the node definitions from the given URL.
  51490. *
  51491. * @param {string} url - The path/URL of the file to be loaded.
  51492. * @param {Function} onLoad - Will be called when load completes.
  51493. * @param {Function} onProgress - Will be called while load progresses.
  51494. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  51495. */
  51496. load( url, onLoad, onProgress, onError ) {
  51497. const loader = new FileLoader( this.manager );
  51498. loader.setPath( this.path );
  51499. loader.setRequestHeader( this.requestHeader );
  51500. loader.setWithCredentials( this.withCredentials );
  51501. loader.load( url, ( text ) => {
  51502. try {
  51503. onLoad( this.parse( JSON.parse( text ) ) );
  51504. } catch ( e ) {
  51505. if ( onError ) {
  51506. onError( e );
  51507. } else {
  51508. console.error( e );
  51509. }
  51510. this.manager.itemError( url );
  51511. }
  51512. }, onProgress, onError );
  51513. }
  51514. /**
  51515. * Parse the node dependencies for the loaded node.
  51516. *
  51517. * @param {Array<Object>} [json] - The JSON definition
  51518. * @return {Object<string,Node>} A dictionary with node dependencies.
  51519. */
  51520. parseNodes( json ) {
  51521. const nodes = {};
  51522. if ( json !== undefined ) {
  51523. for ( const nodeJSON of json ) {
  51524. const { uuid, type } = nodeJSON;
  51525. nodes[ uuid ] = this.createNodeFromType( type );
  51526. nodes[ uuid ].uuid = uuid;
  51527. }
  51528. const meta = { nodes, textures: this.textures };
  51529. for ( const nodeJSON of json ) {
  51530. nodeJSON.meta = meta;
  51531. const node = nodes[ nodeJSON.uuid ];
  51532. node.deserialize( nodeJSON );
  51533. delete nodeJSON.meta;
  51534. }
  51535. }
  51536. return nodes;
  51537. }
  51538. /**
  51539. * Parses the node from the given JSON.
  51540. *
  51541. * @param {Object} json - The JSON definition
  51542. * @param {string} json.type - The node type.
  51543. * @param {string} json.uuid - The node UUID.
  51544. * @param {Array<Object>} [json.nodes] - The node dependencies.
  51545. * @param {Object} [json.meta] - The meta data.
  51546. * @return {Node} The parsed node.
  51547. */
  51548. parse( json ) {
  51549. const node = this.createNodeFromType( json.type );
  51550. node.uuid = json.uuid;
  51551. const nodes = this.parseNodes( json.nodes );
  51552. const meta = { nodes, textures: this.textures };
  51553. json.meta = meta;
  51554. node.deserialize( json );
  51555. delete json.meta;
  51556. return node;
  51557. }
  51558. /**
  51559. * Defines the dictionary of textures.
  51560. *
  51561. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  51562. * @return {NodeLoader} A reference to this loader.
  51563. */
  51564. setTextures( value ) {
  51565. this.textures = value;
  51566. return this;
  51567. }
  51568. /**
  51569. * Defines the dictionary of node types.
  51570. *
  51571. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  51572. * @return {NodeLoader} A reference to this loader.
  51573. */
  51574. setNodes( value ) {
  51575. this.nodes = value;
  51576. return this;
  51577. }
  51578. /**
  51579. * Creates a node object from the given type.
  51580. *
  51581. * @param {string} type - The node type.
  51582. * @return {Node} The created node instance.
  51583. */
  51584. createNodeFromType( type ) {
  51585. if ( this.nodes[ type ] === undefined ) {
  51586. console.error( 'THREE.NodeLoader: Node type not found:', type );
  51587. return float();
  51588. }
  51589. return nodeObject( new this.nodes[ type ]() );
  51590. }
  51591. }
  51592. /**
  51593. * A special type of material loader for loading node materials.
  51594. *
  51595. * @augments MaterialLoader
  51596. */
  51597. class NodeMaterialLoader extends MaterialLoader {
  51598. /**
  51599. * Constructs a new node material loader.
  51600. *
  51601. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51602. */
  51603. constructor( manager ) {
  51604. super( manager );
  51605. /**
  51606. * Represents a dictionary of node types.
  51607. *
  51608. * @type {Object<string,Node.constructor>}
  51609. */
  51610. this.nodes = {};
  51611. /**
  51612. * Represents a dictionary of node material types.
  51613. *
  51614. * @type {Object<string,NodeMaterial.constructor>}
  51615. */
  51616. this.nodeMaterials = {};
  51617. }
  51618. /**
  51619. * Parses the node material from the given JSON.
  51620. *
  51621. * @param {Object} json - The JSON definition
  51622. * @return {NodeMaterial}. The parsed material.
  51623. */
  51624. parse( json ) {
  51625. const material = super.parse( json );
  51626. const nodes = this.nodes;
  51627. const inputNodes = json.inputNodes;
  51628. for ( const property in inputNodes ) {
  51629. const uuid = inputNodes[ property ];
  51630. material[ property ] = nodes[ uuid ];
  51631. }
  51632. return material;
  51633. }
  51634. /**
  51635. * Defines the dictionary of node types.
  51636. *
  51637. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  51638. * @return {NodeLoader} A reference to this loader.
  51639. */
  51640. setNodes( value ) {
  51641. this.nodes = value;
  51642. return this;
  51643. }
  51644. /**
  51645. * Defines the dictionary of node material types.
  51646. *
  51647. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  51648. * @return {NodeLoader} A reference to this loader.
  51649. */
  51650. setNodeMaterials( value ) {
  51651. this.nodeMaterials = value;
  51652. return this;
  51653. }
  51654. /**
  51655. * Creates a node material from the given type.
  51656. *
  51657. * @param {string} type - The node material type.
  51658. * @return {Node} The created node material instance.
  51659. */
  51660. createMaterialFromType( type ) {
  51661. const materialClass = this.nodeMaterials[ type ];
  51662. if ( materialClass !== undefined ) {
  51663. return new materialClass();
  51664. }
  51665. return super.createMaterialFromType( type );
  51666. }
  51667. }
  51668. /**
  51669. * A special type of object loader for loading 3D objects using
  51670. * node materials.
  51671. *
  51672. * @augments ObjectLoader
  51673. */
  51674. class NodeObjectLoader extends ObjectLoader {
  51675. /**
  51676. * Constructs a new node object loader.
  51677. *
  51678. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51679. */
  51680. constructor( manager ) {
  51681. super( manager );
  51682. /**
  51683. * Represents a dictionary of node types.
  51684. *
  51685. * @type {Object<string,Node.constructor>}
  51686. */
  51687. this.nodes = {};
  51688. /**
  51689. * Represents a dictionary of node material types.
  51690. *
  51691. * @type {Object<string,NodeMaterial.constructor>}
  51692. */
  51693. this.nodeMaterials = {};
  51694. /**
  51695. * A reference to hold the `nodes` JSON property.
  51696. *
  51697. * @private
  51698. * @type {?Object[]}
  51699. */
  51700. this._nodesJSON = null;
  51701. }
  51702. /**
  51703. * Defines the dictionary of node types.
  51704. *
  51705. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  51706. * @return {NodeObjectLoader} A reference to this loader.
  51707. */
  51708. setNodes( value ) {
  51709. this.nodes = value;
  51710. return this;
  51711. }
  51712. /**
  51713. * Defines the dictionary of node material types.
  51714. *
  51715. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  51716. * @return {NodeObjectLoader} A reference to this loader.
  51717. */
  51718. setNodeMaterials( value ) {
  51719. this.nodeMaterials = value;
  51720. return this;
  51721. }
  51722. /**
  51723. * Parses the node objects from the given JSON.
  51724. *
  51725. * @param {Object} json - The JSON definition
  51726. * @param {Function} onLoad - The onLoad callback function.
  51727. * @return {Object3D}. The parsed 3D object.
  51728. */
  51729. parse( json, onLoad ) {
  51730. this._nodesJSON = json.nodes;
  51731. const data = super.parse( json, onLoad );
  51732. this._nodesJSON = null; // dispose
  51733. return data;
  51734. }
  51735. /**
  51736. * Parses the node objects from the given JSON and textures.
  51737. *
  51738. * @param {Object[]} json - The JSON definition
  51739. * @param {Object<string,Texture>} textures - The texture library.
  51740. * @return {Object<string,Node>}. The parsed nodes.
  51741. */
  51742. parseNodes( json, textures ) {
  51743. if ( json !== undefined ) {
  51744. const loader = new NodeLoader();
  51745. loader.setNodes( this.nodes );
  51746. loader.setTextures( textures );
  51747. return loader.parseNodes( json );
  51748. }
  51749. return {};
  51750. }
  51751. /**
  51752. * Parses the node objects from the given JSON and textures.
  51753. *
  51754. * @param {Object} json - The JSON definition
  51755. * @param {Object<string,Texture>} textures - The texture library.
  51756. * @return {Object<string,NodeMaterial>}. The parsed materials.
  51757. */
  51758. parseMaterials( json, textures ) {
  51759. const materials = {};
  51760. if ( json !== undefined ) {
  51761. const nodes = this.parseNodes( this._nodesJSON, textures );
  51762. const loader = new NodeMaterialLoader();
  51763. loader.setTextures( textures );
  51764. loader.setNodes( nodes );
  51765. loader.setNodeMaterials( this.nodeMaterials );
  51766. for ( let i = 0, l = json.length; i < l; i ++ ) {
  51767. const data = json[ i ];
  51768. materials[ data.uuid ] = loader.parse( data );
  51769. }
  51770. }
  51771. return materials;
  51772. }
  51773. }
  51774. /**
  51775. * In earlier three.js versions, clipping was defined globally
  51776. * on the renderer or on material level. This special version of
  51777. * `THREE.Group` allows to encode the clipping state into the scene
  51778. * graph. Meaning if you create an instance of this group, all
  51779. * descendant 3D objects will be affected by the respective clipping
  51780. * planes.
  51781. *
  51782. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  51783. *
  51784. * @augments Group
  51785. */
  51786. class ClippingGroup extends Group {
  51787. /**
  51788. * Constructs a new clipping group.
  51789. */
  51790. constructor() {
  51791. super();
  51792. /**
  51793. * This flag can be used for type testing.
  51794. *
  51795. * @type {boolean}
  51796. * @readonly
  51797. * @default true
  51798. */
  51799. this.isClippingGroup = true;
  51800. /**
  51801. * An array with clipping planes.
  51802. *
  51803. * @type {Array<Plane>}
  51804. */
  51805. this.clippingPlanes = [];
  51806. /**
  51807. * Whether clipping should be enabled or not.
  51808. *
  51809. * @type {boolean}
  51810. * @default true
  51811. */
  51812. this.enabled = true;
  51813. /**
  51814. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  51815. *
  51816. * @type {boolean}
  51817. * @default false
  51818. */
  51819. this.clipIntersection = false;
  51820. /**
  51821. * Whether shadows should be clipped or not.
  51822. *
  51823. * @type {boolean}
  51824. * @default false
  51825. */
  51826. this.clipShadows = false;
  51827. }
  51828. }
  51829. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号